iOS給UIimage添加圓角的兩種方式


眾所周知,給圖片添加圓角有CALayer的cornerRadius,

比如:

最直接的方法:

imgView.layer.cornerRadius1=110;
 
imgView.clipsToBounds = YES;
 
這事離屏渲染 (off - screen - rendering), 是很消耗性能的;有很多公司面試的時候會問到,你怎么將圖片設置圓角,如果你
 
只回答了這個方法,那么很遺憾,沒有加分。
 
下面我介紹一種更好的方法:
 
#import "Bys.h"

@implementation Bys

-(UIImage*)imageWithCornerRadius:(CGFloat)radius{
    
    CGRect rect = (CGRect){0.f,0.f,self.size};
    
    // void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale);
    //size——同UIGraphicsBeginImageContext,參數size為新創建的位圖上下文的大小
    //    opaque—透明開關,如果圖形完全不用透明,設置為YES以優化位圖的存儲。
    //    scale—–縮放因子
    UIGraphicsBeginImageContextWithOptions(self.size, NO, [UIScreen mainScreen].scale);
    
    //根據矩形畫帶圓角的曲線
    CGContextAddPath(UIGraphicsGetCurrentContext(), [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
    
    [self drawInRect:rect];
    
    //圖片縮放,是非線程安全的
    UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
    
    //關閉上下文
    UIGraphicsEndImageContext();
  
    return image;
}

給UIImage添加生成圓角圖片的擴展API: 這是on-screen-rendering

 



 


免責聲明!

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



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