Skip to content

Instantly share code, notes, and snippets.

@edwardean
Created February 28, 2018 07:21
Show Gist options
  • Save edwardean/bb8a79bb02e6b42ec1481d1f56d011b9 to your computer and use it in GitHub Desktop.
Save edwardean/bb8a79bb02e6b42ec1481d1f56d011b9 to your computer and use it in GitHub Desktop.
Swift Clip UIImage
extension UIImage {
@objc public func clipWith(_ path: UIBezierPath) -> UIImage? {
let shotest = min(size.width, size.height)
let outputRect = CGRect(x: 0, y: 0, width: shotest, height: shotest)
UIGraphicsBeginImageContextWithOptions(outputRect.size, false, 0)
defer {
UIGraphicsEndImageContext()
}
guard let context = UIGraphicsGetCurrentContext() else { return nil }
context.addPath(path.cgPath)
context.clip()
self.draw(in: CGRect(x: (shotest - size.width)/2,
y: (shotest - size.height)/2,
width: size.width,
height: size.height))
guard let maskedImage = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
return maskedImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment