目前我正在开展一个项目,从一些图像创建 GIF。我使用了 GitHub 上的方法 (generateGifFromImages),该方法采用 CGImage 结构,该结构允许您设置每个图像的帧延迟。但即使将帧延迟设置为每帧 2 秒,生成的 GIF 似乎播放速度也要快得多,通常每帧大约 0.5 秒。
下面的方法是我用来将图像转换为gif的。
public func generateGifFromImages(imagesArray: [CGImage], repeatCount: Int = 0, frameDelay: TimeInterval, targetSize: CGSize, destinationURL: URL, progressHandler: @escaping (Float) -> (), callback: @escaping (_ data: Data?, _ error: NSError?) -> ()) {
DispatchQueue.global(qos: .background).async {
if let imageDestination = CGImageDestinationCreateWithURL(destinationURL as CFURL, kUTTypeGIF, imagesArray.count, nil) {
let gifProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: repeatCount]]
// Calculate total progress steps
let totalSteps = imagesArray.count
var currentStep = 0
for image in imagesArray {
// Resize image while maintaining aspect ratio
guard let resizedImage = resize(image: image, targetSize: targetSize) else {
callback(nil, self.errorFromString("Couldn't resize image"))
return
}
let frameProperties: [String: Any] = [kCGImagePropertyGIFDelayTime as String: frameDelay]
// Add the resized image to the GIF
CGImageDestinationAddImage(imageDestination, resizedImage, frameProperties as CFDictionary )
// Update progress
currentStep += 1
let progress = Float(currentStep) / Float(totalSteps)
progressHandler(progress)
}
CGImageDestinationSetProperties(imageDestination, gifProperties as CFDictionary)
if CGImageDestinationFinalize(imageDestination) {
do {
let data = try Data(contentsOf: destinationURL)
callback(data, nil)
} catch {
callback(nil, error as NSError)
}
} else {
callback(nil, self.errorFromString("Couldn't create the final image"))
}
}
}
}
我尝试使用 kCGImagePropertyGIFDelayTime 属性将每个图像的帧延迟设置为 2 秒,但生成的 GIF 播放速度非常快。我的数组中有六个图像,并且我希望播放每一帧时至少有 1 秒的延迟。有人可以帮助我如何调整每张图像的帧延迟,以便生成的 GIF 以慢动作播放,每帧至少显示 1 秒吗?预先感谢您的支持!
问题出在下面这一行。
let frameProperties: [String: Any] = [kCGImagePropertyGIFDelayTime as String: frameDelay]
,即
[String : Double]
。
您应该将其设置为
[String : [String : Double]]
。所以应该是这样
let frameProperties = [(kCGImagePropertyGIFDictionary as String): [(kCGImagePropertyGIFDelayTime as String): frameDelay]]
.