2017-09-25 121 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幫了我很多。還有一個很好的解釋。

希望這可以幫助別人。