view的三個相關屬性
UIView 的 frame 屬性使用的很頻繁,但是 bounds 這個屬性卻一直用的不多。最近的工作內(nèi)容涉及 bounds 比較多,抽空研究了一下。先說結論,
- frame : 當前 view 在其 superView 中的位置及大小
- bounds : 是 view 自身的坐標系(為其 subViews 提供的坐標系)
- center : 該view的中心點在父view坐標系統(tǒng)中的位置
@interface UIView(UIViewGeometry)
// animatable. do not use frame if view is transformed since it will not correctly reflect the actual location of the view. use bounds + center instead.
@property(nonatomic) CGRect frame;
// use bounds/center and not frame if non-identity transform. if bounds dimension is odd, center may be have fractional part
@property(nonatomic) CGRect bounds; // default bounds is zero origin, frame size. animatable
@property(nonatomic) CGPoint center; // center is center of frame. animatable
bounds與坐標系
bounds 的 origin 默認為 (0, 0) 點,除非你更改了它。
可以設想,在保持一個 view 的 subViews 的 frame 不變的情況下,改變 view.bounds 將改變 subViews的位置。如果要同時移動所有 subViews 的話,改 bounds 的 origin 是一個很簡單的辦法。示例,
執(zhí)行以下代碼,
UIView *viewA = [[UIView alloc] initWithFrame:CGRectMake(50, 50, 200, 200)];
viewA.backgroundColor = [UIColor blackColor];
[self.view addSubview:viewA];
viewA.bounds = CGRectMake(-100, -100, 200, 200);
UIView *viewB = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
viewB.backgroundColor = [UIColor grayColor];
[viewA addSubview:viewB];

結果可以看到,由于 viewA.bounds.origin 為 (-100, -100),所以 viewA 坐標系的 (0, 0) 被挪到了它的中心上去,于是 viewB 的位置也跟著挪到了這里。
巧用center屬性移動view
我們知道 center 是當前 view 的 中心點在其 superView 坐標系中的位置。我們可以推測,如果將上例中 viewB 的 center 改為 (0, 0) 點的話,superView 將正好與 viewA 居中。
viewB.center = CGPointMake(0, 0);
NSLog(@"%@", NSStringFromCGRect(viewB.frame));
//test[9849:2271050] {{-25, -25}, {50, 50}}

增加代碼,運行,結果和預想的一致。而且 viewB.frame 由于受到 center 改變的影響,也發(fā)生了變化。
如果我們旋轉(zhuǎn) viewB 會怎樣呢?
添加代碼,執(zhí)行,打印 frame 和 bounds。
CGAffineTransform t = viewB.transform;
viewB.transform = CGAffineTransformRotate(t, M_PI_4);
//test[12009:2783329] frame -> {{-35.355339059327378, -35.355339059327378}, {70.710678118654755, 70.710678118654755}}
//test[12009:2783329] bounds -> {{0, 0}, {50, 50}}

旋轉(zhuǎn)之后 viewB.frame變大,為其形狀的外接的最小的矩形(與坐標系方向相同的矩形)。而 viewB.bounds 沒有變化。
歡迎來我的個站逛逛: http://alexyu.me/