【问题标题】:CALayer Resize is slowCALayer 调整大小很慢
【发布时间】:2012-08-07 11:03:09
【问题描述】:

我为使用触摸调整 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]; 
 }

有没有更好的方法来实现这一点?

【问题讨论】:

    标签: iphone ios core-graphics calayer quartz-graphics


    【解决方案1】:

    在 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()
    }
    

    【讨论】:

      【解决方案2】:

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

      使用 CALayers(CA 代表核心动画...)对可动画属性的任何更改都将默认为动画。这称为隐式动画。默认动画需要 0.25 秒,因此如果您经常更新它,例如在处理触摸期间,这将加起来并导致明显的延迟。

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

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

      【讨论】:

      • 我至少要花一天时间才能独立解决这个问题,感谢 stack + jrturton。
      • 在一个小时的意外漩涡运动后救了我.. :D
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      • 1970-01-01
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      • 1970-01-01
      • 2012-10-03
      相关资源
      最近更新 更多