392

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

这样的事情怎么可能完成?我已经阅读了文档,但在那里没有找到任何东西。

4

25 回答 25

588

你可以使用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
}

目标-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];
}

如果您以模态方式呈现此视图控制器以模糊底层内容,则需要将模态呈现样式设置为 Over Current Context 并将背景颜色设置为清除以确保底层视图控制器在其呈现在上面时仍然可见。

于 2014-09-07T01:17:49.523 回答
288

核心形象

由于屏幕截图中的图像是静态的,因此您可以使用CIGaussianBlurCore Image(需要 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 和 Gaussian 模糊的混合。比非加速高斯快 7 倍,但不像框模糊那么难看。在此处(Java 插件版本)或此处(JavaScript 版本)查看演示。该算法用于 KDE 和 Camera+ 等。它不使用加速框架,但速度很快。

加速框架

  • 在来自WWDC 2013的会议“在 iOS 上实现 Engaging UI”中,Apple 解释了如何创建模糊背景(在 14:30),并提到了applyLightEffect在示例代码中使用 Accelerate.framework 实现的方法。

  • GPUImage使用 OpenGL 着色器来创建动态模糊。它有几种模糊类型:GPUImageBoxBlurFilter、GPUImageFastBlurFilter、GaussianSelectiveBlur、GPUImageGaussianBlurFilter。甚至还有一个 GPUImageiOSBlurFilter “应该完全复制 iOS 7 的控制面板提供的模糊效果”(推文文章)。这篇文章很详细,内容丰富。

    -(UIImage *)blurryGPUImage:(UIImage *)image withBlurLevel:(NSInteger)blur {
        GPUImageFastBlurFilter *blurFilter = [GPUImageFastBlurFilter new];
        blurFilter.blurSize = 模糊;
        UIImage *result = [blurFilter imageByFilteringImage:image];
        返回结果;
    }
  • 来自 indieambitions.com:使用 vImage 执行模糊。该算法也用于iOS-RealTimeBlur

  • 来自 Nick Lockwood:https ://github.com/nicklockwood/FXBlurView该示例显示了滚动视图上的模糊。它使用 dispatch_async 进行模糊,然后使用 UITrackingRunLoopMode 同步调用更新,因此当 UIKit 将更多优先级赋予 UIScrollView 的滚动时,模糊不会滞后。Nick 的书iOS Core Animation对此进行了解释,顺便说一句,它很棒。

  • iOS-blur这会将 UIToolbar 的模糊层放到其他地方。如果您使用此方法,Apple 将拒绝您的应用程序。见https://github.com/mochidev/MDBlurView/issues/4

  • 来自 Evadne 博客:LiveFrost:快速、同步的 UIView 快照卷积。伟大的代码和伟大的阅读。这篇文章的一些想法:

    • 使用串行队列来限制来自 CADisplayLink 的更新。
    • 除非边界改变,否则重用位图上下文。
    • 使用具有 0.5f 比例因子的 -[CALayer renderInContext:] 绘制较小的图像。

其他的东西

安迪·马图沙克在推特上:“你知道,很多看起来我们正在实时进行的地方,它是静态的,带有巧妙的技巧。”

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

查看 Apple 的SBFProceduralWallpaperView的私有标题。

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

于 2013-06-11T10:32:02.653 回答
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;
}

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

于 2015-02-23T04:14:36.140 回答
14

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

你要找的文件是UIImage上的category,方法是applyLightEffect。

正如我在上面的评论中指出的那样,Apple Blur 除了模糊之外还有饱和度和其他情况。一个简单的模糊不会做......如果你想效仿他们的风格。

于 2013-06-17T05:25:36.357 回答
13

这是一种添加自定义模糊的简单方法,无需使用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/ UITableViewcell

于 2019-03-27T13:16:52.223 回答
10

这是使用 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;
}
于 2016-02-26T01:09:21.063 回答
9

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

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

1) 创建一个新类,它是“子类” UIViewController,并选中“使用 XIB 作为用户界面”复选框。

2) 选择视图并转到右侧面板中的身份检查器 (alt-command-3)。将“类”更改为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 将是完全不透明的颜色 - 没有模糊。

这可以通过以下方式实现:(记住self是 的子类UIToolbar

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

这会给模糊的视图带来蓝色调。

于 2013-10-15T10:38:36.623 回答
8

在此处输入图像描述

从 Xcode 你可以很容易地做到这一点。按照 xcode 中的步骤操作。在您的 uiview 或 imageview 上拖动视觉效果视图。

快乐编码:)

于 2018-04-09T10:27:41.513 回答
6

自定义模糊比例

您可以尝试 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)
    }   
}

输出:- for blurEffect.setValue(1...& blurEffect.setValue(2.. 在此处输入图像描述 在此处输入图像描述

于 2018-07-18T15:53:05.200 回答
6

如果这对任何人都有帮助,这是我根据 Jordan H 的回答创建的一个快速扩展。它是用 Swift 5 编写的,可以从 Objective C 中使用。

extension UIView {

    @objc func blurBackground(style: UIBlurEffect.Style, fallbackColor: UIColor) {
        if !UIAccessibility.isReduceTransparencyEnabled {
            self.backgroundColor = .clear

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

            self.insertSubview(blurEffectView, at: 0)
        } else {
            self.backgroundColor = fallbackColor
        }
    }

}

注意:如果你想模糊UILabel的背景而不影响文字,你应该创建一个容器UIView,将UILabel作为子视图添加到容器UIView中,将UILabel的backgroundColor设置为UIColor.clear,然后调用blurBackground(style : UIBlurEffect.Style, fallbackColor: UIColor) 在容器 UIView 上。这是一个用 Swift 5 编写的快速示例:

let frame = CGRect(x: 50, y: 200, width: 200, height: 50)
let containerView = UIView(frame: frame)
let label = UILabel(frame: frame)
label.text = "Some Text"
label.backgroundColor = UIColor.clear
containerView.addSubview(label)
containerView.blurBackground(style: .dark, fallbackColor: UIColor.black)
于 2019-10-07T20:12:29.047 回答
5

接受的答案是正确的,但这里缺少一个重要步骤,以防这个视图 - 您想要模糊背景 - 使用

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

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

vc.modalPresentationStyle = UIModalPresentationOverFullScreen;

或者使用其他Over样式。

于 2015-12-02T12:43:34.417 回答
3

目标-C

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

斯威夫特 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

于 2016-12-14T00:57:27.197 回答
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
    }
}
于 2015-06-21T10:58:00.500 回答
2

使用 UIImageEffects

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

UIImageEffects 您可以从 Apple 的开发人员库中复制代码:模糊和着色图像

以下是如何应用它:

#import "UIImageEffects.h"
...

self.originalImageView.image = [UIImageEffects imageByApplyingLightEffectToImage:[UIImage imageNamed:@"yourImage.png"]];
于 2016-02-08T01:01:00.900 回答
1

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

于 2013-09-11T14:30:56.300 回答
1

此答案基于Mitja Semolic 的出色早期答案。我已将其转换为 swift 3,在评论中添加了对正在发生的事情的解释,使其成为 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

于 2017-10-18T15:31:06.357 回答
1

@Joey 回答的重要补充

这适用于您想UIViewControllerUINavigationController.

// 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];

享受!

于 2018-02-06T07:30:15.117 回答
1

Swift 3 版本的 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;
    }
于 2018-11-26T15:10:57.627 回答
0

Apple 为 UIImage 类提供了一个扩展名为 UIImage+ImageEffects.h。在这个类中,您有所需的方法来模糊您的视图

于 2015-01-21T08:51:05.117 回答
0

2019代码

这是一个使用惊人的@AdamBardon 技术的更完整的示例。

@IBDesignable class ButtonOrSomethingWithBlur: UIButton {

    var ba: UIViewPropertyAnimator?
    private lazy var blurry: BlurryBall = { return BlurryBall() }()

    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        
        // Setup the blurry ball.  BE SURE TO TEARDOWN.
        // Use superb trick to access the internal guassian level of Apple's
        // standard gpu blurrer per stackoverflow.com/a/55378168/294884
        
        superview?.insertSubview(blurry, belowSubview: self)
        ba = UIViewPropertyAnimator(duration:1, curve:.linear) {[weak self] in
            // note, those duration/curve values are simply unusued
            self?.blurry.effect = UIBlurEffect(style: .extraLight)
        }
        ba?.fractionComplete = live.largeplaybutton_blurfactor
    }
    
    override func willMove(toSuperview newSuperview: UIView?) {
        
        // Teardown for the blurry ball - critical
        
        if newSuperview == nil { print("safe teardown")
            ba?.stopAnimation(true)
            ba?.finishAnimation(at: .current)
        }
    }

    override func layoutSubviews() { super.layoutSubviews()
        blurry.frame = bounds, your drawing frame or whatever
    }

{旁白:作为一般的 iOS 工程问题,didMoveToWindow可能比didMoveToSuperview. 其次,您可以使用其他方式进行拆解,但拆解是那里显示的两行代码。}

BlurryBall只是一个UIVisualEffectView。注意视觉效果视图的 inits。如果您碰巧需要圆角或其他任何东西,请在本课程中进行。

class BlurryBall: UIVisualEffectView {
    
    override init(effect: UIVisualEffect?) { super.init(effect: effect)
        commonInit() }
    
    required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder)
        commonInit() }
    
    private func commonInit() {
        clipsToBounds = true
        backgroundColor = .clear
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        layer.cornerRadius = bounds.width / 2
    }
}
于 2019-09-10T16:56:28.957 回答
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()
    }
于 2016-08-04T12:06:54.050 回答
0

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

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

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

步骤 1 图片

  1. 在情节提要中拖动“带模糊的视觉效果视图”并进行设置...

第 2 步图像

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

单击任何按钮之前的应用程序布局!

单击按钮后的应用程序视图使整个应用程序背景模糊!

于 2019-03-14T10:59:36.443 回答
-1

如果为 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
于 2018-07-09T04:19:00.787 回答
-2

斯威夫特 4:

添加叠加层或弹出视图您还可以使用容器视图,通过它可以获得免费的视图控制器(您从通常的对象调色板/库中获取容器视图)

脚步:

有一个视图(图中的 ViewForContainer)包含这个 Container View,当 Container View 的内容显示时将其变暗。连接第一个 View Controller 内的插座

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

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

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

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

于 2018-04-09T09:20:10.613 回答
-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];
于 2016-06-27T10:33:25.310 回答