2012-08-10 51 views
6

我遇到了一些我为调整CALayer大小而使用touch编写的代码的一些性能问题。它工作正常,但动画远远不够灵活,并且落后于触摸位置。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]; 
} 

有没有更好的实现方法?

回答

24

滞后是因为你正在改变图层的bounds属性,这是一个动画属性。

使用CALayers(CA代表核心动画...),默认情况下,动画属性的任何更改都将动画化。这被称为隐式动画。默认动画需要0.25秒,所以如果您经常更新它,请在处理触摸时说明,这会加起来并导致可见的延迟。

为了防止这种情况,你必须声明的动画交易,关闭隐式动画,然后更改属性:

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

会让我至少花一天时间独立解决这个问题,谢谢stack + jrturton。 – 2016-01-20 20:01:53

1

接受的答案在斯威夫特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() 
}