Skip to content

Instantly share code, notes, and snippets.

@dannofx
Created August 2, 2017 04:29
Show Gist options
  • Save dannofx/b2c79a4d5482b5ab61df5b984d584a7f to your computer and use it in GitHub Desktop.
Save dannofx/b2c79a4d5482b5ab61df5b984d584a7f to your computer and use it in GitHub Desktop.
Extension to force load of UIImage and avoid lazy load in Swift 3
// Based on https://gist.github.com/steipete/1144242
import UIKit
extension UIImage {
func forceLoad() -> UIImage {
guard let imageRef = self.cgImage else {
return self //failed
}
let width = imageRef.width
let height = imageRef.height
let colourSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo: UInt32 = CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue
guard let imageContext = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: colourSpace, bitmapInfo: bitmapInfo) else {
return self //failed
}
let rect = CGRect(x: 0, y: 0, width: width, height: height)
imageContext.draw(imageRef, in: rect)
if let outputImage = imageContext.makeImage() {
let cachedImage = UIImage(cgImage: outputImage)
return cachedImage
}
return self //failed
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment