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);
Share:
67,625
inorganik
Author by

inorganik

Making digital stuff, searching for excellent music and drinking craft beer along the way.

Updated on July 15, 2022

Comments

  • inorganik
    inorganik almost 2 years

    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.

  • Besi
    Besi over 11 years
    What kind of operator are you using here in your second example?
  • Lomithrani
    Lomithrani over 11 years
    Just the normal assignment operator.
  • Besi
    Besi over 11 years
    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.
  • Lomithrani
    Lomithrani over 11 years
    It's a compound literal. They are part of C, standardised in C99.
  • Pion
    Pion about 10 years
    In XCODE 5 it raises: expected expression. This is correct syntax: (CGRect){aPoint, aSize}
  • Lomithrani
    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
    Pion about 10 years
    I'm passing as argument so thats the answer ;)