Code to mask a square image to a circle
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
// UIImage+Utils.swift | |
// This is just one way to do this. | |
public func croppedToCircle() -> UIImage { | |
// Begin a new image that will be the new image with the rounded corners | |
UIGraphicsBeginImageContextWithOptions(size, false, scale) | |
let circleWidth = size.width | |
let radius = circleWidth / 2 | |
// draw the image here | |
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) | |
UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip() | |
draw(in: rect) | |
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
if let newImage = newImage { | |
return newImage | |
} else { | |
return self | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment