UIView的bounds到底是干嘛的

来源:互联网 发布:java多线程经典题目 编辑:程序博客网 时间:2024/06/09 19:47

view的三个相关属性

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

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

12345678
@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 是一个很简单的办法。示例,

执行以下代码,

123456789
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 居中。

1234
viewB.center = CGPointMake(0, 0);NSLog(@"%@", NSStringFromCGRect(viewB.frame));//test[9849:2271050] {{-25, -25}, {50, 50}}

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

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

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

12345
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
原创粉丝点击