UIView的bounds到底是干嘛的

view的三个相关属性

UIView 的 frame 属性使用的很频繁,但是 bounds 这个属性却一直用的不多。最近的工作内容涉及 bounds 比较多,抽空研究了一下。先说结论,

  • frame : 当前 view 在其 superView 中的位置及大小
  • bounds : 是 view 自身的坐标系(为其 subViews 提供的坐标系)
  • center : 该view的中心点在父view坐标系统中的位置

1
2
3
4
5
6
7
8
@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 是一个很简单的办法。示例,

执行以下代码,

1
2
3
4
5
6
7
8
9
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 居中。

1
2
3
4
viewB.center = CGPointMake(0, 0);
NSLog(@"%@", NSStringFromCGRect(viewB.frame));

//test[9849:2271050] {{-25, -25}, {50, 50}}

增加代码,运行,结果和预想的一致。而且 viewB.frame 由于受到 center 改变的影响,也发生了变化。

如果我们旋转 viewB 会怎样呢?

添加代码,执行,打印 frame 和 bounds。

1
2
3
4
5
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}}

旋转之后 viewB.frame变大,为其形状的外接的最小的矩形(与坐标系方向相同的矩形)。而 viewB.bounds 没有变化。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值