Skip to content

Instantly share code, notes, and snippets.

@odrobnik
Created December 7, 2016 13:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odrobnik/ebcb19da06862e50f6b66ebfe31aff3c to your computer and use it in GitHub Desktop.
Save odrobnik/ebcb19da06862e50f6b66ebfe31aff3c to your computer and use it in GitHub Desktop.
Convenience method creating a new image by drawing into a context
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