我在一个快速项目中使用CGImageDestinationAddImage
来从照片创建动画GIF文件。这一切都很好,除了最终GIF中的底行像素总是相同的(这些是我添加的第一张照片中的像素)。这些照片大小相同(600x600像素)。
我注意到这发生在运行iOS 9.3.5的iPad 2上,但在iPad Pro 12.9和#34;运行iOS 10.2。因此,这可能与32位与64位或iOS版本有关。
有谁知道这是一个已知问题,还是我做错了什么?我在下面粘贴了我的代码。
// Load photos
var photos = [Data]()
for index in 1...5 {
if let imageDataURL = Bundle.main.url(forResource: "photo_\(index)", withExtension: "jpg"),
let data = try? Data(contentsOf: imageDataURL, options: []) {
photos.append(data)
}
}
// Create the GIF
let temporaryDirectory = NSTemporaryDirectory()
let url = URL(fileURLWithPath: temporaryDirectory).appendingPathComponent("slideshow.gif")
guard let destination = CGImageDestinationCreateWithURL(url as CFURL, kUTTypeGIF, photos.count, nil) else {
return
}
// Repeat forever by setting the loop count to 0
let gifFileProperties = [kCGImagePropertyGIFLoopCount as String: 0]
let fileProperties = [kCGImagePropertyGIFDictionary as String: gifFileProperties]
CGImageDestinationSetProperties(destination, fileProperties as CFDictionary)
// Set the frame delay to 2 seconds
let gifFrameProperties = [kCGImagePropertyGIFDelayTime as String: 2.0]
let frameProperties = [kCGImagePropertyGIFDictionary as String: gifFrameProperties]
for photo in photos {
if let imageProvider = CGDataProvider(data: photo as CFData),
let cgimage = CGImage(jpegDataProviderSource: imageProvider, decode: nil, shouldInterpolate: true, intent: .defaultIntent) {
CGImageDestinationAddImage(destination, cgimage, frameProperties as CFDictionary)
}
}
guard CGImageDestinationFinalize(destination) else {
return
}
// Get the gif data.
let gifData = try? Data(contentsOf: url)