標籤:
圓角的設定在iOS中隨處可見,開發的時候也很方便,但是有的時候如果一個頁面有大量的需要設定圓角的圖片,容易產生效能問題,UIImageView ios9.0之前設定圓角是會產生離屏渲染的,9.0之後不會產生離屏渲染
因此需要日常設定圓角的方法上加一些改動:
1.最簡單的圖片圓角設定:
self.imageView=[[UIImageView alloc]initWithFrame:CGRectMake(100,200, 100, 100)]; [self.imageView setImage:[UIImage imageNamed:@"FlyElephant.jpg"]]; self.imageView.layer.cornerRadius=50; self.imageView.layer.masksToBounds=YES; [self.view addSubview:self.imageView];
2.設定Rasterize柵格化處理,會將圖片放在緩衝區,不會不斷的進行圖片渲染:
self.imageView=[[UIImageView alloc]initWithFrame:CGRectMake(100,200, 100, 100)]; [self.imageView setImage:[UIImage imageNamed:@"dress3.jpg"]]; self.imageView.layer.cornerRadius=50; self.imageView.layer.shouldRasterize = YES; self.imageView.clipsToBounds=YES; self.imageView.layer.rasterizationScale=[UIScreen mainScreen].scale; //不設定會模糊,不相信可以自己嘗試 [self.view addSubview:self.imageView];
3.UIBezierPath貝茲路徑繪製(推薦)
self.imageView=[[UIImageView alloc]initWithFrame:CGRectMake(100,200, 100, 100)]; UIImage *anotherImage = [UIImage imageNamed:@"FlyElephant.jpg"]; //注意第三個選項的設定 UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, NO, [UIScreen mainScreen].scale); //在繪製之前先裁剪出一個圓形 [[UIBezierPath bezierPathWithRoundedRect:self.imageView.bounds cornerRadius:50] addClip]; //圖片在設定的圓形裡面進行繪製 [anotherImage drawInRect:self.imageView.bounds]; //擷取圖片 self.imageView.image = UIGraphicsGetImageFromCurrentImageContext(); //結束繪製 UIGraphicsEndImageContext(); [self.view addSubview:self.imageView];
參考資料:http://stackoverflow.com/questions/11049016/cliptobounds-and-maskstobounds-performance-issue
http://stackoverflow.com/questions/17593524/using-cornerradius-on-a-uiimageview-in-a-uitableviewcell
iOS開發-UIImageView高效設定Radius