2017-06-26 23 views
0

我有一個UILabel,我正在嘗試縮放和翻譯,並且我想動畫。我通過將transform設置爲UIView.animate塊來完成此操作。當動畫結束後,我想視圖的transform背部設置爲.identity和更新它的框架,使之保持究竟在何處CGAffineTransform移動它。僞代碼:如何動畫縮放並移動UILabel,然後在完成時將其變換設置回身份並保留其框架?

func animateMovement(label: UILabel, 
        newWidth: CGFloat, 
        newHeight: CGFloat, 
        newOriginX: CGFloat, 
        newOriginY: CGFloat) 
{   
    UIView.animate(withDuration: duration, animations: { 
     label.transform = ??? // Something that moves it to the new location and new size 
    }) { 
     label.frame = ??? // The final frame from the above animation 
     label.transform = CGAffineTransform.identity 
    } 
} 

至於我爲什麼不乾脆在動畫塊分配新框架:我的標籤裏面的文字,我想與動畫,動畫改變幀時,這是不可能的規模而不是變換。

我有協調的空間問題,我可以因爲動畫是不是在正確的位置(標籤上有錯誤的原點)後告訴。

回答

2

這裏是我想出了答案。這將在動畫持續時間內縮放內容,然後重置對象以在完成時進行標識轉換。

static func changeFrame(label: UILabel, 
         toOriginX newOriginX: CGFloat, 
         toOriginY newOriginY: CGFloat, 
         toWidth newWidth: CGFloat, 
         toHeight newHeight: CGFloat, 
         duration: TimeInterval) 
{ 
    let oldFrame = label.frame 
    let newFrame = CGRect(x: newOriginX, y: newOriginY, width: newWidth, height: newHeight) 

    let translation = CGAffineTransform(translationX: newFrame.midX - oldFrame.midX, 
             y: newFrame.midY - oldFrame.midY) 
    let scaling = CGAffineTransform(scaleX: newFrame.width/oldFrame.width, 
            y: newFrame.height/oldFrame.height) 

    let transform = scaling.concatenating(translation) 

    UIView.animate(withDuration: duration, animations: { 
     label.transform = transform 
    }) { _ in 
     label.transform = .identity 
     label.frame = newFrame 
    } 
} 
+0

良好的工作!;恭喜 –

相關問題