我最近在創建Gif時遇到了問題,如果它有太多的顏色丟失。不過感謝來自這裏的幫助,有人能夠幫助我找到解決辦法並創建我自己的色彩地圖。在iOS中創建Gif圖像顏色地圖11
上的問題在這裏... iOS Colors Incorrect When Saving Animated Gif
這很好工作,直到iOS的11.我找不到更改過的文檔任何東西,將使這個不再工作。我發現的是,如果我刪除kCGImagePropertyGIFImageColorMap
gif生成,但它有原始問題,如果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))
}
}
不幸的是,這並沒有幫助。問題是創建更大的GIF時,顏色因我的原始SO問題鏈接而丟失。添加彩色貼圖解決了這個問題,但它不再適用於iOS 11.這個答案沒有解決任何問題。我正在尋找一個解決iOS 11中缺失顏色問題的答案。 –
現在更清潔一些。我沒有閱讀原文,抱歉。 所以主要的目標是縮放GIF,我說得對嗎? (樣本中每4個按鈕...) – ingconti
樣本將它們縮放而不縮放。問題是保存較大的GIF顏色時丟失了。 –