CGRect, CGSize and CGPoint Functions

With an understanding ofC structures, and thedefinitions of CGRect, CGSize and CGPointbehind us, let’s look at a handful of functions for working with these structures.

CGRectMake and NSStringFromCGRect

With CGRectMake we can create a new CGRect structure. The rectangles below have differing starting points, however, each have a width and height of 100. The function NSStringFromCGRect returns a string object that defines the rectangle passed in as a parameter:

CGRect rect1 = CGRectMake(100, 100, 100, 100); CGRect rect2 = CGRectMake(190, 190, 100, 100); NSLog(@"rect1: %@", NSStringFromCGRect(rect1)); NSLog(@"rect2: %@", NSStringFromCGRect(rect2));

Note: The output of all examples are shown in the image at the bottom of this post.

CGRectIntersect

To determine if two rectangles intersect, you can write code as follows:

CGRect rect3 = CGRectMake(100, 100, 100, 100); CGRect rect4 = CGRectMake(190, 190, 100, 100); if (CGRectIntersectsRect(rect3, rect4) == 1) NSLog(@"The rectangles intersect"); else NSLog(@"The rectangles do not intersect"); NSLog(@"rect3: %@", NSStringFromCGRect(rect3)); NSLog(@"rect4: %@", NSStringFromCGRect(rect4));

CGRectInset

If you need to create a rectangle that is either larger or smaller than an existing rectangle, centered on the same point, try CGRectInset:

CGRect rect5 = CGRectMake(100, 100, 100, 100); // Use positive values for a smaller rectangle CGRect rect6 = CGRectInset(rect, 25, 25); NSLog(@"%rect5: %@", NSStringFromCGRect(rect5)); NSLog(@"%rect6: %@", NSStringFromCGRect(rect6)); ... CGRect rect7 = CGRectMake(100, 100, 100, 100); // Use negative values for a larger rectangle CGRect rect8 = CGRectInset(rect, -25, -25); NSLog(@"rect7: %@", NSStringFromCGRect(rect7)); NSLog(@"rect8: %@", NSStringFromCGRect(rect8));

CGRectFromString

A little more uncommon, is creating rectangles from a string, however, if the need arises:

NSString *str = @"{{0,0},{50,50}}"; CGRect rect9 = CGRectFromString(str); NSLog(@"rect9: %@", NSStringFromCGRect(rect9));

Functions for CGSize and CGPoint

As you would expect, there are similar functions to those above for working with CGSize and CGPoint:

  • CGSizeMake
  • CGSizeEqualToSize
  • CGPointMake
  • CGPointEqualToPoint

http://iphonedevelopertips.com/c/cgrect-cgsize-and-cgpoint-functions.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值