模糊UIImage以实现像swift的壁纸的密码模糊效果

时间:2014-10-23 11:51:51

标签: xcode swift uiblureffect

我想达到密码视图的效果(壁纸图片模糊,颜色较深)

这给我一个黑屏

func blurWithCoreImage(){

    var inputImage = CIImage(image: UIImage(named: "wallpaper"));

    // Apply gaussian blur filter with radius of 30
    var gaussianBlurFilter = CIFilter(name: "CIGaussianBlur");
    gaussianBlurFilter.setValue(inputImage, forKey: "inputImage")
    gaussianBlurFilter.setValue(30, forKey: "inputRadius")

    var context  =  CIContext(options:nil)
    var cgImage = context.createCGImage(gaussianBlurFilter.outputImage, fromRect: inputImage.extent())

    // Set up output context.
    UIGraphicsBeginImageContext(self.view.frame.size);
    var outputContext = UIGraphicsGetCurrentContext();

    // Invert image coordinates
    CGContextScaleCTM(outputContext, 1.0, -1.0);
    CGContextTranslateCTM(outputContext, 0, -self.view.frame.size.height);

    // Draw base image.
    CGContextDrawImage(outputContext, self.view.frame, cgImage);

    // Apply white tint
    CGContextSaveGState(outputContext);
    //  CGContextSetFillColorWithColor(outputContext, UIColor.blackColor().CGColor!);

    CGContextFillRect(outputContext, self.view.frame);
    CGContextRestoreGState(outputContext);

    // Output image is ready.
    var outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    backgroundImg.image =  outputImage;
}

此功能可使图像模糊但同时缩小图像并且在密码视图中距离效果太远

func blurWithCoreImage2(){
    var ciimage = CIImage(image: UIImage(named: "passcode"))

    var filter = CIFilter(name:"CIGaussianBlur")

    filter.setDefaults()

    filter.setValue(ciimage, forKey: kCIInputImageKey)

    filter.setValue(1, forKey: kCIInputRadiusKey)

    var outputImage = filter.outputImage;

    var finalImage = UIImage(CIImage: outputImage);
    backgroundImg.image =  finalImage;
    UIGraphicsEndImageContext();

}

3 个答案:

答案 0 :(得分:13)

由于您只需要支持iOS 8及更高版本,因此您可以使用新的UIVisualEffectView,这是添加模糊的新内置方法。

它非常易于使用,如下所示:

let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
let blurView = UIVisualEffectView(effect: blurEffect)
blurView.frame = myFrame
self.view.addSubview(blurView)

你可以看到你可以指定一个UIBlurEffectStyle,这样你也可以让它变暗。

答案 1 :(得分:2)

尝试此操作以模糊和裁剪图像

func applyBlurEffect(image: UIImage){
var imageToBlur = CIImage(image: image)
var blurfilter = CIFilter(name: "CIGaussianBlur")
blurfilter.setValue(5, forKey: kCIInputRadiusKey)
blurfilter.setValue(imageToBlur, forKey: "inputImage")
var resultImage = blurfilter.valueForKey("outputImage") as! CIImage
var blurredImage = UIImage(CIImage: resultImage)
var cropped:CIImage=resultImage.imageByCroppingToRect(CGRectMake(0, 0,imageToBlur.extent().size.width, imageToBlur.extent().size.height))
blurredImage = UIImage(CIImage: cropped)
self.backgroundImage.image = blurredImage
}

答案 2 :(得分:0)

我尝试更新答案,但这是无意义的否定。这是最新的语法:

Swift 3.1

let blurEffect = UIBlurEffect(style: .dark)
let blurView = UIVisualEffectView(effect: blurEffect)
self.view.addSubview(blurView)