tableView的性能优化--不使用cornerRadius设置图片圆角
有人问我为什么tableView滑动不流畅,甚至闪退,其实和cell中的圆角头像使用了cornerRadius有关
优化点
行高一定要缓存
不要动态创建子视图
所有子视图都要预先创建
所有的子视图都应该添加到 contentView上
普通
[imageView.layer setCornerRadius:50];// 设置圆角半径
imageView.clipsToBounds = YES;// 超出主层边框就要裁剪掉
第一种方法:通过设置layer的属性,实现圆角(这种方法在iOS9以前可能会造这样设置会触发离屏渲染,比较消耗性能。比如当一个页面上有十几头像这样设置了圆角
会明显感觉到卡顿。
这种就是最常用的,也是最耗性能的。
注意:ios9.0之后对UIImageView的圆角设置做了优化,UIImageView这样设置圆角
不会触发离屏渲染,ios9.0之前还是会触发离屏渲染。而UIButton还是都会触发离屏渲染。
方案一;shapeLayer的实现
#import <UIKit/UIKit.h>
@interface UIImageView (Category)
///使用CAShapeLayer和UIBezierPath设置圆角
- (void) setRoundedCornersSize:(CGFloat)cornersSize ;
@end
#import "UIImageView+Category.h"
@implementation UIImageView (Category)
- (void)setRoundedCornersSize:(CGFloat)cornersSize {
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
cornerRadius:cornersSize];
CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
maskLayer.frame = self.bounds;
maskLayer.path = maskPath.CGPath;
self.layer.mask = maskLayer;
}
@end
其他方案
最好的是#pragma mark - 通过Graphics 和 BezierPath 设置圆角
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"keai"]];
imageView.backgroundColor = [UIColor yellowColor];
imageView.frame = CGRectMake(100, 100, self.view.frame.size.width - 200, self.view.frame.size.width - 200);
[self.view addSubview:imageView];
// [self setGraphicsCutCirculayWithView:imageView roundedCornersSize:100];
[self setLayerAndBezierPathCutCircularWithView:imageView roundedCornersSize:100];
}
#pragma mark - 通过设置layer 切圆角
- (void)setLayerCutCirculayWithView:(UIView *) view roundedCornersSize:(CGFloat )cornersSize
{
view.layer.masksToBounds = YES;
// 设置圆角半径
view.layer.cornerRadius = cornersSize;
}
#pragma mark - 通过layer和bezierPath 设置圆角
- (void)setLayerAndBezierPathCutCircularWithView:(UIView *) view roundedCornersSize:(CGFloat )cornersSize
{
// 创建BezierPath 并设置角 和 半径 这里只设置了 左上 和 右上
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(cornersSize, cornersSize)];
CAShapeLayer *layer = [[CAShapeLayer alloc] init];
layer.frame = view.bounds;
layer.path = path.CGPath;
view.layer.mask = layer;
}
#pragma mark - 通过Graphics 和 BezierPath 设置圆角
- (void)setGraphicsCutCirculayWithView:(UIImageView *) view roundedCornersSize:(CGFloat )cornersSize
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 1.0);
[[UIBezierPath bezierPathWithRoundedRect:view.bounds cornerRadius:cornersSize] addClip];
[view drawRect:view.bounds];
view.image = UIGraphicsGetImageFromCurrentImageContext();
// 结束
UIGraphicsEndImageContext();
}
@end