Skip to content

Instantly share code, notes, and snippets.

@kirsteins
Last active August 29, 2015 14:21
Show Gist options
  • Save kirsteins/23d90ee8593c0517f658 to your computer and use it in GitHub Desktop.
Save kirsteins/23d90ee8593c0517f658 to your computer and use it in GitHub Desktop.
Drawing cache
private let drawingCache = NSCache()
public extension UIImage {
public class func imageForSize(size: CGSize, opaque: Bool = false, drawingBlock: () -> Void) -> UIImage {
assert(size != CGSize.zeroSize)
UIGraphicsBeginImageContextWithOptions(size, opaque, 0.0)
drawingBlock()
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return image
}
public class func imageForIdentifier(identifier: String, opaque: Bool = false, size: CGSize, drawingBlock: () -> Void) -> UIImage {
if let image = drawingCache.objectForKey(identifier) as? UIImage {
assert(image.size == size, "Cached image size doesn't match the requested image size")
return image
}
let image = self.imageForSize(size, opaque: opaque, drawingBlock: drawingBlock)
drawingCache.setObject(image, forKey: identifier)
return image
}
public class func imageForIdentifier(identifier: String) -> UIImage? {
return drawingCache.objectForKey(identifier) as? UIImage
}
public class func removeImageForIdentifier(identifier: String) {
drawingCache.removeObjectForKey(identifier)
}
public class func removeAllCachedImages() {
drawingCache.removeAllObjects()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment