How do I create a CGRect from a CGPoint and CGSize

2019-03-09 06:51发布

I need to create a frame for a UIImageView from a varying collection of CGSize and CGPoint, both values will always be different depending on user's choices. So how can I make a CGRect form a CGPoint and a CGSize? Thank you in advance.

4条回答
戒情不戒烟
2楼-- · 2019-03-09 07:04

Two different options for Objective-C:

CGRect aRect = CGRectMake(aPoint.x, aPoint.y, aSize.width, aSize.height);

CGRect aRect = { aPoint, aSize };

Swift 3:

let aRect = CGRect(origin: aPoint, size: aSize)
查看更多
在下西门庆
3楼-- · 2019-03-09 07:10

you can use some sugar syntax. For example:

This is something like construction block you can use for more readable code:

CGRect rect = ({
   CGRect customCreationRect

   //make some calculations for each dimention
   customCreationRect.origin.x = CGRectGetMidX(yourFrame);
   customCreationRect.origin.y = CGRectGetMaxY(someOtherFrame);

   customCreationRect.size.width = CGRectGetHeight(yetAnotherFrame);
   customCreationRect.size.height = 400;

   //By just me some variable in the end this line will
   //be assigned to the rect va
   customCreationRect;
)}
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-03-09 07:25

Building on the most excellent answer from @Jim, one can also construct a CGPoint and a CGSize using this method. So these are also valid ways to make a CGRect:

CGRect aRect = { {aPoint.x, aPoint.y}, aSize };
CGrect aRect = { aPoint, {aSize.width, aSize.height} };
CGRect aRect = { {aPoint.x, aPoint.y}, {aSize.width, aSize.height} };
查看更多
地球回转人心会变
5楼-- · 2019-03-09 07:26
CGRectMake(yourPoint.x, yourPoint.y, yourSize.width, yourSize.height);
查看更多
登录 后发表回答