iOS

关于corner 性能问题

2015-10-15  本文已影响2146人  ClarkWang_001

在ios 中绘制圆角常用方式:

   myView.layer.cornerRadius = 8;
   myView.layer.masksToBounds = YES;

即可实现圆角; 如果需要只设置上边角或者下边角1个或者几个圆角,也可通过下面的方式来处理:

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(120, 10, 80, 80)];
view.backgroundColor = [UIColor redColor];
[self.view addSubview:view];

 UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(10, 10)];
 CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
 maskLayer.frame = view.bounds;
 maskLayer.path = maskPath.CGPath;
 view.layer.mask = maskLayer;

其中,
byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight
指定了需要成为圆角的角。该参数是UIRectCorner类型的,可选的值有:

UIRectCornerTopLeft
UIRectCornerTopRight
UIRectCornerBottomLeft
UIRectCornerBottomRight
UIRectCornerAllCorners
从名字很容易看出来代表的意思,使用“|”来组合就好了。

在普通的视图中通过以上方式设置1个或者较少数量的视图圆角基本没有问题,但是在UIScrollview,或者UITableView中有大量视图使用带圆角的效果时容易碰到性能问题,出现卡顿;

现在优化方案如下: 根据是否要包含图片圆角分2种处理方式;

1) 关于图片圆角的处理方式,方法就是先把图片处理成圆角,处理后在渲染;

   UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
   UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(self.cornerRadius, self.cornerRadius)];
   [path addClip];
   [_image drawInRect:rect];
   UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  1. 普通视图,不包含图片,可通过如下方式处理: 把背景图设置成clearColor, layer 的背景color和要渲染的视图颜色一致,设置好角度,通过颜色差异来显示出圆角的效果; 关键是把masksToBounds设置NO,就是这个家伙消耗性能;
    self.view.backgroundColor = [UIColor clearColor];
// Set view.layer.backgroundColor not view.backgroundColor otherwise the background is not masked to the rounded border.
    self.view.layer.backgroundColor = [UIColor whiteColor].CGColor;
    self.view.layer.cornerRadius = 8;
// Huge change in performance by explicitly setting the below (even though default is supposedly NO)
    self.view.layer.masksToBounds = NO;     
// Performance improvement here depends on the size of your view
    self.view.layer.shouldRasterize = YES; 
    [self.view.layer setRasterizationScale:[UIScreen mainScreen].scale];

http://stackoverflow.com/questions/4735623/uilabel-layer-cornerradius-negatively-impacting-performance

上一篇下一篇

猜你喜欢

热点阅读