programing

흐릿한 오버레이 보기 만들기

bestprogram 2023. 5. 22. 21:52

흐릿한 오버레이 보기 만들기

새로운 iOS의 뮤직 앱에서, 우리는 그것을 흐리게 하는 뷰 뒤에 있는 앨범 커버를 볼 수 있습니다.

어떻게 그런 일이 이루어질 수 있습니까?설명서를 읽었지만 거기서 아무것도 찾지 못했습니다.

사용할 수 있습니다.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];
}

기본 내용을 흐리게 하기 위해 이 뷰 컨트롤러를 모달로 표시하는 경우 모달 표시 스타일을 현재 컨텍스트 초과로 설정하고 배경색을 지우기로 설정하여 위에 표시된 후에도 기본 뷰 컨트롤러가 계속 표시되도록 해야 합니다.

코어 이미지

에 스린샷이정는때기적다문수있사다습니용할음을크에의미이를 할 수 있습니다.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;
}

스택 흐림(상자 + 가우스)

  • StackBlur 이것은 Box와 Gaussian blur의 혼합을 구현합니다. 가속되지 않은 Gaussian보다 7배 빠르지만 Boxblur만큼 못생기지는 않습니다.여기(Java 플러그인 버전) 또는 여기(JavaScript 버전)의 데모를 참조하십시오.이 알고리즘은 KDE 및 Camera+ 등에 사용됩니다.Accelerate Framework를 사용하지 않지만 속도가 빠릅니다.

프레임워크 가속화

  • WWDC 2013의 "Implementing UI on iOS" 세션에서 Apple은 흐린 배경을 만드는 방법(14:30)을 설명하고 Accelerate.framework를 사용하여 샘플 코드에 구현된 방법을 언급합니다.

  • GPUIimage는 OpenGL 셰이더를 사용하여 동적 블러를 생성합니다.GPIimageBoxBlurFilter, GPIimageFastBlurFilter, GPIimageGaussianBlurFilter, GPIimageGaussianBlurFilter 등 여러 가지 블러 유형이 있습니다.GPUIimage iOS도 있습니다.BlurFilter "iOS 7의 제어판이 제공하는 블러 효과를 완전히 복제해야 한다"(트윗, 기사).그 기사는 상세하고 유익합니다.

-(UIImage *) 흐림GPUImage:(UIImage *) 흐림 수준:(NSInteger) 흐림 {GPUIimageFastBlurFilter *blurFilter = [GPUIimageFastBlurFilter new];
blurFilter.blurSize = 블러;UIImage * 결과 = [BlurFilter imageByFilteringImage:image];
결과 반환;}
  • indieambitions.com 에서: vImage를 사용하여 블러를 수행합니다.이 알고리즘은 iOS-RealTimeBlur에서도 사용됩니다.

  • Nick Lockwood에서: https://github.com/nicklockwood/FXBlurView 예제는 스크롤 보기의 흐림을 보여줍니다.dispatch_async로 흐린 다음 업데이트를 UITtrackingRunLoopMode로 동기화하여 UIKit이 UIScrollView의 스크롤에 더 많은 우선 순위를 부여할 때 흐림이 지연되지 않도록 합니다.이것은 닉의 책 iOS 코어 애니메이션에 설명되어 있는데, 그것은 훌륭합니다.

  • iOS-blur 이것은 UI 툴바의 흐릿한 레이어를 가져와서 다른 곳에 놓습니다.이 방법을 사용하면 Apple에서 앱을 거부합니다.https://github.com/mochidev/MDBlurView/issues/4 을 참조하십시오.

  • Evadne 블로그: LiveFrost: 빠른 동기식 UIView 스냅샷 Convolving.훌륭한 코드와 훌륭한 읽기.이 게시물의 몇 가지 아이디어:

    • 직렬 큐를 사용하여 CADisplayLink의 업데이트를 조절합니다.
    • 경계가 변경되지 않는 한 비트맵 컨텍스트를 재사용합니다.
    • 0.5f 스케일 팩터와 함께 -[CALayer renderInContext:]를 사용하여 더 작은 이미지를 그립니다.

다른 것들

Andy Matuschak은 트위터에서 다음과 같이 말했습니다."우리가 실시간으로 그것을 하는 것처럼 보이는 많은 장소들은 영리한 속임수로 정적입니다."

doubleencore.com 에서 그들은 "10 pt 블러 반경에 10 pt의 채도 증가가 대부분의 상황에서 iOS 7의 블러 효과를 가장 잘 모방한다는 것을 발견했습니다."라고 말합니다.

Apple의 SBP 절차 월페이퍼 보기의 개인 헤더를 살펴봅니다.

마지막으로, 이것은 실제 흐림은 아니지만 픽셀화된 이미지를 얻기 위해 래스터화스케일을 설정할 수 있습니다. http://www.dimzzy.com/blog/2010/11/blur-effect-for-uiview/

다음은 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

저는 단지 이 질문에 더 많은 옵션을 제공하기 위해 수락된 답변에서 작성된 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;
}

세로 모드만 지원하거나 이 기능에 플래그를 추가하여 사용하거나 사용하지 않을 경우에 대비하여 제약 조건을 제거할 수 있습니다.

여기에 이미지 설명 입력

Xcode에서 쉽게 할 수 있습니다.xcode의 단계를 따릅니다.사용자의 보기 또는 이미지 보기에서 시각 효과 보기를 끕니다.

해피 코딩 :)

코드를 게시하는 것은 허용되지 않는 것 같습니다만, 위에 WWDC 샘플 코드를 언급한 게시물은 맞습니다.링크는 다음과 같습니다. https://developer.apple.com/downloads/index.action?name=WWDC%202013

찾으시는 파일은 UI 이미지의 카테고리이며, 방법은 applyLightEffect입니다.

위에서 언급한 바와 같이 Apple Blur는 Blur 이외에도 포화 상태 및 기타 작업이 진행되고 있습니다.단순한 흐릿함으로는...그들의 스타일을 본받으려는 경우.

다음은 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;
}

이것에 대한 가장 쉬운 해결책은 iOS 7에서 뒤에 있는 모든 것을 흐리게 하는 UIT 도구 모음을 무시하는 것이라고 생각합니다.이는 상당히 교활하지만 구현이 매우 간단하고 빠릅니다!

뷰든 할 수, 그냥 에서수수있며으할, 하클만수있다들습니의 수 .UIToolbarUIView당신은 심지어 그것을 할 수 있습니다.UIViewControllerview속성(예:)

클래스인 새 .UIViewController"사용자 인터페이스용 XIB 포함" 확인란을 선택합니다.

View (보기) 선택오패른널에서를쪽고 (alt-command-3)보 Identity inspector(ID 검사기)로 이동합니다.클래스를 다음으로 변경합니다.UIToolbar이제 속성 검사기(alt-command-4)로 이동하여 "백그라운드" 색상을 "클리어 색상"으로 변경합니다.

기본 뷰에 하위 뷰를 추가하고 인터페이스의 IO Butlet에 연결합니다.을 콜잇라고 .backgroundColorView구현의 것입니다..m) 파일.

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

으로 이동합니다(View 컨트이니다합동로구으현.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

궁금한 점이 있으면 알려주세요. 기꺼이 도와드리겠습니다!


편집

7.0.3에서는 유색 블러를 사용할 때 바람직하지 않은 효과를 제공하도록 UI 도구 모음이 변경되었습니다.

우리는 예전에 다음을 사용하여 색상을 설정할 수 있었습니다.barTintColor그러나 이전에 이 작업을 수행한 경우 알파 성분을 1보다 작게 설정해야 합니다.그렇지 않으면 UI 도구 모음의 색이 완전히 불투명해집니다.

이는 다음과 같이 달성할 수 있습니다. (참고로)self의 하위 클래스입니다.UIToolbar)

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

이렇게 하면 흐릿한 시야에 푸른 빛이 납니다.

사용자 지정 블러 스케일

은 시도해 볼 수 있습니다. 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.. 여기에 이미지 설명 입력 여기에 이미지 설명 입력

만약 이것이 누군가에게 도움이 된다면, 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의 배경색을 UIColor.clear로 설정한 다음 블러백(스타일: UIBlur Effect)을 호출해야 합니다.컨테이너 UIView에 스타일, 폴백 색상: UIColor).다음은 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)

허용된 답변은 맞지만, 배경이 흐릿해지길 원하는 이 보기가 다음을 사용하여 표시되는 경우 중요한 단계가 누락됩니다.

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

기본적으로 UIKit이 발표자의 보기를 제거할 때 흐림이 사라집니다. 이 보기는 실제로 흐립니다.이러한 제거를 방지하려면 이전 행 앞에 이 행을 추가합니다.

vc.modalPresentationStyle = UIModalPresentationOverFullScreen;

다른 것을 하세요.Over문체

목표-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

UI 이미지 효과 사용

통제권을 , 신은당해 애플을을 이용할 수 있습니다.UIImageEffects견본 부호

다음에 대한 코드를 복사할 수 있습니다.UIImageEffects Apple의 Developer Library에서: 이미지 흐림색조 지정

적용 방법은 다음과 같습니다.

#import "UIImageEffects.h"
...

self.originalImageView.image = [UIImageEffects imageByApplyingLightEffectToImage:[UIImage imageNamed:@"yourImage.png"]];
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
    }
}

우연히 이것을 발견했고, 저에게 정말 좋은 결과를 주었고(애플의 것과 거의 중복됨) 가속 프레임워크를 사용했습니다. -- http://pastebin.com/6cs6hsyQ *내가 쓴 것이 아닙니다.

이 답변은 Mitja Semolic의 이전의 훌륭한 답변에 기초하고 있습니다.swift 3으로 변환하고, 설명을 추가하고, 코멘트에서 일어나는 일들을 추가하고, 어떤 VC도 마음대로 호출할 수 있도록 UIViewController의 확장을 만들고, 선택적 적용을 보여주기 위해 흐리지 않는 뷰를 추가하고, 콜링 뷰 컨트롤러가 블러가 완료될 때 원하는 모든 것을 할 수 있도록 완료 블록을 추가했습니다.

    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에서 모두 작동하는 것을 확인했습니다.

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

맛있게 드세요!

흐릿한 이미지를 돌려주는 케브의 대답의 스위프트 3 버전 -

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

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시각적 효과 보기의 시작 부분을 확인합니다.만약 당신이 둥근 모서리나 다른 것이 필요하다면, 이 수업에서 하세요.

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

Apple은 UIImage+ImageEffects.h라는 UIImage 클래스에 대한 확장 기능을 제공했습니다.이 수업에서는 원하는 방식으로 시야를 흐리게 할 수 있습니다.

다음은 수락된 답변으로 제공된 솔루션에 대한 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()
    }

"흐림이 있는 시각 효과 보기" 및 "흐림과 진동이 있는 시각 효과 보기"를 사용하여 배경을 직접 흐리게 만들 수 있습니다.

iOS 애플리케이션에서 블러 배경을 만들기 위해 해야 할 일은 다음과 같습니다.

  1. 개체 라이브러리에서 "흐림이 있는 시각적 효과 보기"로 이동하여 검색

1단계 이미지

  1. 스토리보드에서 "흐림이 있는 시각 효과 보기"를 끌어 설정합니다.

2단계 이미지

  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

스위프트 4:

오버레이 또는 팝업 뷰를 추가하려면 무료 뷰 컨트롤러(일반 객체 팔레트/라이브러리에서 컨테이너 뷰를 얻을 수 있음)를 사용할 수도 있습니다.

단계:

Container View의 내용이 표시될 때 이 Container View를 어둡게 하려면 이 Container View를 포함하는 View(그림의 ViewForContainer)가 있어야 합니다.첫 번째 View 컨트롤러 내부의 콘센트 연결

첫 번째 VC가 로드될 때 이 보기 숨기기

단추를 클릭할 때 숨기기 취소 여기에 이미지 설명 입력

Container View 컨텐츠가 표시될 때 이 보기를 어둡게 하려면 보기 배경을 검은색으로 설정하고 불투명도를 30%로 설정합니다.

다른 스택 오버플로 질문 https://stackoverflow.com/a/49729431/5438240 에서 팝뷰 뷰 생성에 대한 답변을 추가했습니다.

간단한 대답은 하위 보기를 추가하고 알파로 변경하는 것입니다.

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

언급URL : https://stackoverflow.com/questions/17041669/creating-a-blurring-overlay-view