美文网首页
如何设置圆角减轻页面卡顿

如何设置圆角减轻页面卡顿

作者: MangoJ | 来源:发表于2017-01-11 15:50 被阅读30次

    之前的项目中,多用到设置图片或者view的圆角,当时用到的方法多为:
    圆角
    ( UIView.layer.cornerRadius UIView.layer.maskToBounds 一起使用时)
    这样的设置会产生"离屏渲染".

    离屏渲染

    离屏渲染是指图层在被显示之前是在当前屏幕缓冲区以外开辟的一个缓冲区进行渲染操作。

    离屏渲染需要多次切换上下文环境:先是从当前屏幕(On-Screen)切换到离屏(Off-Screen);等到离屏渲染结束以后,将离屏缓冲区的渲染结果显示到屏幕上又需要将上下文环境从离屏切换到当前屏幕,而上下文环境的切换是一项高开销的动作。

    除设置圆角外还有其他设置也会产生离屏渲染如:

    阴影

    (UIView.layer.shadowOffset/shadowRadius/…)

    图层蒙板
    开启光栅化

    (shouldRasterize = true)

    下面所介绍的是如何优化圆角设置
    1.图片圆角设置:
    + (UIImage *)cutCircleImageWithImage:(UIImage *)image size:(CGSize)size radious:(CGFloat)radious { 
      UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale); 
      CGRect rect = CGRectMake(0, 0, size.width, size.height); 
      CGContextAddPath(UIGraphicsGetCurrentContext(), [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radious].CGPath);
      CGContextClip(UIGraphicsGetCurrentContext());
      [image drawInRect:rect];
      UIImage *newImage =   UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      return newImage; 
    }
    
    2.View圆角设置
    + (void)cutCicleViewWithView:(UIView *)view radious:(CGFloat)radius {   
      CGSize size = view.frame.size;   
      CGRect rect = CGRectMake(0, 0, size.width, size.height);     
      UIColor *bkColor = view.backgroundColor;  
      UIImage *image = [[UIImage alloc] init];
      UIGraphicsBeginImageContextWithOptions(size, NO, UIScreen.mainScreen.scale);    
      CGContextRef context =   UIGraphicsGetCurrentContext(); 
      CGContextSetFillColorWithColor(context, bkColor.CGColor);    
      CGContextAddPath(context, [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);   
      CGContextDrawPath(context, kCGPathFill);    
      [image drawInRect:rect];    
      UIImage *output =     UIGraphicsGetImageFromCurrentImageContext();         
      UIGraphicsEndImageContext();     
      UIImageView *imageView = [[UIImageView alloc] initWithFrame:rect];    
      imageView.image = output;    
      [view insertSubview:imageView atIndex:0];
      view.backgroundColor = [UIColor clearColor]; 
    }
    
    温馨提示:以上两个方法可在开发中可添加在工具类中,没准下个需求就能用到!

    相关文章

      网友评论

          本文标题:如何设置圆角减轻页面卡顿

          本文链接:https://www.haomeiwen.com/subject/ejrrbttx.html