Last active
August 29, 2015 14:21
-
-
Save kirsteins/23d90ee8593c0517f658 to your computer and use it in GitHub Desktop.
Drawing cache
This file contains 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
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