【问题标题】:Changing the color of a gif in Swift在 Swift 中更改 gif 的颜色
【发布时间】:2017-05-21 13:26:25
【问题描述】:

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

我已经尝试过this thread 中的答案,但这会导致 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 文件作为解决方法,但这听起来非常低效。有什么想法吗?

提前致谢!

【问题讨论】:

    标签: ios swift3


    【解决方案1】:

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

    像这样:

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

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

    希望这会有所帮助。

    【讨论】:

    • 这不会在 gif 上创建一个红色的半透明矩形吗?我正在尝试做的是将原件中的白色更改为红色,同时保持清晰的背景。
    • 哦,是的,这正是这样做的。对于那个很抱歉。您发布的代码冻结的原因是您将图像视图的图像设置为单个UIImage。您的代码首先将图像视图的图像设置为我假设的动画序列,然后在您为图像视图设置单个图像之后。要解决此问题,您需要将扩展​​程序中的着色代码应用于 GIF 中的每个图像。
    猜你喜欢
    • 2012-01-16
    • 2014-02-28
    • 2010-11-30
    • 2015-11-03
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多