# CGPoint,CGSize,CGRect

在iOS开发中经常需要处理点,大小以及矩形,对应的数据结构分别为CGPoint,CGSize,CGRect，这些数据结构都是C结构体,定义分别如下:

CGPoint {
CGFloat x;

CGFloat y;

};

CGSize {
CGFloat width;

CGFloat height;

};

struct CGRect {
CGPoint origin;

CGSize size;

};

1.创建CGPoint,CGSize,CGRect

CGSize size = CGSizeMake (10.0, 20.0);

CGPoint center = CGPointMake (60.0, 240.0);

CGRect bounds = CGRectMake (5.0, 10.0, 100.0, 200.0);

2.判断两个点，大小，矩形是否相等

bool CGPointEqualToPoint (CGPoint point1, CGPoint point2);

bool CGSizeEqualToSize (CGSize size1, CGSize size2);

bool CGRectEqualToRect (CGRect rect1, CGRect rect2);

CGPoint,CGSize,CGRect的内部数据都是CGPoint,对于浮点数,由于可能存在舍入误差，不能直接判断两者是否相等，而应该判断两个值的差是否足够小。使用上述方法可以避免手工做这些判断,简化代码。

3. 获取矩形边界,中点坐标值，长宽

CGFloat CGRectGetMinX(CGRect rect);

CGFloat CGRectGetMaxX(CGRect rect);

CGFloat CGRectGetMinY(CGRect rect);

CGFloat CGRectGetMaxY(CGRect rect);

CGFloat CGRectGetMidX(CGRect rect);

CGFloat CGRectGetMidY(CGRect rect);

CGFloat CGRectGetWidth(CGRect rect);

CGFloat CGRectGetHeight(CGRect rect);

4.对称缩进CGRect

CGRect aRectangle = CGRectMake(0, 0, 100, 200);

CGRect smallerRectangle = CGRectInset(aRectangle, 10, 20);

// result origin (10, 20) and size (80, 160)

5. 非对称缩进CGRect

CGRect rect = CGRectMake(0, 0, 100, 200);

UIEdgeInsets contentInsets = UIEdgeInsetsMake(10, 20, 30, 40);

CGRect result = UIEdgeInsetsInsetRect(rect, contentInsets);

//result origin(20,10) and size(40,160)

6. 调整小数像素CGRect到整数像素

CGRect rect = CGRectMake(5, 7.5, 50, 29);

CGRect result = CGRectIntegral(rect);

//result origin(5,7) and size(50,30)

7. 检查矩形内是否包含某点

CGRect enemyRect = CGRectMake(0, 0, 100, 200);

CGPoint hitPoint = CGPointMake(50, 50);

if(CGRectContainsPoint(enemyRect, hitPoint))    {
// YES!

}

8.检查两矩形是否相交

CGRect playerRect = CCRectMake(200, 300, 10, 10);

CGRect mineRect = CGRectMake(10, 10, 20, 20);

if(CGRectIntersectsRect(playerRect, mineRect))    {
// YES!

}

9. CGRect与NSString 转换

CGRect rect = CGRectMake(0, 0, 100, 200);

NSString *rectString = NSStringFromCGRect(rect))

CGRect newRect = CGRectFromString(rectString);

10.CGRect与NSDictionary转换

CGRect rect = CGRectMake(0, 0, 100, 200);

CFDictionaryRef frameDictRef = CGRectCreateDictionaryRepresentation(rect);

NSDictionary*frameDict = [NSDictionary dictionaryWithDictionary:(NSDictionary*)frameDictRef]; // autoreleased

CFRelease(frameDictRef);

NSLog(@"%@", frameDict);

CGRect newRect;

CGRectMakeWithDictionaryRepresentation((CFDictionaryRef)frameDict, &rect);

10. CGRect与NSValue转换

CGRect rect = CGRectMake(0, 0, 100, 200);

NSValue *value = [NSValue valueWithCGRect:rect];

CGRect newRect = [value rectValue];

posted @ 2021-09-07 17:29  brave-sailor  阅读(9)  评论(0编辑  收藏  举报