標籤:
眾所周知,給圖片添加圓角有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
iOS給UIimage添加圓角的兩種方式