创建模糊叠加视图

问题描述 投票:353回答:24

在新iOS的音乐应用程序中,我们可以看到一个模糊背后的专辑封面。

如何才能完成这样的事情?我已经阅读了文档,但没有找到任何内容。

ios objective-c graphics filtering core-image
24个回答
521
投票

您可以使用UIVisualEffectView来实现此效果。这是一个本机API,经过微调,性能和电池寿命长,而且易于实现。

迅速:

//only apply the blur if the user hasn't disabled transparency effects
if !UIAccessibility.isReduceTransparencyEnabled {
    view.backgroundColor = .clear

    let blurEffect = UIBlurEffect(style: .dark)
    let blurEffectView = UIVisualEffectView(effect: blurEffect)
    //always fill the view
    blurEffectView.frame = self.view.bounds
    blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    view.addSubview(blurEffectView) //if you have more UIViews, use an insertSubview API to place it where needed
} else {
    view.backgroundColor = .black
}

Objective-C的:

//only apply the blur if the user hasn't disabled transparency effects
if (!UIAccessibilityIsReduceTransparencyEnabled()) {
    self.view.backgroundColor = [UIColor clearColor];

    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    //always fill the view
    blurEffectView.frame = self.view.bounds;
    blurEffectView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    [self.view addSubview:blurEffectView]; //if you have more UIViews, use an insertSubview API to place it where needed
} else {
    self.view.backgroundColor = [UIColor blackColor];
}

如果您以模态方式呈现此视图控制器以模糊基础内容,则需要将模态演示文稿样式设置为“当前上下文”并将背景颜色设置为“清除”以确保基础视图控制器在显示为超出时保持可见。


3
投票

enter image description here

从Xcode您可以轻松完成。按照xcode中的步骤操作。在您的uiview或imageview上展示视觉效果视图。

快乐编码:)


2
投票

偶然发现这个,给了我非常好的(与Apple的重复)结果,并使用Acceleration框架。 - http://pastebin.com/6cs6hsyQ *不是我写的


2
投票

Using UIImageEffects

对于想要更多控制的人,您可以使用Apple的UIImageEffects示例代码。

您可以从Apple的开发人员库中复制UIImageEffects的代码:Blurring and Tinting an Image

And here's how to apply it :

#import "UIImageEffects.h"
...

self.originalImageView.image = [UIImageEffects imageByApplyingLightEffectToImage:[UIImage imageNamed:@"yourImage.png"]];

2
投票
func blurBackgroundUsingImage(image: UIImage)
{
    var frame                   = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
    var imageView               = UIImageView(frame: frame)
    imageView.image             = image
    imageView.contentMode       = .ScaleAspectFill
    var blurEffect              = UIBlurEffect(style: .Light)
    var blurEffectView          = UIVisualEffectView(effect: blurEffect)
    blurEffectView.frame        = frame
    var transparentWhiteView    = UIView(frame: frame)
    transparentWhiteView.backgroundColor = UIColor(white: 1.0, alpha: 0.30)
    var viewsArray              = [imageView, blurEffectView, transparentWhiteView]

    for index in 0..<viewsArray.count {
        if let oldView = self.view.viewWithTag(index + 1) {
            var oldView         = self.view.viewWithTag(index + 1)
            // Must explicitly unwrap oldView to access its removeFromSuperview() method as of Xcode 6 Beta 5
            oldView!.removeFromSuperview()
        }
        var viewToInsert        = viewsArray[index]
        self.view.insertSubview(viewToInsert, atIndex: index + 1)
        viewToInsert.tag        = index + 1
    }
}

1
投票

Apple为UIImage类提供了一个名为UIImage + ImageEffects.h的扩展。在本课程中,您可以使用所需的方法来模糊视图


1
投票

这个答案是基于Mitja Semolic's excellent earlier answer。我已经将它转换为swift 3,添加了解释在coments中发生的事情,使其成为UIViewController的扩展,因此任何VC都可以随意调用它,添加了一个不显眼的视图来显示选择性应用程序,并添加了一个完成块,以便调用视图控制器可以在模糊完成时执行任何操作。

    import UIKit
//This extension implements a blur to the entire screen, puts up a HUD and then waits and dismisses the view.
    extension UIViewController {
        func blurAndShowHUD(duration: Double, message: String, completion: @escaping () -> Void) { //with completion block
            //1. Create the blur effect & the view it will occupy
            let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
            let blurEffectView = UIVisualEffectView()//(effect: blurEffect)
            blurEffectView.frame = self.view.bounds
            blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

        //2. Add the effect view to the main view
            self.view.addSubview(blurEffectView)
        //3. Create the hud and add it to the main view
        let hud = HudView.getHUD(view: self.view, withMessage: message)
        self.view.addSubview(hud)
        //4. Begin applying the blur effect to the effect view
        UIView.animate(withDuration: 0.01, animations: {
            blurEffectView.effect = blurEffect
        })
        //5. Halt the blur effects application to achieve the desired blur radius
        self.view.pauseAnimationsInThisView(delay: 0.004)
        //6. Remove the view (& the HUD) after the completion of the duration
        DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
            blurEffectView.removeFromSuperview()
            hud.removeFromSuperview()
            self.view.resumeAnimationsInThisView()
            completion()
        }
    }
}

extension UIView {
    public func pauseAnimationsInThisView(delay: Double) {
        let time = delay + CFAbsoluteTimeGetCurrent()
        let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, time, 0, 0, 0, { timer in
            let layer = self.layer
            let pausedTime = layer.convertTime(CACurrentMediaTime(), from: nil)
            layer.speed = 0.0
            layer.timeOffset = pausedTime
        })
        CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, CFRunLoopMode.commonModes)
    }
    public func resumeAnimationsInThisView() {
        let pausedTime  = layer.timeOffset

        layer.speed = 1.0
        layer.timeOffset = 0.0
        layer.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
    }
}

我已经确认它适用于iOS 10.3.1和iOS 11


1
投票

@Joey答案的重要补充

这适用于你想要用UIViewController呈现模糊背景UINavigationController的情况。

// suppose you've done blur effect with your presented view controller
UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController];

// this is very important, if you don't do this, the blur effect will darken after view did appeared
// the reason is that you actually present navigation controller, not presented controller
// please note it's "OverFullScreen", not "OverCurrentContext"
nav.modalPresentationStyle = UIModalPresentationOverFullScreen;

UIViewController *presentedViewController = [[UIViewController alloc] init]; 
// the presented view controller's modalPresentationStyle is "OverCurrentContext"
presentedViewController.modalPresentationStyle = UIModalPresentationOverCurrentContext;

[presentingViewController presentViewController:nav animated:YES completion:nil];

请享用!


1
投票

这是一种使用UIViewPropertyAnimator添加自定义模糊而无需使用私有API讨价还价的简单方法:

首先,声明类属性:

var blurAnimator: UIViewPropertyAnimator!

然后在viewDidLoad()中设置模糊视图:

let blurEffectView = UIVisualEffectView()
blurEffectView.backgroundColor = .clear
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)

blurAnimator = UIViewPropertyAnimator(duration: 1, curve: .linear) { [blurEffectView] in
    blurEffectView.effect = UIBlurEffect(style: .light)
}

blurAnimator.fractionComplete = 0.15 // set the blur intensity.    

注意:此解决方案不适用于UICollectionView / UITableView细胞


0
投票

以下是已接受答案中提供的解决方案的Swift 2.0代码:

    //only apply the blur if the user hasn't disabled transparency effects
    if !UIAccessibilityIsReduceTransparencyEnabled() {
        self.view.backgroundColor = UIColor.clearColor()

        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        //always fill the view
        blurEffectView.frame = self.view.bounds
        blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]

        self.view.addSubview(blurEffectView) //if you have more UIViews, use an insertSubview API to place it where needed
    } else {
        self.view.backgroundColor = UIColor.blackColor()
    }

0
投票

如果为tableView添加一个黑暗的模糊视图,这将很好地使它:

tableView.backgroundColor = .clear
let blurEffect = UIBlurEffect(style: .dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = tableView.bounds
blurEffectView.autoresizingMask = [.flexibleHeight, .flexibleWidth]


// Assigning blurEffectView to backgroundView instead of addSubview to tableView makes tableView cell not blocked by blurEffectView 
tableView.backgroundView = blurEffectView

280
投票

核心形象

由于屏幕截图中的图像是静态的,因此您可以使用Core Image中的CIGaussianBlur(需要iOS 6)。这是样本:https://github.com/evanwdavis/Fun-with-Masks/blob/master/Fun%20with%20Masks/EWDBlurExampleVC.m

请注意,这比此页面上的其他选项慢。

#import <QuartzCore/QuartzCore.h>

- (UIImage*) blur:(UIImage*)theImage
{   
    // ***********If you need re-orienting (e.g. trying to blur a photo taken from the device camera front facing camera in portrait mode)
    // theImage = [self reOrientIfNeeded:theImage];

    // create our blurred image
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *inputImage = [CIImage imageWithCGImage:theImage.CGImage];

    // setting up Gaussian Blur (we could use one of many filters offered by Core Image)
    CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [filter setValue:inputImage forKey:kCIInputImageKey];
    [filter setValue:[NSNumber numberWithFloat:15.0f] forKey:@"inputRadius"];
    CIImage *result = [filter valueForKey:kCIOutputImageKey];

    // CIGaussianBlur has a tendency to shrink the image a little, 
    // this ensures it matches up exactly to the bounds of our original image
    CGImageRef cgImage = [context createCGImage:result fromRect:[inputImage extent]];

    UIImage *returnImage = [UIImage imageWithCGImage:cgImage];//create a UIImage for this function to "return" so that ARC can manage the memory of the blur... ARC can't manage CGImageRefs so we need to release it before this function "returns" and ends.
    CGImageRelease(cgImage);//release CGImageRef because ARC doesn't manage this on its own.

    return returnImage;

    // *************** if you need scaling
    // return [[self class] scaleIfNeeded:cgImage];
}

+(UIImage*) scaleIfNeeded:(CGImageRef)cgimg {
    bool isRetina = [[[UIDevice currentDevice] systemVersion] intValue] >= 4 && [[UIScreen mainScreen] scale] == 2.0;
    if (isRetina) {
        return [UIImage imageWithCGImage:cgimg scale:2.0 orientation:UIImageOrientationUp];
    } else {
        return [UIImage imageWithCGImage:cgimg];
    }
}

- (UIImage*) reOrientIfNeeded:(UIImage*)theImage{

    if (theImage.imageOrientation != UIImageOrientationUp) {

        CGAffineTransform reOrient = CGAffineTransformIdentity;
        switch (theImage.imageOrientation) {
            case UIImageOrientationDown:
            case UIImageOrientationDownMirrored:
                reOrient = CGAffineTransformTranslate(reOrient, theImage.size.width, theImage.size.height);
                reOrient = CGAffineTransformRotate(reOrient, M_PI);
                break;
            case UIImageOrientationLeft:
            case UIImageOrientationLeftMirrored:
                reOrient = CGAffineTransformTranslate(reOrient, theImage.size.width, 0);
                reOrient = CGAffineTransformRotate(reOrient, M_PI_2);
                break;
            case UIImageOrientationRight:
            case UIImageOrientationRightMirrored:
                reOrient = CGAffineTransformTranslate(reOrient, 0, theImage.size.height);
                reOrient = CGAffineTransformRotate(reOrient, -M_PI_2);
                break;
            case UIImageOrientationUp:
            case UIImageOrientationUpMirrored:
                break;
        }

        switch (theImage.imageOrientation) {
            case UIImageOrientationUpMirrored:
            case UIImageOrientationDownMirrored:
                reOrient = CGAffineTransformTranslate(reOrient, theImage.size.width, 0);
                reOrient = CGAffineTransformScale(reOrient, -1, 1);
                break;
            case UIImageOrientationLeftMirrored:
            case UIImageOrientationRightMirrored:
                reOrient = CGAffineTransformTranslate(reOrient, theImage.size.height, 0);
                reOrient = CGAffineTransformScale(reOrient, -1, 1);
                break;
            case UIImageOrientationUp:
            case UIImageOrientationDown:
            case UIImageOrientationLeft:
            case UIImageOrientationRight:
                break;
        }

        CGContextRef myContext = CGBitmapContextCreate(NULL, theImage.size.width, theImage.size.height, CGImageGetBitsPerComponent(theImage.CGImage), 0, CGImageGetColorSpace(theImage.CGImage), CGImageGetBitmapInfo(theImage.CGImage));

        CGContextConcatCTM(myContext, reOrient);

        switch (theImage.imageOrientation) {
            case UIImageOrientationLeft:
            case UIImageOrientationLeftMirrored:
            case UIImageOrientationRight:
            case UIImageOrientationRightMirrored:
                CGContextDrawImage(myContext, CGRectMake(0,0,theImage.size.height,theImage.size.width), theImage.CGImage);
                break;

            default:
                CGContextDrawImage(myContext, CGRectMake(0,0,theImage.size.width,theImage.size.height), theImage.CGImage);
                break;
        }

        CGImageRef CGImg = CGBitmapContextCreateImage(myContext);
        theImage = [UIImage imageWithCGImage:CGImg];

        CGImageRelease(CGImg);
        CGContextRelease(myContext);
    }

    return theImage;
}

堆栈模糊(Box + Gaussian)

  • StackBlur这实现了Box和高斯模糊的混合。比非加速高斯快7倍,但不像盒子模糊那么难看。请参阅here(Java插件版本)或here(JavaScript版本)中的演示。该算法用于KDE和Camera +等。它不使用Accelerate Framework,但速度很快。

加速框架

  • WWDC 2013的“在iOS上实现引导UI”会议中,Apple解释了如何创建模糊背景(在14:30),并提到了使用Accelerate.framework在示例代码中实现的方法applyLightEffect
  • GPUImage使用OpenGL着色器创建动态模糊。它有几种类型的模糊:GPUImageBoxBlurFilter,GPUImageFastBlurFilter,GaussianSelectiveBlur,GPUImageGaussianBlurFilter。甚至还有一个GPUImageiOSBlurFilter“应该完全复制iOS 7控制面板提供的模糊效果”(tweetarticle)。这篇文章详细而且内容丰富。
    -(UIImage *)blurryGPUImage:(UIImage *)image withBlurLevel:(NSInteger)blur {
        GPUImageFastBlurFilter *blurFilter = [GPUImageFastBlurFilter new];
        blurFilter.blurSize = blur;
        UIImage *result = [blurFilter imageByFilteringImage:image];
        return result;
    }

其他的东西

Andy Matuschak said在推特上说:“你知道,很多地方看起来我们都在实时做这件事,但这很聪明,技巧娴熟。”

doubleencore.com,他们说“我们发现在大多数情况下,10 pt模糊半径加上10 pt饱和度增加最能模仿iOS 7的模糊效果”。

看看Apple的SBFProceduralWallpaperView的私人标题。

最后,这不是真正的模糊,但请记住,您可以设置rasterizationScale来获取像素化图像:http://www.dimzzy.com/blog/2010/11/blur-effect-for-uiview/


0
投票

Swv3版Kev回答模糊图像的答案 -

func blurBgImage(image: UIImage) -> UIImage? {
        let radius: CGFloat = 20;
        let context = CIContext(options: nil);
        let inputImage = CIImage(cgImage: image.cgImage!);
        let filter = CIFilter(name: "CIGaussianBlur");
        filter?.setValue(inputImage, forKey: kCIInputImageKey);
        filter?.setValue("\(radius)", forKey:kCIInputRadiusKey);

        if let result = filter?.value(forKey: kCIOutputImageKey) as? CIImage{

            let rect = CGRect(origin: CGPoint(x: radius * 2,y :radius * 2), size: CGSize(width: image.size.width - radius * 4, height: image.size.height - radius * 4))

            if let cgImage = context.createCGImage(result, from: rect){
                return UIImage(cgImage: cgImage);
                }
        }
        return nil;
    }

0
投票

您可以使用“带模糊的视觉效果视图”和“带模糊和活力的视觉效果视图”直接制作背景模糊。

在iOS应用程序中制作模糊背景所需要做的就是......

  1. 在对象库中搜索“带模糊的视觉效果视图”

Step 1 Image

  1. 在故事板中拖动“带模糊的视觉效果视图”并设置它......

Step 2 Image

  1. 最后......你让你的应用背景模糊!

Application Layout before clicking on any Button!

Application View After Clicking on Button which makes the whole application background Blur!


-1
投票

斯威夫特4:

添加叠加层或弹出窗口视图您还可以使用容器视图来获取免费的视图控制器(从常用的对象选项板/库中获取容器视图)

脚步:

拥有一个包含此容器视图的视图(图片中的ViewForContainer),在显示容器视图的内容时将其调暗。连接第一个View Controller内的插座

加载第一个VC时隐藏此视图

单击按钮时取消隐藏在此处输入图像描述

要在显示容器视图内容时调暗此视图,请将视图背景设置为黑色,将不透明度设置为30%

我在其他Stackoverflow问题https://stackoverflow.com/a/49729431/5438240中添加了popview视图创建的答案


-1
投票

Swift 4.2:

在视频或图像上显示模糊效果的最简单方法。

1)使用UICustomBlurEffect设置模糊半径的自定义值,如下所示。

2)记住在将其添加到UIVisualEffectView之前设置模糊值,否则您的模糊值将不会在视图上设置。

3)您可以将它用于图像或在playerLayer上显示实时模糊。

希望能帮助到你 :)

    let blurEffect = (NSClassFromString("_UICustomBlurEffect") as! UIBlurEffect.Type).init()
 //Don't Forget to set blurValue before adding it to View
    blurEffect.setValue(15, forKey: "blurRadius")

    let blurView = UIVisualEffectView(effect: blurEffect)

//Add blur View on top of any view you want to blur
    view.insertSubview(blurView!, at: 1)

-3
投票

简单的答案是添加子视图并更改它的alpha。

UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)];
UIView *subView = [[UIView alloc] initWithFrame:popupView.frame];
UIColor * backImgColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"blue_Img.png"]];
subView.backgroundColor = backImgColor;
subView.alpha = 0.5;
[mainView addSubview:subView];

15
投票

我决定从接受的答案中发布一个书面的Objective-C版本,以便在这个问题中提供更多选项。

- (UIView *)applyBlurToView:(UIView *)view withEffectStyle:(UIBlurEffectStyle)style andConstraints:(BOOL)addConstraints
{
  //only apply the blur if the user hasn't disabled transparency effects
  if(!UIAccessibilityIsReduceTransparencyEnabled())
  {
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:style];
    UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    blurEffectView.frame = view.bounds;

    [view addSubview:blurEffectView];

    if(addConstraints)
    {
      //add auto layout constraints so that the blur fills the screen upon rotating device
      [blurEffectView setTranslatesAutoresizingMaskIntoConstraints:NO];

      [view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
                                                       attribute:NSLayoutAttributeTop
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:view
                                                       attribute:NSLayoutAttributeTop
                                                      multiplier:1
                                                        constant:0]];

      [view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
                                                       attribute:NSLayoutAttributeBottom
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:view
                                                       attribute:NSLayoutAttributeBottom
                                                      multiplier:1
                                                        constant:0]];

      [view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
                                                       attribute:NSLayoutAttributeLeading
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:view
                                                       attribute:NSLayoutAttributeLeading
                                                      multiplier:1
                                                        constant:0]];

      [view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
                                                       attribute:NSLayoutAttributeTrailing
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:view
                                                       attribute:NSLayoutAttributeTrailing
                                                      multiplier:1
                                                        constant:0]];
    }
  }
  else
  {
    view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
  }

  return view;
}

如果您只想支持纵向模式,或者我只是在此函数中添加一个标志以便使用它们,那么可以删除约束。


13
投票

我不认为我可以发布代码,但上面提到WWDC示例代码的帖子是正确的。这是链接:https://developer.apple.com/downloads/index.action?name=WWDC%202013

您要查找的文件是UIImage上的类别,方法是applyLightEffect。

正如我在评论中所提到的,Apple Blur除了模糊之外还有饱和度和其他事情。一个简单的模糊不会...如果你想模仿他们的风格。


9
投票

我认为最简单的解决方案是覆盖UIToolbar,它在iOS 7中模糊了它背后的一切。它非常狡猾,但它实现起来非常简单,而且速度快!

您可以使用任何视图执行此操作,只需将其设为UIToolbar的子类而不是UIView。你甚至可以用UIViewControllerview财产来做,例如......

1)创建一个新类,它是UIViewController的“子类”,并选中“With XIB for user interface”框。

2)选择View并转到右侧面板中的身份检查器(alt-command-3)。将“Class”更改为UIToolbar。现在转到属性检查器(alt-command-4)并将“背景”颜色更改为“清除颜色”。

3)将子视图添加到主视图并将其连接到界面中的IBOutlet。称之为backgroundColorView。它看起来像这样,作为实现(.m)文件中的私有类。

@interface BlurExampleViewController ()
@property (weak, nonatomic) IBOutlet UIView *backgroundColorView;
@end

4)转到视图控制器实现(.m)文件并更改-viewDidLoad方法,如下所示:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.barStyle = UIBarStyleBlack; // this will give a black blur as in the original post
    self.backgroundColorView.opaque = NO;
    self.backgroundColorView.alpha = 0.5;
    self.backgroundColorView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:1];
}

这会给你一个深灰色的视图,模糊背后的一切。没有有趣的业务,没有缓慢的核心图像模糊,使用OS / SDK提供的触手可及的一切。

您可以将此视图控制器的视图添加到另一个视图,如下所示:

[self addChildViewController:self.blurViewController];
[self.view addSubview:self.blurViewController.view];
[self.blurViewController didMoveToParentViewController:self];

// animate the self.blurViewController into view

如果有什么不清楚,请告诉我,我很乐意提供帮助!


编辑

UIToolbar在7.0.3中已更改,在使用彩色模糊时可能会产生不良影响。

我们曾经能够使用barTintColor设置颜色,但如果你之前这样做,你需要将alpha组件设置为小于1.否则你的UIToolbar将是完全不透明的颜色 - 没有模糊。

这可以通过以下方式实现:(记住selfUIToolbar的子类)

UIColor *color = [UIColor blueColor]; // for example
self.barTintColor = [color colorWithAlphaComponent:0.5];

这将为模糊的视图提供蓝色色调。


8
投票

这是使用CIGaussianBlur在Swift中的快速实现:

func blur(image image: UIImage) -> UIImage {
    let radius: CGFloat = 20;
    let context = CIContext(options: nil);
    let inputImage = CIImage(CGImage: image.CGImage!);
    let filter = CIFilter(name: "CIGaussianBlur");
    filter?.setValue(inputImage, forKey: kCIInputImageKey);
    filter?.setValue("\(radius)", forKey:kCIInputRadiusKey);
    let result = filter?.valueForKey(kCIOutputImageKey) as! CIImage;
    let rect = CGRectMake(radius * 2, radius * 2, image.size.width - radius * 4, image.size.height - radius * 4)
    let cgImage = context.createCGImage(result, fromRect: rect);
    let returnImage = UIImage(CGImage: cgImage);

    return returnImage;
}

5
投票

接受的答案是正确的,但这里有一个重要的步骤,如果这个视图 - 你想要模糊的背景 - 使用

[self presentViewController:vc animated:YES completion:nil]

默认情况下,这会消除模糊,因为UIKit会删除演示者的视图,而视图实际上是模糊的。要避免删除,请在上一行之前添加此行

vc.modalPresentationStyle = UIModalPresentationOverFullScreen;

或使用其他Over样式。


5
投票

自定义模糊比例

You can try UIVisualEffectView,自定义设置为 -

class BlurViewController: UIViewController {
    private let blurEffect = (NSClassFromString("_UICustomBlurEffect") as! UIBlurEffect.Type).init()

    override func viewDidLoad() {
        super.viewDidLoad()
        let blurView = UIVisualEffectView(frame: UIScreen.main.bounds)
        blurEffect.setValue(1, forKeyPath: "blurRadius")
        blurView.effect = blurEffect
        view.addSubview(blurView)
    }   
}

输出: - 对于blurEffect.setValue(1...blurEffect.setValue(2.. enter image description here enter image description here


3
投票

Objective-C的

UIVisualEffect *blurEffect;
blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
UIVisualEffectView *visualEffectView;
visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
visualEffectView.frame = self.accessImageView.bounds;
[self.accessImageView addSubview:visualEffectView];

SWIFT 3.0

let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(blurEffectView)

来自:https://stackoverflow.com/a/24083728/4020910

© www.soinside.com 2019 - 2024. All rights reserved.