如果要適配ios7的系統(tǒng),要給一張圖片切成一張圓形圖,用layer的圓角發(fā)現(xiàn)程序很"卡",所以如果可以,用“繪圖”技術(shù)來解決問題,通過看視頻,獲取了信息,封裝了一個工具分類
.h文件
/*? 設(shè)置圓環(huán)切圖
*? name:要切圖的圖片名
*? borderWidth: 被切掉的圓環(huán)的邊框?qū)挾?/p>
*? borderColor: 邊框顏色
*/
+(instancetype)circleImageWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor;
/**
*? 圓形圖片
*/
-(UIImage *)circleImage;
.m文件
+(instancetype)circleImageWithName:(NSString *)name borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor
{
//獲得老圖片
UIImage *oldimage = [UIImage imageNamed:name];
//開始畫圖上下文(由于外面要設(shè)計一個大圓環(huán),所以這個小相對大一點了)
CGFloat imgW = oldimage.size.width + borderWidth;
CGFloat imgH = oldimage.size.height + borderWidth;
CGSize imgSize = CGSizeMake(imgW, imgH);
UIGraphicsBeginImageContextWithOptions(imgSize, NO, 0.0);
//獲得上下文
CGContextRef ref = UIGraphicsGetCurrentContext();
//畫外面的圓環(huán)
[borderColor set];
CGFloat bigRadius = imgW * 0.5;
CGFloat currentX = bigRadius;
CGFloat currentY = bigRadius;
CGContextAddArc(ref, currentX, currentY, bigRadius, 0, M_PI * 2, 0);
CGContextFillPath(ref);
//畫里面的小圓
CGFloat smallRadius = bigRadius - borderWidth;
CGContextAddArc(ref, currentX, currentY, smallRadius, 0, M_PI * 2, 0);
//裁剪
CGContextClip(ref);
//畫圖
[oldimage drawInRect:CGRectMake(borderWidth, borderWidth, oldimage.size.width, oldimage.size.height)];
//取圖
UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
//結(jié)束上下文
UIGraphicsEndImageContext();
return newImg;
}
-(UIImage *)circleImage
{
//第二個參數(shù)填NO是透明
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
//獲得上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
//獲得一個圓
CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
CGContextAddEllipseInRect(ctx, rect);
//裁剪
CGContextClip(ctx);
//將圖片畫上去
[self drawInRect:rect];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}