Ios: how to blur an image using CGPath?

enter image description here

I am creating a CGPath region as shown in the green circle. The CGPath area should be transparent, and the rest of the image will be blurry or translucent, I can crop the image inside CGPath with the 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 a blurry or translucent effect with CGPath at the same time. I think I can blur the original image and combine it with the image of the clip, but I don’t know how to implement it.

+4
source share
1 answer

It took you 2 concepts to achieve the final result: -

i) CGBlendMode ii) CIFilter

CGBlendMode is used to remove the desired part of the image. Constructing operations on paths that are in each other in the current context. Clear mode, whose rawValue - 16 helps clear the desired part.


CIFilter helps 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 accomplished

enter image description here

Final github demo

+1
source

Source: https://habr.com/ru/post/1483255/


All Articles