自从iOS7出来之后,越来越多的应用头像设计成圆形了,圆形设计的头像看起来确实挻上流的。现在我给大家带来两种把UIImageView的图片设计成圆形。
方案一:从UIImageView的布局着手
我相信大家都知道对UIImageView的layer设置方法来把图片设计成圆形。
self.avatarImageView = [[ABELImageView alloc] init];self.avatarImageView.frame = CGRectMake(15, 6, 48, 48);self.avatarImageView.image = [UIImage imageNamed:@"DefaultAvatar.png"];self.avatarImageView.layer.masksToBounds = YES;// 这个必须设置为YES[self.avatarImageView.layer setCornerRadius:24.0];
方案二:从UIImage着手
我们想要图片显示成圆形,只要把UIImage弄成圆形就可以了。
UIImage的category
static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth,
float ovalHeight)
{
float fw, fh;
if (ovalWidth == 0 || ovalHeight == 0)
{
CGContextAddRect(context, rect);
return;
}
CGContextSaveGState(context);
CGContextTranslateCTM(context, CGRectGetMinX(rect), CGRectGetMinY(rect));
CGContextScaleCTM(context, ovalWidth, ovalHeight);
fw = CGRectGetWidth(rect) / ovalWidth;
fh = CGRectGetHeight(rect) / ovalHeight;
CGContextMoveToPoint(context, fw, fh/2); // Start at lower right corner
CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1); // Top right corner
CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1); // Top left corner
CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1); // Lower left corner
CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1); // Back to lower right
CGContextClosePath(context);
CGContextRestoreGState(context);
}
+ (id)createRoundedRectImage:(UIImage*)image size:(CGSize)size radius:(NSInteger)radius
{
// the size of CGContextRef
int width = size.width;
UIImage *img = image;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef context = CGBitmapContextCreate(NULL, width, width, 8, 4 * width, colorSpace, 2); //2 = kCGImageAlphaPremultipliedFirst
CGRect rect = CGRectMake(0, 0, width, width);
CGContextBeginPath(context);
addRoundedRectToPath(context, rect, radius, radius);
CGContextClosePath(context);
CGContextClip(context);
CGContextDrawImage(context, CGRectMake(0, 0, width, width), img.CGImage);
CGImageRef imageMasked = CGBitmapContextCreateImage(context);
img = [UIImage imageWithCGImage:imageMasked];
CGContextRelease(context);
CGColorSpaceRelease(colorSpace);
CGImageRelease(imageMasked);
return img;
}
实际应用
self.avatarImageView = [[ABELImageView alloc] init];
self.avatarImageView.frame = CGRectMake(15, 6, 48, 48);
self.avatarImageView.image = [UIImage createRoundedRectImage:image size:image.size radius:image.size.width / 2.0];
两种方法对比:第一种比较简单,也是大家比较常用的方法,但对用户体验不好,运行在UITableView上的时候会有一点卡的效果,当然对于不是要求特别高的应用可以忽略这一点。第二种是通过低层的绘图方式,优点是效率好,不会存在卡的效果,相对来说有一定的难度。