Last active
November 29, 2023 10:42
-
-
Save drumnkyle/c2ae34ea2422514c45d5 to your computer and use it in GitHub Desktop.
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