Bezdepbonusu7Программирование: статьи и ответы

Вопрос

Размытие во весь экран

Автор вопроса: CommunityОтветов: 2

Я хочу показать размытый фон в своем приложении, когда нажимаю кнопку "Показать вид". Я могу сделать размытие фона, но это не на весь экран. он отображается под панелью вкладок и панелью навигации.

Это мой экран входа в систему и то, что я хочу (SCLAlertView)

введите здесь описание изображения

Но мы не можем добавить пользовательский вид в эту библиотеку. Итак, я хочу создать собственный вид и добавить индикатор выполнения в этот вид.

введите здесь описание изображения

 @property (nonatomic, strong) UIView *ContentView;
 @property (nonatomic, strong) UIImageView *BgView;


_BgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,[[UIScreen mainScreen] applicationFrame].size.width,[[UIScreen mainScreen] applicationFrame].size.height)];

[_BgView setBackgroundColor:[UIColor blackColor]];
_BgView.userInteractionEnabled = YES;
_BgView.alpha = 1.0;
_BgView.tag=7001;

_ContentView = [[UIView alloc] init];
_ContentView.tag=7002;

[self.view addSubview:_ContentView];

_ContentView.backgroundColor = [UIColor whiteColor];
_ContentView.layer.cornerRadius = 2.0f;
_ContentView.layer.masksToBounds = YES;
_ContentView.layer.borderWidth = 0.5f;

когда я нажимаю кнопку, он вызывает этот метод

-(void)BlurBg{

    float width = self.view.frame.size.width-20;
    float height= 120.0;
    float x     = (self.view.frame.size.width-width)/2;
    float y     = (self.view.frame.size.height-height)/2;

    _ContentView.frame = CGRectMake(x, y, width, height);
    UIButton *OkBtn = [[UIButton alloc] initWithFrame:CGRectMake((_ContentView.frame.size.width-(_IcerikView.frame.size.width/3))/2, ((_ContentView.frame.size.height-20)/3)*2, _ContentView.frame.size.width/3, 40)];
    OkBtn.backgroundColor=[UIColor greenColor];
    [OkBtn setTitle:@"OK" forState:UIControlStateNormal];
    OkBtn.layer.cornerRadius = 1;
    OkBtn.clipsToBounds = YES;
    [OkBtn addTarget:self action:@selector(Sonuc) forControlEvents:UIControlEventTouchUpInside];

    [_ContentView addSubview:OkBtn];

    [self.view addSubview:_BgView];
    [self.view addSubview:_ContentView];
}

-(void) Sonuc{
    [[self.view viewWithTag:7001] removeFromSuperview];
    [[self.view viewWithTag:7002] removeFromSuperview];
}
  • Проверьте эти ссылки: 1. stackoverflow.com/questions/17041669 / 2. stackoverflow.com/questions/17055740/ 3. stackoverflow.com/questions/17036655/ios-7-style-blur-view VRAwesome 24.02.2015
  • я видел этот вопрос, но код в принятом ответе написан на Swift и для IOS8. и я новичок в Objective-C. так и не понял решения. 24.02.2015
  • Если вы собираетесь развернуть на iOS8, вы можете использовать UIVisualEffectView, его действительно легко реализовать, и он заботится об обновлении пользовательского интерфейса. Если вы развернете более низкую цель и используете статическое изображение размытия, вы можете использовать категорию UIImage + ImageEffects, созданную Apple, вам просто нужно создать снимок экрана вашего представления. Andrea 24.02.2015
  • Я могу создать снимок экрана, но если я хочу развернуть его на весь экран, он отображается на панели вкладок и панели навигации (вы можете видеть второе изображение). 24.02.2015
  • Панели вкладок @ismailMoon не являются частью представления, по которому они направляют вас к представлениям, вместо этого добавьте contentView в свой суперпредставление. soulshined 24.02.2015
  • Это потому, что вам нужно проверить границы вашего контроллера представления. Andrea 24.02.2015

iosblurbackground

Ответы

Ответ 1 · рейтинг -2 · delavega66

Я думаю, вы можете использовать FXBlurView. Это полезная библиотека. После импорта этой библиотеки вы можете добавить новый вид (или вы можете создать его динамически). Тип класса Viewcontroller должен быть FXBlurView. Вы можете найти небольшой пример ниже.

 @property (nonatomic, weak) IBOutlet FXBlurView *blurView;
 ...
 self.blurView.blurRadius = 40; // you can set 0 to 100

Изменить:

Если вы не хотите использовать библиотеку, вам нужно создать собственное размытие фона. Я скопировал ваш код и отредактировал его. вы можете найти его ниже.

BlurBG.h:

#import <UIKit/UIKit.h>

@interface BlurBG : UIViewController
- (void)showAlert:(UIViewController *)vc;
- (void) ProgressUpdate ;
@end

BlurBG.m:

#import "BlurBG.h"
#import "UIImage+ImageEffects.h"
#import <AVFoundation/AVFoundation.h>

#define UIColorFromRGB(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

#define KEYBOARD_HEIGHT 80
#define PREDICTION_BAR_HEIGHT 40

@interface BlurBG ()
@property (nonatomic, strong) UIImageView *backgroundView;
@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, strong) UIButton *OkBtn;
@property UIProgressView *prog;
@property (nonatomic) CGFloat backgroundOpacity;
@property UILabel *labelTitle;
@property UITextView *viewText;
@end

@implementation BlurBG

CGFloat kWindowWidth;
CGFloat kWindowHeight;
CGFloat kTextHeight;
CGFloat kSubTitleHeight;

#pragma mark - Initialization

- (id)initWithCoder:(NSCoder *)aDecoder
{
    @throw [NSException exceptionWithName:NSInternalInconsistencyException
                               reason:@"NSCoding not supported"
                             userInfo:nil];
}

-(instancetype) init{
    self = [super init];
    if (self)
    {
        kWindowWidth = [UIScreen mainScreen].bounds.size.width-50;
        kWindowHeight = ([UIScreen mainScreen].bounds.size.height/5);

        _OkBtn = [[UIButton alloc] initWithFrame:CGRectMake(kWindowWidth-25,5,20,20)];
        _OkBtn.backgroundColor=[UIColor grayColor];
        [_OkBtn setTitle:@"X" forState:UIControlStateNormal];
        _OkBtn.layer.cornerRadius = 1;
        _OkBtn.clipsToBounds = YES;
        [_OkBtn addTarget:self action:@selector(fadeOut) forControlEvents:UIControlEventTouchUpInside];

        _prog = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];

        _labelTitle = [[UILabel alloc] init];
        _viewText = [[UITextView alloc] init];
        _contentView = [[UIView alloc] init];

        [self.view addSubview:_contentView];

        [_contentView addSubview:_labelTitle];
        [_contentView addSubview:_viewText];
        [_contentView addSubview:_prog];
        [_contentView addSubview:_OkBtn];

    // Content View
        _contentView.layer.cornerRadius = 5.0f;
        _contentView.layer.masksToBounds = YES;
        _contentView.layer.borderWidth = 0.5f;

        _labelTitle.numberOfLines = 1;
        _labelTitle.textAlignment = NSTextAlignmentCenter;
        _labelTitle.font = [UIFont fontWithName:@"HelveticaNeue" size:20.0f];

    // View text
        _viewText.editable = NO;
        _viewText.allowsEditingTextAttributes = YES;
        _viewText.textAlignment = NSTextAlignmentCenter;
        _viewText.font = [UIFont fontWithName:@"HelveticaNeue" size:14.0f];

        _backgroundView = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        _backgroundView.userInteractionEnabled = YES;

        _contentView.backgroundColor = [UIColor whiteColor];
        _labelTitle.textColor = UIColorFromRGB(0x4D4D4D);
        _viewText.textColor = UIColorFromRGB(0x4D4D4D);
        _contentView.layer.borderColor = UIColorFromRGB(0xCCCCCC).CGColor;

    }
    return self;
}

-(void) ShowTitle:(UIViewController *)vc{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];

    self.view.alpha = 0;

    [self makeBlurBackground];
    _backgroundView.frame = vc.view.bounds;

    _labelTitle.text = @"Title";
    _viewText.text = @"Description..";

    [window addSubview:_backgroundView];
    [window addSubview:self.view];
    [vc addChildViewController:self];

    [self fadeIn];
}

- (void)showAlert:(UIViewController *)vc {
    [self ShowTitle:vc];
}

-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    CGSize sz = [UIScreen mainScreen].bounds.size;

    if (SYSTEM_VERSION_LESS_THAN(@"8.0"))
    {
        if UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])
        {
            CGSize ssz = sz;
            sz = CGSizeMake(ssz.height, ssz.width);
        }
    }

    CGRect newFrame = self.backgroundView.frame;
    newFrame.size = sz;
    self.backgroundView.frame = newFrame;

    CGRect r;
    if (self.view.superview != nil)
    {
        r = CGRectMake((sz.width-kWindowWidth)/2, (sz.height-kWindowHeight)/2, kWindowWidth, kWindowHeight/2);
    }
    else
    {
        r = CGRectMake((sz.width-kWindowWidth)/2, -kWindowHeight, kWindowWidth, kWindowHeight);
    }

    self.view.frame = r;

    _contentView.frame = CGRectMake(0,0, kWindowWidth, kWindowHeight);
    _labelTitle.frame = CGRectMake((kWindowWidth-(kWindowWidth-10))/2, 5, kWindowWidth-10,28);
    _viewText.frame = CGRectMake((kWindowWidth-(kWindowWidth-10))/2, 8+(_labelTitle.frame.size.height), kWindowWidth-10,28);
    _prog.frame = CGRectMake((kWindowWidth-(kWindowWidth-10))/2, 65, kWindowWidth-10,28);
}

- (void)fadeIn
{
    self.backgroundView.alpha = 0.0f;
    self.view.alpha = 0.0f;

    [UIView animateWithDuration:0.3f
                      delay:0.0f
                    options:UIViewAnimationOptionCurveEaseIn
                 animations:^{
                     self.backgroundView.alpha = _backgroundOpacity;
                     self.view.alpha = 1.0f;
                 }
                 completion:^(BOOL completed){


    [self performSelectorOnMainThread:@selector(ProgressUpdate) withObject:nil waitUntilDone:YES];
                     }];
    }

    - (void)fadeOut
    {
    [UIView animateWithDuration:0.3f animations:^{
        self.backgroundView.alpha = 0.0f;
        self.view.alpha = 0.0f;
    } completion:^(BOOL completed) {
        [self.backgroundView removeFromSuperview];
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
    }];
}

- (void)makeBlurBackground
{
    UIImage *image = [UIImage convertViewToImage];
    UIImage *blurSnapshotImage = [image applyBlurWithRadius:5.0f
                                                  tintColor:[UIColor colorWithWhite:0.2f
                                                                              alpha:0.7f]
                                      saturationDeltaFactor:1.8f
                                                  maskImage:nil];

    _backgroundView.image = blurSnapshotImage;
    _backgroundView.alpha = 0.0f;
    _backgroundOpacity = 1.0f;
}

-(void) ProgressUpdate {
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf) {
            for (int i=0; i<100; i++) {
                [NSThread sleepForTimeInterval:0.1];
                float currentProgress = _prog.progress;
                NSLog(@"%f",currentProgress);
                [strongSelf.prog setProgress:currentProgress+0.01 animated:YES];
            };
        }
    });
}

@end

Вызов BlurBG:

BlurBG *bg = [[BlurBG alloc]init];
[bg showAlert:self];
[bg ProgressUpdate];

Ответ 2 · рейтинг 1 · soulshined

Apple предоставила нам замечательный ресурс для воспроизведения эффекта размытия. Посмотрите UIBlurEffect

typedef enum {
UIBlurEffectStyleExtraLight,
UIBlurEffectStyleLight,
UIBlurEffectStyleDark
} UIBlurEffectStyle;

Перевод вопроса и ответов сообщества Stack Overflow, лицензия CC BY-SA. Оригинал на Stack Overflow.

Похожие материалы