How do I create a CGRect from a CGPoint and CGSize?
67,625
Solution 1
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)
Solution 2
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} };
Solution 3
CGRectMake(yourPoint.x, yourPoint.y, yourSize.width, yourSize.height);
Author by
inorganik
Making digital stuff, searching for excellent music and drinking craft beer along the way.
Updated on July 15, 2022Comments
-
inorganik almost 2 years
I need to create a frame for a
UIImageView
from a varying collection ofCGSize
andCGPoint
, both values will always be different depending on user's choices. So how can I make aCGRect
form aCGPoint
and aCGSize
? Thank you in advance. -
Besi over 11 yearsWhat kind of operator are you using here in your second example?
-
Lomithrani over 11 yearsJust the normal assignment operator.
-
Besi over 11 yearsI mean the curly brackets. Is this some sort of macro. I know about the native
NSDictionary @{}
andNSArray @[]
operator but this one looks new to me. -
Lomithrani over 11 yearsIt's a compound literal. They are part of C, standardised in C99.
-
Pion about 10 yearsIn XCODE 5 it raises: expected expression. This is correct syntax: (CGRect){aPoint, aSize}
-
Lomithrani about 10 years@Pion: No it doesn't. That code works fine and doesn't produce any warnings in the latest version of Xcode. I'm assuming you're using different code, doing something other than initialising a local variable. You need the cast if you want to do something like pass a compound literal as a method argument, but just for initialising a local variable, you don't need the cast.
-
Pion about 10 yearsI'm passing as argument so thats the answer ;)