如果要适配ios7的系统,要给一张图片切成一张圆形图,用layer的圆角发现程序很"卡",所以如果可以,用“绘图”技术来解决问题,通过看视频,获取了信息,封装了一个工具分类
.h文件
/* 设置圆环切图
* name:要切图的图片名
* borderWidth: 被切掉的圆环的边框宽度
* 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];
//开始画图上下文(由于外面要设计一个大圆环,所以这个小相对大一点了)
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();
//画外面的圆环
[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();
//结束上下文
UIGraphicsEndImageContext();
return newImg;
}
-(UIImage *)circleImage
{
//第二个参数填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;
}