2017-09-25 76 views
0

我需要创建一个组件,让用户从图像中选择2个选项。起初,你会看到两个图像并排放置在中间的“手柄”。如果将手柄向左移动,则会看到更多的图像位于右侧,而左侧图像的位置更少,从而显示正确的图像,反之亦然。从技术上讲,我有两个全尺寸的UIImageView,一个在另一个之上,并且它们被遮盖。我有一个平移的手势,当用户滑动手柄时,手柄移动并且面具更新自己以适应“新中间”。UIImageview掩码更新速度太慢,以响应手势

下面是负责调整图像蒙版的代码。该常数是用手势调用的方法计算的。我知道我对这个常数的计算是很好的,因为“句柄”和掩码都被正确地更新了。

面具被来不及更新,并拖动时,我们看到它正在调整为时已晚。

func adjustImagesMasks(to constant: CGFloat) { 
    choiceImageA.mask?.willChangeValue(forKey: "frame") 
    choiceImageB.mask?.willChangeValue(forKey: "frame") 

    let separationPoint: CGFloat = self.frame.width/2.0 + constant 

    maskA.backgroundColor = UIColor.black.cgColor 
    maskA.frame = CGRect(origin: .zero, size: CGSize(width: separationPoint, height: self.frame.size.height)) 

    maskB.backgroundColor = UIColor.black.cgColor 
    maskB.frame = CGRect(x: separationPoint, y: 0, width: self.frame.width - separationPoint, height: self.frame.size.height) 

    choiceImageA.mask?.didChangeValue(forKey: "frame") 
    choiceImageB.mask?.didChangeValue(forKey: "frame") 

    maskA.drawsAsynchronously = true 
    maskB.drawsAsynchronously = true 

    self.setNeedsDisplay() 
    maskA.setNeedsDisplay() 
    maskA.displayIfNeeded() 
    maskB.setNeedsDisplay() 
    maskB.displayIfNeeded() 
} 

图像观点都有其面具设置是这样的:

maskA = CALayer() 
maskB = CALayer() 
choiceImageA.layer.mask = maskA 
choiceImageA.layer.masksToBounds = true 
choiceImageB.layer.mask = maskB 
choiceImageB.layer.masksToBounds = true 

因此,要回顾一下,我的问题实际上是关于性能。图像视图正在正确调整,但速度太慢。位于约束条件下的“句柄”会很快得到更新。

回答

0

很明显,CALayer试图对其属性的大部分更改进行动画处理。所以我看到的延迟实际上是由于动画。

我通过围绕adjustImagesMasks()调用CATransaction.setValue(kCFBooleanTrue, forKey:kCATransactionDisableActions)CATransaction.commit()来解决我的问题。所以对于这个交易,我要求不要动画变化。因为这是连续的(与平移手势),它是无形的。

全部代码在这里:

CATransaction.setValue(kCFBooleanTrue, forKey:kCATransactionDisableActions) 
adjustImagesMasks(to: newConstant) 
CATransaction.commit()```. 

other post帮了我很多。还有一个很好的解释。

希望这可以帮助别人。