Created
August 2, 2017 04:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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