CALayer之anchorPoint分析

anchorPoint:CALayer中心点,动画特效的中心点,取值区间[0.0, 1.0],默认为(0.5, 0.5);

position:CALayer中心点坐标;

frame.origin:由anchorPoint、position共同计算得出:


frame.origin.x = position.x - anchorPoint * bounds.size.width;

frame.origin.y = position.y - anchorPoint * bounds.size.height;

frame.size.width = bounds.size.width;

frame.size.height = bounds.size.height;


有些动画效果需要我们修改anchorPoint,比如绕着自身某条边旋转等。

当我们改变了anchorPoint,计算出的frame.origin也会随之改变,因此最终显示的图像就会发生偏移,这时就需要我们对position或frame做适当的修改。


例如:在屏幕上显示一个蓝色button

UIButton *btnBlue = [[UIButton alloc] initWithFrame:CGRectMake(50, 50, 100, 100)];

btnBlue.backgroundColor = [UIColor blueColor];

CGRect oldFrame = btnBlue.layer.frame;

CALayer之anchorPoint分析_第1张图片


修改anchorPoint:

CGPoint anchorPoint = CGPointMake(0.0, 0.5);

btnBlue.layer.anchorPoint = anchorPoint;

修改之后,btnBlue显示位置向右偏移。

CALayer之anchorPoint分析_第2张图片


解决办法:

1.修改position

btnBlue.layer.position = CGPointMake(btnBlue.layer.position.x - btnBlue.layer.frame.size.width * (0.5 - anchorPoint.x),

                                                                      btnBlue.layer.position.y - btnBlue.layer.frame.size.height * (0.5 - anchorPoint.y);

2.直接修改frame

btnBlue.layer.frame = oldFrame.

这样,btnBlue就显示正常了。


你可能感兴趣的:(iOS开发)