Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save freshking/b33b46f8c8223c4cd7d80a8399c4b757 to your computer and use it in GitHub Desktop.
Save freshking/b33b46f8c8223c4cd7d80a8399c4b757 to your computer and use it in GitHub Desktop.
import UIKit
class ImageView: UIImageView {
// image data
var data: Data? {
didSet {
// render image
renderImage()
}
}
private func renderImage() {
// get image source from data
guard let data = data, let source = CGImageSourceCreateWithData(data as CFData, nil) else {
image = nil
return
}
// get size of image view
let size = bounds.size
// move to asynchronous thread for creating image
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
// setup option for creating CGImage from source
let options = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceThumbnailMaxPixelSize: max(size.width, size.height)
] as CFDictionary
// create CGImage from source
if let cgImage = CGImageSourceCreateThumbnailAtIndex(source, 0, options) {
// create UIImage from CGImage
let image = UIImage(cgImage: cgImage)
// move to main thread for actually rendering image
DispatchQueue.main.async { [weak self] in
guard let strongSelf = self else {
return
}
// assign and animate in image by cross-dissolving
UIView.transition(with: strongSelf, duration: 0.2, options: .transitionCrossDissolve, animations: { [weak self] in
self?.image = image
}, completion: nil)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment