Skip to content

Instantly share code, notes, and snippets.

@mathewsanders
Created October 14, 2016 19:20
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathewsanders/94ed8212587d72684291483905132790 to your computer and use it in GitHub Desktop.
Save mathewsanders/94ed8212587d72684291483905132790 to your computer and use it in GitHub Desktop.
Create CGContext from a CGSize
extension CGSize {
typealias ContextClosure = (_ context: CGContext, _ frame: CGRect) -> ()
func image(withContext context: ContextClosure) -> UIImage? {
UIGraphicsBeginImageContext(self)
let frame = CGRect(origin: .zero, size: self)
context(UIGraphicsGetCurrentContext()!, frame)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
let face = UIImage(named: "face.jpg")
let image = CGSize(width: 100, height: 100).image { context, frame in
// create a path to use both for clipping (masking) and the border
let path = UIBezierPath(ovalIn: frame)
path.addClip()
// the color to use as background tint and border color
let tint = UIColor.blue.cgColor
// add a blue background
context.setFillColor(tint)
context.fill(frame)
// add the profile image
face?.draw(in: frame, blendMode: .luminosity, alpha: 1)
// add the border
context.addPath(path.cgPath)
context.setStrokeColor(tint)
context.setLineWidth(5)
context.strokePath()
}
@mathewsanders
Copy link
Author

Using the UIGraphics functions don't feel very swifty to me so exploring with this little wrapper.

artboard

(Face from http://www.diverseui.com)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment