深入浅出了解frame和bounds

简介: 对bounds和frame的理解
frame

frame的官方解释如下:

The frame rectangle, which describes the view’s location and size in its superview’s coordinate system.

This rectangle defines the size and position of the view in its superview’s coordinate system. Use this rectangle during layout operations to set the size and position the view. Setting this property changes the point specified by the center property and changes the size in the bounds rectangle accordingly. The coordinates of the frame rectangle are always specified in points.

它定义了一个view相对于父视图坐标系的位置和大小,它会影响center属性和bounds属性的size。
先看一下它究竟是什么?
它是一个CGRect类型,如下:

struct CGRect {
    CGPoint origin;
    CGSize size;
};
typedef struct CG_BOXABLE CGRect CGRect;

struct CGPoint {
    CGFloat x;
    CGFloat y;
};
typedef struct CG_BOXABLE CGPoint CGPoint;

/* Sizes. */

struct CGSize {
    CGFloat width;
    CGFloat height;
};
typedef struct CG_BOXABLE CGSize CGSize;

其中的origin就是该view的位置,它是一个CGPoint类型,也是一个结构体,包含了我们熟知的常用二维坐标系的x、y。根据x、y可以在坐标系里面唯一确定一个点。如下图:
frame

这个坐标系和我们平时接触的还不太一样,它是向右向下为正方向。所以对于window来说,其原点是左上角,比如现在的头像的起始坐标就是(200,40)。按照原来常规的坐标系来说,应该是(200,-40)。
在设置一个CGRect的时候,用到的方法是CGRectMake,其实现如下:

CG_INLINE CGRect
CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
  CGRect rect;
  rect.origin.x = x; rect.origin.y = y;
  rect.size.width = width; rect.size.height = height;
  return rect;
}

也就是自己在实现部分创建了一个rect,然后逐个赋值。
关于frame,这里要注意的一点就是:frame是相对于父视图的坐标系来定位的。如果你这样设置frame:(0,0,100,200),也就是在父视图左上角添加了一个宽100,高200的子视图(前提是没有改变父视图的bounds,接下来会有介绍bounds)。

bounds

The bounds rectangle, which describes the view’s location and size in its own coordinate system.

The default bounds origin is (0,0) and the size is the same as the size of the rectangle in the frame property. Changing the size portion of this rectangle grows or shrinks the view relative to its center point. Changing the size also changes the size of the rectangle in the frame property to match. The coordinates of the bounds rectangle are always specified in points.

Changing the bounds rectangle automatically redisplays the view without calling its drawRect: method. If you want UIKit to call the drawRect: method, set the contentMode property to UIViewContentModeRedraw.

Changes to this property can be animated.

它也是描述的是视图的位置和大小,只不过是在自己的坐标系上。也就是说它描述的是当前视图相对于自身坐标系的位置和大小。
举个例子:

- (void)viewDidLoad {
    [super viewDidLoad];
   
    CGRect rect  = self.view.frame;
    self.parentView = [[ParentView alloc] initWithFrame:CGRectMake(60, 80, rect.size.width-120, rect.size.height - 160)];
    self.parentView.backgroundColor = [UIColor redColor];
    [self.view addSubview:_parentView];
    NSLog(@"frame:%@",NSStringFromCGRect(self.parentView.frame));
    NSLog(@"bounds:%@",NSStringFromCGRect(self.parentView.bounds));
    NSLog(@"center:%@",NSStringFromCGPoint(self.parentView.center));
    
}

输出的结果如下:

frame:{{60, 80}, {200, 408}}
bounds:{{0, 0}, {200, 408}}
center:{160, 284}

由此可见,如果我们没有去更改bounds的值,它默认的位置坐标点是(0,0)。

center

The center point of the view's frame rectangle.

The center point is specified in points in the coordinate system of its superview. Setting this property updates the origin of the rectangle in the frame property appropriately.

Use this property, instead of the frame property, when you want to change the position of a view. The center point is always valid, even when scaling or rotation factors are applied to the view's transform.

Changes to this property can be animated.

center是view的中点。该属性是想归于父类的坐标系确定的。从bounds小节里面的例子可以看到center的值,其计算方法为:

center.x = frame.origin.x + frame.size.width/2
center.y = frame.origin.y + frame.size.height/2

transform

Specifies the transform applied to the view, relative to the center of its bounds.
Use this property to scale or rotate the view's frame rectangle within its superview's coordinate system. (To change the position of the view, modify the center property instead.) The default value of this property is CGAffineTransformIdentity.

Transformations occur relative to the view's anchor point. By default, the anchor point is equal to the center point of the frame rectangle. To change the anchor point, modify the anchorPoint property of the view's underlying CALayer object.

Changes to this property can be animated.

In iOS 8.0 and later, the transform property does not affect Auto Layout. Auto layout calculates a view’s alignment rectangle based on its untransformed frame.

它用于指定视图的变换。使用这个属性可以放大或者旋转视图,它的frame会因此改变,是以中心点为变换的。看例子:

- (void)viewDidLoad {
    [super viewDidLoad];
   
    CGRect rect  = self.view.frame;
    self.parentView = [[ParentView alloc] initWithFrame:CGRectMake(60, 80, rect.size.width-120, rect.size.height - 160)];
    self.parentView.backgroundColor = [UIColor redColor];
    [self.view addSubview:_parentView];
    NSLog(@"frame:%@",NSStringFromCGRect(self.parentView.frame));
    NSLog(@"bounds:%@",NSStringFromCGRect(self.parentView.bounds));
    NSLog(@"center:%@",NSStringFromCGPoint(self.parentView.center));
    
    self.parentView.transform = CGAffineTransformMakeRotation(60);
   
    NSLog(@"after change transform,frame:%@",NSStringFromCGRect(self.parentView.frame));
    NSLog(@"after change transform,bounds:%@",NSStringFromCGRect(self.parentView.bounds));
    NSLog(@"after change transform,center:%@",NSStringFromCGPoint(self.parentView.center));
}

看输出的结果:

frame:{{60, 80}, {200, 408}}
bounds:{{0, 0}, {200, 408}}
center:{160, 284}
after change transform,frame:{{2.5773352536321568, 59.226689885086444}, {314.84532949273569, 449.54662022982711}}
after change transform,bounds:{{0, 0}, {200, 408}}
after change transform,center:{160, 284}

如图:
transform
可以看出,当我们对图像通过旋转,旋转后的图片的frame已经变成了{(2.5773352536321568, 59.226689885086444), (314.84532949273569, 449.54662022982711)},此时的起始位置为图上旋转后标的(2.58,59.2),大小也变成了双箭头黑线标注的大小。
因此得出结论:进行了transform变换,其frame改变了,但是其bounds和center并没有修改。此时bounds的size和frame的size已经没有关系了。当没有进行任何transform时,frame的size总是和bounds相等。

以上便是对frame、bounds、center和transform做了一个简单的介绍。

bounds的使用

接下来看一个例子(例子A):

- (void)viewDidLoad {
    [super viewDidLoad];
   
    CGRect rect  = self.view.frame;
    self.parentView = [[ParentView alloc] initWithFrame:CGRectMake(60, 80, rect.size.width-120, rect.size.height - 160)];
    self.parentView.backgroundColor = [UIColor redColor];
    [self.view addSubview:_parentView];
    NSLog(@"frame:%@",NSStringFromCGRect(self.parentView.frame));
    NSLog(@"bounds:%@",NSStringFromCGRect(self.parentView.bounds));
    NSLog(@"center:%@",NSStringFromCGPoint(self.parentView.center));
 
    self.parentView.bounds = CGRectMake(-40, -40, self.parentView.frame.size.width, self.parentView.frame.size.height);
    NSLog(@"parent change bound ,frame:%@",NSStringFromCGRect(self.parentView.frame));
    NSLog(@"parent change bound ,bounds:%@",NSStringFromCGRect(self.parentView.bounds));
    NSLog(@"parent change bound ,center:%@",NSStringFromCGPoint(self.parentView.center));

    self.childView = [[ChildView alloc] initWithFrame:CGRectMake(20, 20, 100, 100)];
    self.childView.backgroundColor = [UIColor yellowColor];
    [self.parentView addSubview:_childView];
   
    NSLog(@"childView frame:%@",NSStringFromCGRect(self.childView.frame));
    NSLog(@"childView ounds:%@",NSStringFromCGRect(self.childView.bounds));
    NSLog(@"childView center:%@",NSStringFromCGPoint(self.childView.center));
}

这里在parentView上添加了一个childView,然后对parentView的bounds进行修改和不修改进行了测试,结果如下:
change bounds
你会发现当修改了parentView的bounds之后,发现childView缺向右向下做了偏移。这里设置parentView的bounds的origin为(-40,-40)为何会发生这种情况呢?接下来先看一下下面这张图:
坐标系

+代表正方向,-代表负方向。

如果此时我们没有改变图中O的坐标,那么此时A的坐标是(20,20),如果我们更改了O的坐标为(-20,-20),那么原来A点的坐标就成了A'(0,0),但是A坐标是不变的,所以它会到黑色A处。所以你改变了原点坐标为负之后,A点会移动到黑色A。相反如果你设置了坐标原点为(20,20),那么A点就会和坐标原点重合。
这就是为什么childView会向右向下移动的原因。
接下来再做如下操作(例子B):

- (void)viewDidLoad {
    [super viewDidLoad];
   
    CGRect rect  = self.view.frame;
    self.parentView = [[ParentView alloc] initWithFrame:CGRectMake(60, 80, rect.size.width-120, rect.size.height - 160)];
    self.parentView.backgroundColor = [UIColor redColor];
    [self.view addSubview:_parentView];
     
    NSLog(@"parent change bound ,frame:%@",NSStringFromCGRect(self.parentView.frame));
    NSLog(@"parent change bound ,bounds:%@",NSStringFromCGRect(self.parentView.bounds));
    NSLog(@"parent change bound ,center:%@",NSStringFromCGPoint(self.parentView.center));

    self.childView = [[ChildView alloc] initWithFrame:CGRectMake(self.parentView.frame.origin.x, self.parentView.frame.origin.y+self.parentView.frame.size.height-200, 100, 100)];
    self.childView.backgroundColor = [UIColor yellowColor];
    [self.parentView addSubview:_childView];
   
    
    NSLog(@"childView frame:%@",NSStringFromCGRect(self.childView.frame));
    NSLog(@"childView ounds:%@",NSStringFromCGRect(self.childView.bounds));
    NSLog(@"childView center:%@",NSStringFromCGPoint(self.childView.center));
    NSLog(@"\n--------\n");
    CGRect parentBounds = self.parentView.bounds;
    [UIView animateWithDuration:2 animations:^{
        
        self.parentView.bounds = CGRectMake(parentBounds.origin.x, 400, parentBounds.size.width, parentBounds.size.height);
    } completion:^(BOOL finished) {
        NSLog(@"anim finished,parentView frame:%@",NSStringFromCGRect(self.parentView.frame));
        NSLog(@"anim finished,parentView ounds:%@",NSStringFromCGRect(self.parentView.bounds));
        NSLog(@"anim finished,parentView center:%@",NSStringFromCGPoint(self.parentView.center));
        NSLog(@"anim finished,childView frame:%@",NSStringFromCGRect(self.childView.frame));
        NSLog(@"anim finished,childView bounds:%@",NSStringFromCGRect(self.childView.bounds));
        NSLog(@"anim finished,childView center:%@",NSStringFromCGPoint(self.childView.center));
    }];
}

输出结果如下:

parent change bound ,frame:{{60, 80}, {200, 408}}
parent change bound ,bounds:{{0, 0}, {200, 408}}
parent change bound ,center:{160, 284}
childView frame:{{60, 288}, {100, 100}}
childView ounds:{{0, 0}, {100, 100}}
childView center:{110, 338}
--------
anim finished,parentView frame:{{60, 80}, {200, 408}}
anim finished,parentView ounds:{{0, 400}, {200, 408}}
anim finished,parentView center:{160, 284}
anim finished,childView frame:{{60, 288}, {100, 100}}
anim finished,childView bounds:{{0, 0}, {100, 100}}
anim finished,childView center:{110, 338}

运行效果是childView向上移动,然后停止。结果前后对比图如下:
animation bounds
直观来看,按说childView的frame改变了,但是从console输出的结果来看,childView的frame/bounds/center都没有改变,但是直观来看其位置却改变了。再看一下parentView,只有bounds改变了,frame和center却没变,从直观来看parentView没有任何更改。所以很有可能是parentView的bounds修改引起了childView的位置更改。这是为什么呢?这里先不说明为什么,再看一下最常用的UIScrollView:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.scrollView = [[ZGUIScrolLView alloc] initWithFrame:self.view.frame];
    self.scrollView.delegate = self;
    [self.view addSubview:_scrollView];
    NSLog(@"scrollview frame:%@",NSStringFromCGRect(_scrollView.frame));
    NSLog(@"scrollview bounds:%@",NSStringFromCGRect(_scrollView.bounds));
    NSLog(@"scrollview center:%@",NSStringFromCGPoint(_scrollView.center));
    self.scrollView.contentSize = CGSizeMake(800, 800);
    self.parentView = [[ParentView alloc] initWithFrame:CGRectMake(20, 100, 250, 300)];
    self.parentView.backgroundColor = [UIColor redColor];
    [self.scrollView addSubview:_parentView];
    NSLog(@"parentView frame:%@",NSStringFromCGRect(_parentView.frame));
    NSLog(@"parentView bounds:%@",NSStringFromCGRect(_parentView.bounds));
    NSLog(@"parentView center:%@",NSStringFromCGPoint(_parentView.center));
    
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSLog(@"didScroll scrollview frame:%@",NSStringFromCGRect(_scrollView.frame));
    NSLog(@"didScroll scrollview bounds:%@",NSStringFromCGRect(_scrollView.bounds));
    NSLog(@"didScroll scrollview center:%@",NSStringFromCGPoint(_scrollView.center));
    NSLog(@"didScroll parentView frame:%@",NSStringFromCGRect(_parentView.frame));
    NSLog(@"didScroll parentView bounds:%@",NSStringFromCGRect(_parentView.bounds));
    NSLog(@"didScroll parentView center:%@",NSStringFromCGPoint(_parentView.center));
    printf("\n-------------------------------------------\n");
}

当滚动视图的时候,console输出结果如下:

scrollview frame:{{0, 0}, {320, 568}}
scrollview bounds:{{0, 0}, {320, 568}}
scrollview center:{160, 284}
parentView frame:{{20, 100}, {250, 300}}
parentView bounds:{{0, 0}, {250, 300}}
parentView center:{145, 250}
didScroll scrollview frame:{{0, 0}, {320, 568}}
didScroll scrollview bounds:{{0, -20}, {320, 568}}
didScroll scrollview center:{160, 284}
didScroll parentView frame:{{20, 100}, {250, 300}}
didScroll parentView bounds:{{0, 0}, {250, 300}}
didScroll parentView center:{145, 250}
-------------------------------------------
didScroll scrollview frame:{{0, 0}, {320, 568}}
didScroll scrollview bounds:{{8.5, 31.5}, {320, 568}}
didScroll scrollview center:{160, 284}
didScroll parentView frame:{{20, 100}, {250, 300}}
didScroll parentView bounds:{{0, 0}, {250, 300}}
didScroll parentView center:{145, 250}
-------------------------------------------
didScroll scrollview frame:{{0, 0}, {320, 568}}
didScroll scrollview bounds:{{25.5, 162}, {320, 568}}
didScroll scrollview center:{160, 284}
didScroll parentView frame:{{20, 100}, {250, 300}}
didScroll parentView bounds:{{0, 0}, {250, 300}}
didScroll parentView center:{145, 250}

根据输出结果可以看到,parentView的center、frame、bounds在滚动过程中都没有作出更改,但是我们看到的它的位置的确改变了。而对于scrollView来说,其frame和center也没有更改,但是bounds更改了。
这种现象和上面提到的(例子B)的现象一样,都是对bounds进行了修改。然后子视图从新进行了布局。说道子视图重新布局,让我想到了一个方法:

- (void)layoutSubviews;

从字面意思看就是布局某个视图的子视图,那么会不会和这个方法有关呢?因此我在自定义的ZGUIScrollView里面实现了该方法:

- (void)layoutSubviews {
    NSLog(@"scrollview's layoutSubViews called");
    [super layoutSubviews];
}

再次滚动界面,发现每次滚动都会调用scrollview的layoutSubViews方法。苹果官方文档介绍:

Lays out subviews.

The default implementation of this method does nothing on iOS 5.1 and earlier. Otherwise, the default implementation uses any constraints you have set to determine the size and position of any subviews.

Subclasses can override this method as needed to perform more precise layout of their subviews. You should override this method only if the autoresizing and constraint-based behaviors of the subviews do not offer the behavior you want. You can use your implementation to set the frame rectangles of your subviews directly.

You should not call this method directly. If you want to force a layout update, call the setNeedsLayout method instead to do so prior to the next drawing update. If you want to update the layout of your views immediately, call the layoutIfNeeded method.

它的作用就是布局一个视图上的子视图。确定子视图的大小和位置。如果你想强制布局更新,你不能直接去调用这个方法,而是在下次更新图形之前调用setNeedsLayout方法,如果你要立即更新视图布局,调用layoutIfNeeded方法。

由此可知,UIScrollView的实现就是通过bounds来实现的。contentOffset是bounds的origin。然后当bounds修改之后,会在layoutSubviews方法里面对子视图进行布局。对子类进行更新。
另外,我们还可以用bounds实现如下效果:
bounds to set cell
图上右侧便是使用了bounds实现的效果。实现方式就是在自定义cell中重写drawReact:

- (void)drawRect:(CGRect)rect {
     self.bounds = CGRectMake(self.bounds.origin.x, self.bounds.origin.y, self.frame.size.width-20, self.frame.size.height - 5);
    [super drawRect:rect];
}

其实UITableView(它是UIScrollView)的实现也是类似,更改了bounds,来实现滚动加载cell。

总结

对bounds和frame的理解就是这些,其实系统用bounds的地方还是很多的。例如UIScrollView的实现就用到了。有疑问的话可以留言交流。

注:转赞请标明来源:[张贵的博客(https://yq.aliyun.com/articles/300444)

相关文章
|
Swift iOS开发 开发者
iOS - 跳转App Store下载 app 的两种方式
iOS - 跳转App Store下载 app 的两种方式
3642 0
iOS - 跳转App Store下载 app 的两种方式
|
6月前
|
Rust JavaScript Java
PHP已死?谎言与真相:2025年PHP生态现状、薪资趋势与未来前景
每隔几年,技术圈就会响起“PHP已死”的论调。然而现实是,直至2025年,PHP仍然驱动着超过77%的网站,WordPress市场占有率持续攀升,Laravel和Symfony社区依然活跃。
880 0
|
8月前
|
Web App开发 人工智能
火语言 RPA:豆包AI问答内容采集案例
本案例用火语言RPA自动向豆包AI批量提问,精准抓取回答并逐条写入Excel,支持答案特征分析与内容策略优化,为GEO(生成式引擎优化)提供高效、稳定的数据支撑。
1054 4
|
API 数据处理
鸿蒙应用开发从入门到实战(十三):ArkUI组件Slider&Progress
ArkUI提供滑块Slider与进度条Progress组件,用于鸿蒙原生APP开发。Slider支持拖动调节音量、亮度等,可设步长、方向及提示气泡;Progress支持线性、环形等多种样式,可自定义颜色、宽度与刻度,实时显示任务进度。
779 2
|
机器人 API Python
智能对话机器人(通义版)会话接口API使用Quick Start
本文主要演示了如何使用python脚本快速调用智能对话机器人API接口,在参数获取的部分给出了具体的获取位置截图,这部分容易出错,第一次使用务必仔细参考接入参数获取的位置。
1283 1
|
开发者
HarmonyOS Next快速入门:Image组件
本教程摘自《HarmonyOS Next快速入门》,专注于HarmonyOS应用开发中的Image组件使用。Image组件支持多种图片格式(如png、jpg、svg等),可渲染本地资源、网络图片、媒体库文件及PixelMap像素图。通过设置`objectFit`属性,实现不同缩放类型;利用`fillColor`属性调整矢量图颜色。示例代码涵盖本地、网络及资源图片的加载与样式设置,同时需在`module.json5`中声明网络权限以加载外部资源。适合开发者快速掌握HarmonyOS图像展示功能。
1501 0
|
前端开发 JavaScript Java
如何开发项目管理系统中的统计分析看板?(附架构图+流程图+代码参考)
本文介绍如何通过项目管理系统的统计分析看板,提升项目管理效率与决策能力。内容涵盖客户分析、财务收支及项目综合看板的设计与实现,提供技术架构、业务流程和代码示例,帮助开发者快速构建数据驱动的项目管理平台。
|
消息中间件 人工智能 Kafka
【云故事探索】NO.14:乐言科技——云原生加速电商行业赋能,云消息队列助力降本 37%
上海乐言科技股份有限公司专注于AI技术,提供电商、金融等领域的整体解决方案。其核心产品“乐语助人”智能客服机器人日均服务超千万人次,助力六万余家电商客户数智化转型。为解决自建消息队列痛点,乐言科技采用阿里云消息队列RocketMQ版Serverless系列,实现业务稳定、开发成本降低、运维效率提升及资源弹性降本37%。通过云原生架构,乐言科技推动AI与电商深度融合,助力行业创新突破。
|
JSON 缓存 负载均衡
Node.js 的性能
Node.js 的性能
619 12

热门文章

最新文章