UIView的bounds到底是干嘛的?

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];

![](http://7xivcr.com1.z0.glb.clouddn.com/Screen Shot 2015-05-31 at 5.15.41 PM.png)

結果可以看到,由于 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}}

![](http://7xivcr.com1.z0.glb.clouddn.com/Screen Shot 2015-05-31 at 5.17.35 PM.png)

增加代碼,運行,結果和預想的一致。而且 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}}

![](http://7xivcr.com1.z0.glb.clouddn.com/Screen Shot 2015-06-01 at 10.54.20 AM.png)

旋轉(zhuǎn)之后 viewB.frame變大,為其形狀的外接的最小的矩形(與坐標系方向相同的矩形)。而 viewB.bounds 沒有變化。


歡迎來我的個站逛逛: http://alexyu.me/

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容