iOS開發-UIImageView高效設置Radius


圓角的設置在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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM