Define CGRectmake with CGPoint and/or CGSize
Solution 1
I think this is what you have in mind:
- (void) logRects
{
CGFloat
x = 10.0,
y = 20.0,
width = 50.0,
height = 60.0;
CGPoint point = {x, y};
CGSize size = {width, height};
CGRect rect1 = {1, 3, size};
CGRect rect2 = {point, size};
CGRect rect3 = {point, size.width, size.height};
//using designated (named) initialisers
CGRect rect4 = {.origin.x=3, .origin.y=5, .size = {100,100}};
//with designated initialisers, order doesn't matter
CGRect rect5 = {.size=size, .origin.x=3, .origin.y=5};
NSLog (@"rect1 %@",NSStringFromCGRect(rect1));
NSLog (@"rect2 %@",NSStringFromCGRect(rect2));
NSLog (@"rect3 %@",NSStringFromCGRect(rect3));
NSLog (@"rect4 %@",NSStringFromCGRect(rect4));
NSLog (@"rect5 %@",NSStringFromCGRect(rect5));
}
But note the discussion here:
Why use functions like CGRectMake?
This kind of compound literal syntax seems to me much easier to read and write, although functions have the edge when it comes to futureproofing ( + you get autocomplete).
update
see also this more recent q&a:
CGRect syntax I haven't seen before
Solution 2
CGRectMake(1, 3, size):
CGRectMake(1, 3, size.width, size.heigh)
CGRectMake(pointB, size):
CGRectMake(pointB.x, pointB.y, size.width, size.height)
CGRectMake(pointB, size.width, size.height):
CGRectMake(pointB.x, pointB.y, size.width, size.height)
A CGRect just looks like this:
struct CGRect {
CGPoint origin;
CGSize size;
};
typedef struct CGRect CGRect;
And CGPoint and CGSize just look like this:
struct CGPoint {
CGFloat x;
CGFloat y;
};
typedef struct CGPoint CGPoint;
struct CGSize {
CGFloat width;
CGFloat height;
};
typedef struct CGSize CGSize;
CGRectMake is the following function:
CG_INLINE CGRect
CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
CGRect rect;
rect.origin.x = x;
rect.origin.y = y;
rect.size.width = width;
rect.size.height = height;
return rect;
}
So instead of:
CGRect r = CGRectMake(pointB.x, pointB.y, size.width, size.height)
You can simply write:
CGRect r;
r.origin = pointB;
r.size = size;
If you feel like creating your own CGRectMake, feel free to do so:
CG_INLINE CGRect
MyPrivateCGRectMake(CGPoint p, CGSize s)
{
CGRect rect;
rect.origin = p;
rect.size = s;
return rect;
}
But there is no way you can change which arguments an already existing function accepts.
Related videos on Youtube
Plot
Updated on June 04, 2022Comments
-
Plot almost 2 years
This is a very simple question of which i can't seem to find the answer. How to do this :
CGRectMake(1, 3, size)
or
CGRectMake(pointB, size)
or
CGRectMake(pointB, size.width, size.height)
instead of
CGRectMake(self.someview.frame.origin.x, self.someview.frame.origin.y, self.someotherview.frame.size.width, self.someotherview.frame.size.height)
?? Thank you ! :)
EDIT:
The method
CGRectmake
takesCGFloat
. I would like it to takeCGSize
, and/orCGpoint
as arguments of the method.-
Lanorkin over 9 yearspossible duplicate of How do I create a CGRect from a CGPoint and CGSize?
-