5

在此处输入图像描述

我创建了一个 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 应用模糊或半透明效果。我想我可以模糊原始图像并将其与剪辑图像合并,但我不知道如何实现它。

4

1 回答 1

1

您需要 2 个概念来实现最终结果:-

i) CGBlendMode ii) CIFilter

CGBlendMode 用于从图像中删除所需的部分。在 Current Context 中相互驻留的路径上进行合成操作。rawValue 为 16的清除模式有助于清除所需部分。


CIFilter 有助于模糊最终图像。

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
        
        
        
    }
    
}

完成任务

在此处输入图像描述

最终的 Github 演示

于 2016-12-16T13:43:08.503 回答