2017-08-02 88 views
2

我想保存更改UIView作爲UIImage。但是,它將始終保存爲第一個(默認)視圖。如何將UIView轉換(編輯)爲UIImage?

這是第一個(默認)UIView。

enter image description here

應用程序使用漸變動畫來改變顏色。 的改變UIView的是一樣的,如下圖:

enter image description here

我寫的代碼如下:

extension UIImage { 
convenience init(layer: CALayer, view: UIView) { 
    UIGraphicsBeginImageContext(view.frame.size) 
    layer.render(in: UIGraphicsGetCurrentContext()!) 
    let image = UIGraphicsGetImageFromCurrentImageContext() 
    UIGraphicsEndImageContext() 
    self.init(cgImage: (image?.cgImage)!) 
    } 
} 

順便說一句,圖像保存與默認的UIView。

如何用更改的UIView保存圖像?

[編輯]添加動畫代碼

func animateLayer(){ 

    if index == 11 { 
     addEmitter(a: index, b: 0) 
     fromColors = [Colors.fromColorList[index], Colors.fromColorList[0]] 
     toColors = [Colors.toColorList[index], Colors.toColorList[0]] 
     index = 0 
    } else { 
     addEmitter(a: index, b: index + 1) 
     fromColors = [Colors.fromColorList[index], Colors.fromColorList[index+1]] 
     toColors = [Colors.toColorList[index], Colors.toColorList[index+1]] 
     index += 1 
    } 

    animation.fromValue = fromColors 
    animation.toValue = toColors 
    animation.duration = 1.00 

    mind.mindAnimation(animation: animation) 

} 

[EDIT2]添加ViewDidAppear

override func viewDidAppear(_ animated: Bool) { 

    animation.isRemovedOnCompletion = false 
    animation.fillMode = kCAFillModeForwards 
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) 
    animation.delegate = self 
} 
+0

也爲動畫添加代碼。你需要在那裏改變。 – adev

+0

@adev爲動畫添加代碼。謝謝。 –

+0

在向動畫添加動畫之前,嘗試使用'animation.removedOnCompletion = false'。 – adev

回答

2

爲了讓動畫層的動畫中的內容,你應該使用表示層而不是視圖的圖層。對於你的代碼,這應該是這樣的:它是從視圖層移除之前

if let layer = view.layer.presentation() { 
    let image = UIImage(layer: layer, view: view) 
    ... 
} 

你應該在動畫後執行該代碼已經完成了。

如果你不想扭轉動畫,它應該更容易「恢復」它的過程。這意味着您可以交換開始和結束顏色,並直接在視圖中設置目標顏色。在這種情況下,您無需在動畫結束時保留動畫,並且可以使用視圖的圖層來保存圖像。

+0

哦!它運作良好。非常感謝你。 –