Created
October 14, 2016 19:20
-
-
Save mathewsanders/94ed8212587d72684291483905132790 to your computer and use it in GitHub Desktop.
Create CGContext from a CGSize
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
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 | |
} | |
} |
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
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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Using the UIGraphics functions don't feel very swifty to me so exploring with this little wrapper.
(Face from http://www.diverseui.com)