如何从CGPoint和CGSize创建CGRect?

时间:2012-08-21 21:57:07

标签: ios objective-c quartz-graphics cgpoint cgrectmake

我需要从UIImageViewCGSize的不同集合中为CGPoint创建一个框架,这两个值将始终根据用户的选择而有所不同。那么如何将CGRect表单设为CGPointCGSize?提前谢谢。

4 个答案:

答案 0 :(得分:113)

Objective-C的两个不同选项:

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

CGRect aRect = { aPoint, aSize };

斯威夫特3:

let aRect = CGRect(origin: aPoint, size: aSize)

答案 1 :(得分:4)

在@Jim的最佳答案的基础上,还可以使用此方法构建CGPoint和CGSize。所以这些也是制作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} };

答案 2 :(得分:3)

CGRectMake(yourPoint.x, yourPoint.y, yourSize.width, yourSize.height);

答案 3 :(得分:0)

你可以使用一些糖语法。例如:

这类似于构造块,可用于更易读的代码:

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;
)}