UIView的frame和bounds区别

48 篇文章 0 订阅

UIView的frame和bounds区别

iOS中,大家肯定对view和frame都不陌生,我们设置view在父view中的位置和大小时,只需要设置frame就可以了。

可能大家也有查过网上的一些资料,可能也会得知frame是相对于superview坐标系的,而bounds则相对于view自身的坐标系,但是frame究竟是怎样表示坐标的呢,其实这就和bounds有关了。

值得肯定的是frame.size 和bounds.size 肯定一样,但是UIView中,frame其实是不存储的,而是动态计算的,改变center,改变bounds大小,或者改变transfrom都可能会导致frame的改变。 

UIView的frame是一个动态的,官方文档中有提到

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

大意是说,如果我们的view有transform,则frame不能反映其在父view中的实际位置,需要用bounds+center来反映。

假定我们的view没有transform。 每次我们设置frame时,则系统首先会设置

bounds.origin = 0,0
bounds.size = frame.size

然后会继续设置

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

也就是说 设置frame时,我们的bounds和center都会发生变化,但是view的位置是由center和bounds共同决定的,完全可以不依赖于frame。

每次我们访问frame时,其实也是通过center和bounds计算。

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

当然期间如果有transform,则会考虑到transfrom,比如大小缩小到0.9倍,则center不变,frame.size 变为 0.9倍,origin也会跟着变。 transform不会影响到view的bounds和center,但是会影响到frame。 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个IT大叔的内心独白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值