Tworzenie rozmytego widoku nakładki
W aplikacji Muzyka nowego iOS możemy zobaczyć okładkę albumu za widokiem, który ją zaciera.
Jak można coś takiego osiągnąć? Czytałem dokumentację, ale nic tam nie znalazłem.
20 answers
Możesz użyć UIVisualEffectView
, aby osiągnąć ten efekt. Jest to natywne API, które zostało dopracowane pod kątem wydajności i żywotności baterii, a także jest łatwe do wdrożenia.
Swift:
//only apply the blur if the user hasn't disabled transparency effects
if !UIAccessibilityIsReduceTransparencyEnabled() {
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];
}
Jeśli prezentujesz ten kontroler widoku modalnie, aby zamazać zawartość bazową, musisz ustawić styl prezentacji modalnej Na Over Current Context i ustawić kolor tła na clear, aby upewnić się, że kontroler widoku bazowego pozostanie widoczne, gdy jest to przedstawione overtop.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-02 18:08:35
Core Image
Ponieważ obraz na zrzucie ekranu jest statyczny, możesz użyć CIGaussianBlur
z Core Image (wymaga iOS 6). Oto przykład: https://github.com/evanwdavis/Fun-with-Masks/blob/master/Fun%20with%20Masks/EWDBlurExampleVC.m{[8]
Pamiętaj, że jest to wolniejsze niż inne opcje na tej stronie.
#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;
}
Stack blur (Box + Gaussian)
- StackBlur to połączenie rozmycia boxa i Gaussa. 7x szybszy niż bez akceleracji gaussian, ale nie tak brzydki jak box blur. Zobacz demo w tutaj (wersja wtyczki Java) lub tutaj (wersja JavaScript). Algorytm ten jest używany w KDE i Camera+ i innych. Nie używa frameworka Accelerate, ale jest szybki.
Accelerate Framework
W sesji "Implementing Engaging UI on iOS" z WWDC 2013 Apple wyjaśnia, jak utworzyć niewyraźne tło (o 14:30) i wspomina metodę
applyLightEffect
realizowane w przykładowy kod za pomocą programu Accelerate.ramy.GPUImage używa shaderów OpenGL do tworzenia dynamicznych rozmycia. Posiada kilka rodzajów rozmycia: GPUImageBoxBlurFilter, GPUImageFastBlurFilter, GaussianSelectiveBlur, GPUImageGaussianBlurFilter. Jest nawet GPUImageiOSBlurFilter, który " powinien w pełni replikować efekt rozmycia zapewniany przez panel sterowania systemu iOS 7 "(tweet, Artykuł ). Artykuł jest szczegółowy i pouczające.
-(UIImage *)blurryGPUImage:(UIImage *)image withBlurLevel:(NSInteger)blur { GPUImageFastBlurFilter *blurFilter = [GPUImageFastBlurFilter new]; blurFilter.blurSize = blur; UIImage *result = [blurFilter imageByFilteringImage:image]; return result; }
Od indieambitions.com: wykonaj rozmycie za pomocą vImage . Algorytm jest również używany w iOS-RealTimeBlur .
Od Nick Lockwood: https://github.com/nicklockwood/FXBlurView przykład pokazuje rozmycie w widoku przewijania. Rozmywa się za pomocą dispatch_async, a następnie synchronizuje się, aby wywołać aktualizacje za pomocą UITrackingRunLoopMode, więc rozmycie nie jest opóźnione, gdy UIKit nadaje większy priorytet przewijaniu UIScrollView. Jest to wyjaśnione w książce Nicka iOS Core Animation, która btw jest świetna.
IOS-blur pobiera warstwę rozmycia Uitoolbara i umieszcza ją w innym miejscu. Apple odrzuci Twoją aplikację, jeśli użyjesz tej metody. Zobacz https://github.com/mochidev/MDBlurView/issues/4
-
[[6]}z bloga Evadne: LiveFrost: szybkie, synchroniczne Konwolwowanie migawek UIView . Świetny kod i świetna lektura. Kilka pomysłów z tego postu:
- użyj kolejki szeregowej, aby Dławić aktualizacje z CADisplayLink.
- używaj ponownie kontekstów bitmapowych, chyba że zmienią się granice.
- Rysuj mniejsze obrazy za pomocą -[CALayer renderInContext:] z współczynnikiem skali 0,5 F.
Inne rzeczy
Andy Matuschak powiedział na Twitterze: "wiesz, wiele miejsc, w których wygląda na to, że robimy to w czasie rzeczywistym, jest statycznych z sprytnymi sztuczkami."At doubleencore.com mówią: "mamy okazało się, że promień rozmycia 10 pt plus wzrost nasycenia 10 pt najlepiej naśladuje efekt rozmycia systemu iOS 7 w większości sytuacji".
[[6]}a peek at the private headers of Apple ' s sbfproceduralwallpaperview .Wreszcie, nie jest to prawdziwe rozmycie, ale pamiętaj, że możesz ustawić rasteryzationscale, aby uzyskać obraz pikselowy: http://www.dimzzy.com/blog/2010/11/blur-effect-for-uiview/
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-18 23:14:29
Postanowiłem opublikować pisemną wersję Objective-C z zaakceptowanej odpowiedzi, aby zapewnić więcej opcji w tym pytaniu..
- (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;
}
Ograniczenia mogą zostać usunięte, jeśli chcesz okryć, jeśli obsługujesz tylko tryb portretowy lub po prostu dodam flagę do tej funkcji, aby z nich korzystać lub nie..
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-23 04:40:21
Wydaje mi się, że nie wolno mi zamieszczać kodu, ale powyższy post zawierający przykładowy kod WWDC jest poprawny. Oto link: https://developer.apple.com/downloads/index.action?name=WWDC%202013
Plik, którego szukasz, to kategoria w UIImage, a metoda to applyLightEffect.
Jak wspomniałem powyżej w komentarzu, Apple Blur ma nasycenie i inne rzeczy się dzieją poza rozmyciem. Zwykłe rozmycie nie wystarczy... jeśli chcesz naśladować ich styl.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-17 18:53:19
Myślę, że najprostszym rozwiązaniem jest obejście Uitoolbara, który zaciera wszystko za nim w iOS 7. Jest to dość podstępne, ale bardzo proste do wdrożenia i szybkie!
Możesz to zrobić z dowolnym widokiem, po prostu zrób z niego podklasę UIToolbar
zamiast UIView
. Można to zrobić na przykład za pomocą właściwości UIViewController
'S view
...
1) Utwórz nową klasę, która jest "podklasą" {[6] } i zaznacz pole "z XIB dla interfejsu użytkownika".
2) Wybierz widok i przejdź do inspektora tożsamości w prawym panelu (alt-command-3). Zmień "klasę" na UIToolbar
. Teraz przejdź do inspektora atrybutów (alt-command-4) i zmień kolor " tła "na"Wyczyść Kolor".
3) Dodaj subview do widoku głównego i podłącz go do IBOutlet w interfejsie. Nazwij to backgroundColorView
. Będzie to wyglądało mniej więcej tak, jako prywatna kategoria w pliku implementation (.m
).
@interface BlurExampleViewController ()
@property (weak, nonatomic) IBOutlet UIView *backgroundColorView;
@end
4) przejdź do implementacji kontrolera widoku (.m
) i zmień metoda -viewDidLoad
, aby wyglądać następująco:
- (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];
}
To da ci ciemnoszary widok, który zaciera wszystko za nim. Bez śmiesznych interesów, bez powolnego rozmycia obrazu rdzenia, używając wszystkiego, co jest na wyciągnięcie ręki przez OS / SDK.
Możesz dodać widok kontrolera widoku do innego widoku, w następujący sposób:
[self addChildViewController:self.blurViewController];
[self.view addSubview:self.blurViewController.view];
[self.blurViewController didMoveToParentViewController:self];
// animate the self.blurViewController into view
Daj mi znać, jeśli coś jest niejasne, chętnie pomogę!
Edit
UIToolbar został zmieniony w 7.0.3 aby dać możliwe-efekt niepożądany przy użyciu kolorowego rozmycia.
Byliśmy w stanie ustawić kolor za pomocą barTintColor
, ale jeśli robiłeś to wcześniej, będziesz musiał ustawić Składnik alfa na mniej niż 1. W przeciwnym razie Twój UIToolbar będzie całkowicie nieprzezroczysty - bez rozmycia.
Można to osiągnąć w następujący sposób: (mając na uwadze self
jest podklasą UIToolbar
)
UIColor *color = [UIColor blueColor]; // for example
self.barTintColor = [color colorWithAlphaComponent:0.5];
To da niebieski odcień rozmytego widoku.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-03 13:39:15
Oto szybka implementacja w Swift przy użyciu CIGaussianBlur:
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-26 01:09:21
Akceptowana odpowiedź jest poprawna, ale brakuje tu ważnego kroku, w przypadku, gdy ten widok - dla którego chcesz zamazać tło-jest przedstawiony za pomocą
[self presentViewController:vc animated:YES completion:nil]
Domyślnie spowoduje to negację rozmycia, gdy UIKit usunie widok prezentera, który faktycznie się rozmywa. Aby uniknąć tego usunięcia, dodaj tę linię przed poprzednią
vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
Lub używać innych stylów Over
.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-02 12:43:34
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)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:47
Znalazłem to przez przypadek, daje mi naprawdę świetne (prawie duplikat z Apple) wyniki i wykorzystuje framework akceleracji. -- http://pastebin.com/6cs6hsyQ * Not written by me
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-11 14:30:56
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
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-27 10:58:22
Apple udostępniło rozszerzenie dla klasy UIImage o nazwie UIImage + ImageEffects.h. w tej klasie masz pożądane metody rozmycia widoku
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-21 08:51:05
Korzystanie Z UIImageEffects
Dla osób, które chcą mieć większą kontrolę, możesz skorzystać z przykładowego kodu Apple ' a UIImageEffects
.
Możesz skopiować kod do UIImageEffects
z biblioteki programistów Apple: rozmycie i przyciemnianie obrazu
A oto jak go zastosować:
#import "UIImageEffects.h"
...
self.originalImageView.image = [UIImageEffects imageByApplyingLightEffectToImage:[UIImage imageNamed:@"yourImage.png"]];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-08 01:01:00
Ta odpowiedź jest oparta na doskonałej wcześniejszej odpowiedzi Mitji Semolic . Przekonwertowałem go do swift 3, dodałem wyjaśnienie do tego, co dzieje się w coments, zrobiłem z niego rozszerzenie UIViewController, aby każdy VC mógł go wywołać do woli, dodałem widok nieblustrowany, aby pokazać selektywną aplikację, i dodałem blok zakończenia, aby kontroler widoku wywołującego mógł robić, co chce po zakończeniu rozmycia.
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
}
}
Potwierdziłem, że działa zarówno z iOS 10.3.1, jak i iOS 11
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-18 15:31:06
Ważne uzupełnienie odpowiedzi @ Joey
Dotyczy to sytuacji, w której chcesz przedstawić rozmyte tło UIViewController
za pomocą 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];
Smacznego!Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-06 07:30:15
Z Xcode możesz to zrobić łatwo. Wykonaj kroki z xcode. Efekt wizualny Drage w widoku uiview lub imageview.
Happy Coding:)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-09 10:27:41
Oto Kod Swift 2.0 Dla rozwiązania, które zostało podane w accepted answer :
//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()
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-04 12:06:54
Jeśli dodamy ciemny widok rozmycia dla tableView, to pięknie to zrobi:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-09 04:19:00
Niestandardowa skala rozmycia
Możesz spróbować UIVisualEffectView
z niestandardowym ustawieniem as -
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)
}
}
Wyjście: - dla blurEffect.setValue(1...
& blurEffect.setValue(2..
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-18 15:53:05
Swift 4:
Aby dodać nakładkę lub widok wyskakujący, Możesz również użyć widoku kontenera, za pomocą którego otrzymasz bezpłatny kontroler widoku (widok kontenera otrzymasz z zwykłej palety obiektów/biblioteki)
Kroki:
Mieć Widok (ViewForContainer w pic), który przechowuje ten widok kontenera, aby go przyciemnić, gdy wyświetlana jest zawartość widoku kontenera. Podłącz gniazdo wewnątrz pierwszego kontrolera widoku
Ukryj ten Widok, gdy wczytuje się 1. VC
Odkryj, kiedy Kliknij przycisk enter image description here
Aby przyciemnić ten Widok, gdy wyświetlana jest zawartość widoku kontenera, Ustaw tło widoków na czarne, a krycie na 30%
Dodałem odpowiedź do tworzenia widoku popview w innym pytaniu Stackoverflow https://stackoverflow.com/a/49729431/5438240
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-09 11:08:08
Prosta odpowiedź to Dodaj subview i zmień to jest Alfa.
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];
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-27 10:33:25