在開發(fā)過程常遇到控件圓角的設(shè)計(jì);我們常用的方式是設(shè)置layer屬性如下:
self.imageView.layer.cornerRadius = 5;
self.imageView.layer.masksToBounds = YES;
這種處理的渲染機(jī)制是GPU在當(dāng)前屏幕緩沖區(qū)外新開辟一個渲染緩沖區(qū)進(jìn)行工作,也就是離屏渲染。如果圓角操作達(dá)到一定數(shù)量,會觸發(fā)緩沖區(qū)的頻繁合并和上下文頻繁切換,性能的代價會宏觀地表現(xiàn)在用戶體驗(yàn)上——掉幀。
方案1:使用貝塞爾曲線UIBezierPath和Core Graphics框架畫出一個圓角
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"imagename"];
//開始對imageView進(jìn)行畫圖
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, NO, 1.0);
//使用貝塞爾曲線畫出一個圓形圖
[[UIBezierPath bezierPathWithRoundedRect:imageView.bounds cornerRadius:imageView.frame.size.width] addClip];
[imageView drawRect:imageView.bounds];
imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self.view addSubview:imageView];
方案2:使用CAShapeLayer和UIBezierPath設(shè)置圓角
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100,100,100,100)];
imageView.image = [UIImage imageNamed:@"imagename"];
UIBezierPath *maskPath=[UIBezierPath bezierPathWithRoundedRect:imageView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:imageView.bounds.size];
CAShapeLayer *maskLayer=[[CAShapeLayer alloc]init];
maskLayer.frame=imageView.bounds;
maskLayer.path=maskPath.CGPath;
imageView.layer.mask=maskLayer;
[self.view addSubview:imageView];
轉(zhuǎn)發(fā):http://www.itdecent.cn/p/b4b002f8f1e7