ios:如何使用CGPath模糊图像?

我创建了一个CGPath区域,如图所示的绿色圆圈. CGPath区域需要清晰,其余的图像将应用模糊或半透明效果,我可以使用以下代码在CGPath内剪辑图像:

UIGraphicsBeginImageContext(view.frame.size);
CGContextAddPath(ctx, path);
CGContextClip(ctx);

[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *clipImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(clipImage, nil, nil, nil);
CGPathRelease(path);

但我不知道如何同时使用CGPath应用模糊或半透明效果.我想我可以模糊原始图像并将其与剪辑图像合并,但我不知道如何实现它.

您需要2个概念才能达到最终结果: –

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



    }

}

任务实现

enter image description here

Final Github Demo

相关文章
相关标签/搜索