How do I create a CGRect from a CGPoint and CGSize?
Asked Answered
P

4

53

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.

Pape answered 21/8, 2012 at 21:57 Comment(0)
N
125

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)
Neighborly answered 21/8, 2012 at 21:59 Comment(7)
What kind of operator are you using here in your second example?Hecatomb
Just the normal assignment operator.Neighborly
I mean the curly brackets. Is this some sort of macro. I know about the native NSDictionary @{} and NSArray @[] operator but this one looks new to me.Hecatomb
It's a compound literal. They are part of C, standardised in C99.Neighborly
In XCODE 5 it raises: expected expression. This is correct syntax: (CGRect){aPoint, aSize}Thiamine
@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.Neighborly
I'm passing as argument so thats the answer ;)Thiamine
S
7

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} };
Scornik answered 11/12, 2014 at 21:6 Comment(0)
R
2
CGRectMake(yourPoint.x, yourPoint.y, yourSize.width, yourSize.height);
Reynaud answered 21/8, 2012 at 21:57 Comment(0)
V
0

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;
)}
Violoncellist answered 19/1, 2016 at 18:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.