CALayer调整大小的速度很慢。

17

我对自己编写的代码进行了调整,用于通过触摸来改变CALayer的大小,但是我遇到了一些性能问题。尽管功能正常,但动画不够流畅,落后于触摸位置。

CGPoint startPoint;
CALayer *select;

- (CGRect)rectPoint:(CGPoint)p1 toPoint:(CGPoint)p2 {
     CGFloat x, y, w, h;
     if (p1.x < p2.x) {
         x = p1.x;
         w = p2.x - p1.x;
     } else {
         x = p2.x;
         w = p1.x - p2.x;
     }
     if (p1.y < p2.y) {
         y = p1.y;
         h = p2.y - p1.y;
     } else {
         y = p2.y;
         h = p1.y - p2.y;
     }
     return CGRectMake(x, y, w, h);
 }

 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
     UITouch *t1 = [[[event allTouches]allObjects]objectAtIndex:0];
     CGPoint loc = [t1 locationInView:self];
     startPoint = loc;
     lastPoint = CGPointMake(loc.x + 5, loc.y + 5);

     select = [CALayer layer];
     select.backgroundColor = [[UIColor blackColor]CGColor];
     select.frame = CGRectMake(startPoint.x, startPoint.y, 5, 5);
     [self.layer addSublayer:select];
 }

 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
     UITouch *t1 = [[[event allTouches]allObjects]objectAtIndex:0];
     CGPoint loc = [t1 locationInView:self];
     select.bounds = [self rectPoint:startPoint toPoint:loc]; 
 }

有没有更好的实现方式?

2个回答

48

出现延迟是因为您正在更改图层的bounds属性,这是一个可动画化的属性。

对于CALayers(CA代表核心动画...),任何对可动画属性的更改默认都会进行动画处理。这被称为隐式动画。默认动画持续时间为0.25秒,因此如果您频繁更新它,比如在触摸处理期间,这将会累积并导致明显的延迟。

为了防止这种情况发生,您必须声明一个动画事务,关闭隐式动画,然后再更改属性:

[CATransaction begin];
[CATransaction setDisableActions:YES];
layer.bounds = whatever;
[CATransaction commit];

2
如果没有Stack和jrturton的帮助,我独立解决这个问题至少需要一天时间。非常感谢他们。 - Johnny Rockex
1
在意想不到的旋转运动持续了一个小时之后,它拯救了我... :D - swebal

18

在Swift 3/4中被接受的答案:

CATransaction.begin()
CATransaction.setDisableActions(true)
layer.bounds = whatever
CATransaction.commit()
值得一提的是,这也适用于 .frame 属性,例如当你调整 AVPlayerLayer 大小时。
override func layoutSubviews() {
    CATransaction.begin()
    CATransaction.setDisableActions(true)
    playerLayer.frame = self.bounds
    CATransaction.commit()
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接