繁体   English   中英

在Swift中改变gif的颜色

[英]Changing the color of a gif in Swift

我需要以编程方式更改gif的颜色。 原始的gif在清晰的背景上是白色的,我想让它通过代码改变颜色。

我在这个帖子中尝试过这个答案,但是这会导致gif在第一帧冻结。 这是我正在使用的一些代码。

class MyViewController: UIViewController {
    @IBOutlet weak var myImageView: UIImageView?

    override func viewDidLoad() {
        myImageView?.image = UIImage.gif(name: "my_gif")
        myImageView?.image = myImageView?.image?.maskWithColor(color: UIColor.red)
        // This creates a red, but still version of the gif
    }
}

extension UIImage {

    func maskWithColor(color: UIColor) -> UIImage? {
        let maskImage = cgImage!

        let width = size.width
        let height = size.height
        let bounds = CGRect(x: 0, y: 0, width: width, height: height)

        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
        let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!

        context.clip(to: bounds, mask: maskImage)
        context.setFillColor(color.cgColor)
        context.fill(bounds)

        if let cgImage = context.makeImage() {
            let coloredImage = UIImage(cgImage: cgImage)
            return coloredImage
        } else {
            return nil
        }
    }

}

我目前正在为我需要的每种颜色使用不同的gif文件作为解决方法,但这听起来非常低效。 有任何想法吗?

提前致谢!

您可以创建UIView并设置它的背景颜色。 然后,您可以将视图的alpha值设置为0.5,并将视图放在图像视图上。

像这样:

let overlayView = UIView()
overlayView.frame = myImageView.frame
overlayView.backgroundColor = .red
overlayView.alpha = 0.5
view.addSubview(overlayView)

这样你就不会弄乱现有的图像视图。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM