【发布时间】: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 文件作为解决方法,但这听起来非常低效。有什么想法吗?
提前致谢!
【问题讨论】: