I create a CGPath area as shown green circle. The CGPath area need to be clear, and the rest of image will be applied blurry or translucent effect, I can clip image inside CGPath with following code:
UIGraphicsBeginImageContext(view.frame.size);
CGContextAddPath(ctx, path);
CGContextClip(ctx);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(clipImage, nil, nil, nil);
CGPathRelease(path);
but I don't know how to apply blurry or translucent effect with CGPath simultaneously. I think I can blur origin image and merge it with clip image, but I don't know how to implement it.
You required 2 concept to achieved end result :-
i) CGBlendMode ii) CIFilter
CGBlendMode is Used to remove the desired portion from image. Compositing operations on paths residing one another in the Current Context . Clear mode whose rawValue is 16 help to clear the desired portion.
CIFilter help to blur the final image.
class ConvertToBlurryImage:UIView {
var originalImage:UIImage!
var finalImage:UIImage!
override func draw(_ rect: CGRect) {
super.draw(rect)
//Original Image
originalImage = UIImage(named: "originalImage.png")
//Intermediate Image
let intermediateImage = UIImage().returnBlurImage(image: originalImage)
//Final Result Image
finalImage = blendImage(image: intermediateImage)
let attachedImage = UIImageView(image: finalImage)
addSubview(attachedImage)
}
func blurryImage(image:UIImage) -> UIImage {
UIGraphicsBeginImageContext(frame.size)
image.draw(in: CGRect(origin: frame.origin, size: frame.size) )
// 16 === clear
let mode = CGBlendMode(rawValue: 16)
UIGraphicsGetCurrentContext()!.setBlendMode(mode!)
//Path that need to crop
pathToCrop()
let mode2 = CGBlendMode(rawValue: 16)
UIGraphicsGetCurrentContext()!.setBlendMode(mode2!)
let finalImage = UIGraphicsGetImageFromCurrentImageContext()
return finalImage!
}
func pathToCrop() {
let path = UIBezierPath(ovalIn: CGRect(x: frame.width/2 - 50, y: frame.height/2 - 100 , width: 150, height: 150) )
path.fill()
path.stroke()
}
}
extension UIImage {
func returnBlurImage(image:UIImage) -> UIImage {
let beginImage = CIImage(cgImage: image.cgImage!)
let blurfilter = CIFilter(name: "CIGaussianBlur")
blurfilter?.setValue(beginImage, forKey: "inputImage")
let resultImage = blurfilter?.value(forKey: "outputImage") as! CIImage
let blurredImage = UIImage(ciImage: resultImage)
return blurredImage
}
}
Mission Achived
Final Github Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With