好久没写了过了,继续开写吧.
将图片转化裁剪为圆形的头像
-(UIImage*) imageToHeadView:(UIImage*)image withParam:(CGFloat)inset{
//先获取大小
CGFloat lengthW = CGImageGetWidth(image.CGImage);
CGFloat lengthH = CGImageGetHeight(image.CGImage);
CGFloat cutSzie;
//判断长宽比,获得最大正方形裁剪值
if(lengthW>= lengthH){
cutSzie = lengthH;
}
else cutSzie = lengthW;
//执行裁剪(为正方形)
CGImageRef sourceImageRef = [image CGImage]; //将UIImage转换成CGImageRef
CGRect rect = CGRectMake(lengthW/2-cutSzie/2, lengthH/2 - cutSzie/2, cutSzie, cutSzie); //构建裁剪区
CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect); //按照给定的矩形区域进行剪裁
UIImage *newImage = [UIImage imageWithCGImage:newImageRef]; //将CGImageRef转换成UIImage
//取圆形
UIGraphicsBeginImageContextWithOptions(newImage.size, NO, 0);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [UIColor clearColor].CGColor);
CGContextFillPath(context);
CGContextSetLineWidth(context, .5);
CGContextSetStrokeColorWithColor(context, [UIColor clearColor].CGColor);
CGRect newrect = CGRectMake(inset, inset, newImage.size.width - inset * 2.0f, newImage.size.height - inset * 2.0f);
CGContextAddEllipseInRect(context, newrect);
CGContextClip(context);
[newImage drawInRect:newrect];
CGContextAddEllipseInRect(context, newrect);
CGContextStrokePath(context);
UIImage *circleImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return circleImg;
}
原图:
edit_background1.jpg
效果图:
Demo.png
调用:
UIImage *img = [UIImage imageNamed:@"edit_background1.jpg"];
img = [self imageToHeadView:img withParam:0]; //封装的方法,从中间裁剪为圆形,后面参数为偏移量
小小白一只,就是这样啦
网友评论