CGGeometry Reference

CGRectUnion
CGRectUnion接受两个CGRect结构体作为参数并且返回一个能够包含这两个矩形的最小矩形。听起来可能没什么,我相信你也可以用几行代码轻松实现这个功能,不过 CGGeometry 做的是给你提供一些方法让你的代码更干净、可读性更强。

如果你把下面代码片段加到一个 view controller 的viewDidLoad方法中,你将在模拟器中看到如下结果。那个灰色的矩形就是使用CGRectUnion的结果。

// CGRectUnion
CGRect frame1 = CGRectMake(80.0, 100.0, 150.0, 240.0);
CGRect frame2 = CGRectMake(140.0, 240.0, 120.0, 120.0);
CGRect frame3 = CGRectUnion(frame1, frame2);
 
UIView *view1 = [[UIView alloc] initWithFrame:frame1];
[view1 setBackgroundColor:[UIColor redColor]];
 
UIView *view2 = [[UIView alloc] initWithFrame:frame2];
[view2 setBackgroundColor:[UIColor orangeColor]];
 
UIView *view3 = [[UIView alloc] initWithFrame:frame3];
[view3 setBackgroundColor:[UIColor grayColor]];
 
[self.view addSubview:view3];
[self.view addSubview:view2];
[self.view addSubview:view1];

CGRectDivide

另一个有用的方法是CGRectDivide,它帮你把一个给定矩形分割成两个。看看下面的代码和截图来了解它是怎么运作的。

// CGRectDivide
CGRect frame = CGRectMake(10.0, 50.0, 300.0, 300.0);
CGRect part1;
CGRect part2;
CGRectDivide(frame, &part1, &part2, 100.0, CGRectMaxYEdge);
 
UIView *view1 = [[UIView alloc] initWithFrame:frame];
[view1 setBackgroundColor:[UIColor grayColor]];
 
UIView *view2 = [[UIView alloc] initWithFrame:part1];
[view2 setBackgroundColor:[UIColor orangeColor]];
 
UIView *view3 = [[UIView alloc] initWithFrame:part2];
[view3 setBackgroundColor:[UIColor redColor]];
 
[self.view addSubview:view1];
[self.view addSubview:view2];
[self.view addSubview:view3];

如果你不使用CGRectDivide来计算红色和橙色矩形的话,你可能要多谢几十行代码。不信你就试试。

比较和包含

用下面六个方法来比较几何结构和检查包含关系非常简单。

  • CGPointEqualToPoint

  • CGSizeEqualToSize

  • CGRectEqualToRect

  • CGRectIntersectsRect

  • CGRectContainsPoint

  • CGRectContainsRect

CGGeometry Reference 还有一些其他宝贝,比如CGPointCreateDictionaryRepresentation可以用来将一个 CGPoint 结构体转换为一个 CGDictionaryRefCGRectIsEmpty可以用来检查一个矩形的宽高是否都为零。更多详情请看[《CGGeometry Reference 文档》]()

来源:https://segmentfault.com/a/1190000004695617?hmsr=toutiao.io

posted @ 2016-10-28 11:18  Dadada胖纸er  阅读(218)  评论(0编辑  收藏  举报