Created
February 28, 2018 07:21
-
-
Save edwardean/bb8a79bb02e6b42ec1481d1f56d011b9 to your computer and use it in GitHub Desktop.
Swift Clip UIImage
This file contains hidden or 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 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