CGImageDestinationAddImage写入没有蓝色元素的图像

时间:2017-08-28 18:46:19

标签: swift3 gif cgimage

出于某种原因,当gifArrayAdjusted: [CGImage] 17或更多 CGImages时,gif会以全彩色正确创建。

但是gifArrayAdjusted: [CGImage] 16或更少 CGImages时,会创建gif但缺少所有蓝色元素。 gif中存在红色,绿色和灰色鳞片,但它像蓝色一样是“看不见的”。

经测试:在任何一种情况下查看gifArrayAdjusted时,图像都是全彩色的。因此,我认为问题出在createGIF func。

注意:由于for in loop,这与时序或CPU资源有关。如果我只使用我的gifArray并跳过强调某些帧,则始终会出现全彩色。

有谁可以解释为什么会这样?

{
var gifArray = [CGImage]()

// Fill [CGImage] with CoverPage
let rect = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height)
UIGraphicsBeginImageContextWithOptions(RVC.MainView.frame.size, false, 1.0)
#imageLiteral(resourceName: "CoverPage").draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
gifArray.append(newImage!.cgImage!)


// Fill [CGImage] with rest of images
repeat {
     UIGraphicsBeginImageContext(RVC.MainView.frame.size)
     RVC.MainView.layer.render(in: UIGraphicsGetCurrentContext()!)
     let image = UIGraphicsGetImageFromCurrentImageContext()!
     UIGraphicsEndImageContext()
     let cgImage = image.cgImage
     gifArray.append(cgImage!)
     RVC.ReplayForward()
} while RVC.loopSwitch == 0


// Certain images are double entered for longer showing in gif according to RVC.specialGifFrames:[Int]
var gifArrayAdjusted = [CGImage]()
for frame in 0..<RVC.specialGifFrames.count {
    if RVC.specialGifFrames[frame] == 1 {
        gifArrayAdjusted.append(gifArray[frame])
    } else if RVC.specialGifFrames[frame] == 2 {
        gifArrayAdjusted.append(gifArray[frame])
        gifArrayAdjusted.append(gifArray[frame])
    }
}


//Create GifData
let CFData1 = CFDataCreateMutable(kCFAllocatorDefault, 0)
let GifData = createGIF(with: gifArrayAdjusted, data: CFData1!, loopCount: 0, frameDelay: 1.1)


// Save Data                
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString             
let pathed = documentsPath.appendingPathComponent(path)
    do {
        try GifData.write(to: URL(fileURLWithPath: pathed), options: .atomic)
    } catch _ {
    }
}
func createGIF(with images: [CGImage], data: CFMutableData, loopCount: Int, frameDelay: Double) -> Data {
    let gifDest = CGImageDestinationCreateWithData(data, kUTTypeGIF, images.count, nil)
    let fileProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: loopCount]]
    CGImageDestinationSetProperties(gifDest!, fileProperties as CFDictionary?)
    let frameProperties = [(kCGImagePropertyGIFDictionary as String): [(kCGImagePropertyGIFDelayTime as String): frameDelay]]
    for img in images {
        CGImageDestinationAddImage(gifDest!, img, frameProperties as CFDictionary?)
    }
    CGImageDestinationFinalize(gifDest!)
    return data as Data
}

0 个答案:

没有答案