最近我在制作Gif时遇到了一个问题,如果文件太大,颜色会消失。但是幸运的是,在Stack Overflow上得到帮助后,有人帮助我找到了解决方法并创建了自己的颜色映射。
之前的问题在这里...iOS Colors Incorrect When Saving Animated Gif
这个方法一直很好用,直到iOS 11出现了问题。我在文档中没有找到任何更改,也不知道为什么不能再用了。我发现,如果我删除kCGImagePropertyGIFImageColorMap
,虽然生成了一个gif文件,但它仍然存在颜色丢失的问题,就像我的之前的问题一样。这很容易理解,因为添加这个属性就是为了解决这个问题。
疑似问题......
func createGifFromImage(_ image: UIImage) -> URL{
let fileProperties: [CFString: CFDictionary] = [kCGImagePropertyGIFDictionary: [
kCGImagePropertyGIFHasGlobalColorMap: false as NSNumber] as CFDictionary]
let documentsDirectoryPath = "file://\(NSTemporaryDirectory())"
if let documentsDirectoryURL = URL(string: documentsDirectoryPath){
let fileURL = documentsDirectoryURL.appendingPathComponent("test.gif")
let destination = CGImageDestinationCreateWithURL(fileURL as CFURL, kUTTypeGIF, 1, nil)!
CGImageDestinationSetProperties(destination, fileProperties as CFDictionary);
let colorMap = image.getColorMap()
print("ColorMap \(colorMap.exported as NSData)")
let frameProperties: [String: AnyObject] = [
String(kCGImagePropertyGIFImageColorMap): colorMap.exported as NSData
]
let properties: [String: AnyObject] = [
String(kCGImagePropertyGIFDictionary): frameProperties as AnyObject
]
CGImageDestinationAddImage(destination, image.cgImage!, properties as CFDictionary);
if (!CGImageDestinationFinalize(destination)) {
print("failed to finalize image destination")
}
return fileURL
}
//shouldn't get here
return URL(string: "")!
}
这里有一个下载测试项目的链接。请注意,如果您在10.3模拟器上运行它,它会很好地工作,但如果您在iOS 11上运行它,则是一个白色图像。 https://www.dropbox.com/s/hdmkwyz47ondd52/gifTest2.zip?dl=0 其他被引用的代码...
extension UIImage{
//MARK: - Pixel
func getColorMap() -> ColorMap {
var colorMap = ColorMap()
let pixelData = self.cgImage!.dataProvider!.data
let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)
var byteIndex = 0
for _ in 0 ..< Int(size.height){
for _ in 0 ..< Int(size.width){
let color = Color(red: data[byteIndex], green: data[byteIndex + 1], blue: data[byteIndex + 2])
colorMap.colors.insert(color)
byteIndex += 4
}
}
return colorMap
}
}
色彩映射
struct Color : Hashable {
let red: UInt8
let green: UInt8
let blue: UInt8
var hashValue: Int {
return Int(red) + Int(green) + Int(blue)
}
public static func == (lhs: Color, rhs: Color) -> Bool {
return [lhs.red, lhs.green, lhs.blue] == [rhs.red, rhs.green, rhs.blue]
}
}
struct ColorMap {
var colors = Set<Color>()
var exported: Data {
let data = Array(colors)
.map { [$0.red, $0.green, $0.blue] }
.joined()
return Data(bytes: Array(data))
}
}