OGeek|极客世界-中国程序员成长平台

标题: ios - 如何将(编辑的)UIView 转换为 UIImage? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 02:25
标题: ios - 如何将(编辑的)UIView 转换为 UIImage?

我想将更改后的 UIView 保存为 UIImage。但是,它将始终保存为第一个(默认) View 。

这是第一个(默认)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
}



Best Answer-推荐答案


要在动画期间获取动画层的内容,您应该使用表示层而不是 View 层。对于您的代码,这应该是这样的:

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

您应该在动画完成后执行此代码,然后再将其从 View 层中移除。

如果您不想反转动画,“还原”它的过程应该更容易。这意味着您可以交换开始颜色和结束颜色并直接在 View 中设置目标颜色。在这种情况下,您不需要在动画结束时保留动画,您可以使用 View 的图层来保存图像。

关于ios - 如何将(编辑的)UIView 转换为 UIImage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45451442/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4