2017-08-02 232 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

哦!它运作良好。非常感谢你。 –