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.

Alex Cio
  • 6,014
  • 5
  • 44
  • 74
inorganik
  • 24,255
  • 17
  • 90
  • 114

4 Answers4

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)
Jim
  • 72,985
  • 14
  • 101
  • 108
  • What kind of operator are you using here in your second example? – Besi Nov 22 '12 at 14:32
  • Just the normal assignment operator. – Jim Nov 23 '12 at 19:34
  • 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. – Besi Nov 24 '12 at 13:04
  • 7
    It's a compound literal. They are part of C, standardised in C99. – Jim Nov 24 '12 at 13:14
  • 6
    In XCODE 5 it raises: expected expression. This is correct syntax: (CGRect){aPoint, aSize} – Pion Feb 25 '14 at 20:03
  • 3
    @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. – Jim Feb 26 '14 at 12:03
  • 1
    I'm passing as argument so thats the answer ;) – Pion Feb 26 '14 at 15:01
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} };
coco
  • 2,998
  • 1
  • 35
  • 58
2
CGRectMake(yourPoint.x, yourPoint.y, yourSize.width, yourSize.height);
Besi
  • 22,579
  • 24
  • 131
  • 223
rooster117
  • 5,502
  • 1
  • 21
  • 19
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;
)}
Nikolay Shubenkov
  • 3,133
  • 1
  • 29
  • 31