I'm trying to clip a UIImage
based on a given UIBezierPath
, but the resulting image retains the original shape and size. I want the shape and size to resemble the path, i.e. the visible content of the new image.
Take a look at this following example:
The following is the code I am using to mask an image given a path:
func imageByApplyingClippingBezierPath(_ path: UIBezierPath) -> UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(
width: size.width,
height: size.height
), false, 0.0)
let context = UIGraphicsGetCurrentContext()!
context.saveGState()
path.addClip()
draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
context.restoreGState()
UIGraphicsEndImageContext()
return newImage
}
One solution would be to crop the image after masking it, but ideally I want this to be done as simple and efficiently as possible in one go.
Any solution/ tips would be appreciated.