Created
December 7, 2016 13:53
-
-
Save odrobnik/ebcb19da06862e50f6b66ebfe31aff3c to your computer and use it in GitHub Desktop.
Convenience method creating a new image by drawing into a context
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
import UIKit | |
extension UIImage | |
{ | |
/// Creates an image from drawing into a context | |
convenience init(size: CGSize, opaque: Bool = true, operations: (CGContext)->()) | |
{ | |
UIGraphicsBeginImageContextWithOptions(size, opaque, 0) | |
let ctx = UIGraphicsGetCurrentContext()! | |
operations(ctx) | |
let image = UIGraphicsGetImageFromCurrentImageContext()! | |
UIGraphicsEndImageContext() | |
self.init(cgImage: image.cgImage!, scale: image.scale, orientation: image.imageOrientation) | |
} | |
public func resized(to size: CGSize) -> UIImage | |
{ | |
let image = UIImage(size: size, opaque: false) { context in | |
self.draw(in: CGRect(origin: .zero, size: size)) | |
} | |
return image | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment