Skip to content

Instantly share code, notes, and snippets.

@drumnkyle
Last active November 29, 2023 10:42
Show Gist options
  • Save drumnkyle/c2ae34ea2422514c45d5 to your computer and use it in GitHub Desktop.
Save drumnkyle/c2ae34ea2422514c45d5 to your computer and use it in GitHub Desktop.
Code to mask a square image to a circle
// 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