项目有个需求:裁剪图片,针对头像、下面是要求:
,
大家可以看到这张图片的圆角已经去除、下面说说我在项目利用了两种方式实现此裁剪以及查看技术文档发现更高效裁剪方式、下面一一讲解:看下来大约需要15 - 20分钟。
在公共类中跑龙套类中创建类方法
//CGContext裁剪 +(用户界面图像*)CGContextClip:(界面图像*)img cornerRadius: (CGFloat) c;
实现该方法:
//CGContext裁剪 +(用户界面图像*)CGContextClip:(界面图像*)img cornerRadius: c (CGFloat) { int w=img.size。宽度* img.scale; int h=img.size。高度* img.scale; UIGraphicsBeginImageContextWithOptions (CGSizeMake (w h),假的,1.0); CGContextRef上下文=UIGraphicsGetCurrentContext (); CGContextMoveToPoint(上下文、0 c); CGContextAddArcToPoint(上下文,0,0,c, 0, c); CGContextAddLineToPoint(上下文,含水量,0); CGContextAddArcToPoint(上下文,w, 0 w c, c); CGContextAddLineToPoint(上下文、w·hc·); CGContextAddArcToPoint(上下文,w, h,含水量,h, c); CGContextAddLineToPoint(上下文、c、h); CGContextAddArcToPoint(上下文,0 h 0·hc·c); CGContextAddLineToPoint(上下文、0 c); CGContextClosePath(上下文);//先裁剪上下文,再画的图,就会在裁剪后的路径中画 CGContextClip(上下文); [img图形:CGRectMake (0, 0 w h)];//画图 CGContextDrawPath(上下文,kCGPathFill); 用户界面图像* ret=UIGraphicsGetImageFromCurrentImageContext (); UIGraphicsEndImageContext (); 返回受潮湿腐烂; }
在该需要的地方调用如下:
(Util CGContextClip:图像cornerRadius:半径);
在Util.h类中声明
//UIBezierPath裁剪 +(用户界面图像*)UIBezierPathClip:(界面图像*)img cornerRadius: (CGFloat) c;
在Util.m实现方法
//UIBezierPath裁剪 +(用户界面图像*)UIBezierPathClip:(界面图像*)img cornerRadius: c (CGFloat) { int w=img.size。宽度* img.scale; int h=img.size。高度* img.scale; CGRect中矩形=CGRectMake (0, 0 w h); UIGraphicsBeginImageContextWithOptions (CGSizeMake (w h),假的,1.0); [[UIBezierPath bezierPathWithRoundedRect:矩形cornerRadius: c] addClip); [img图形:矩形]; 用户界面图像* ret=UIGraphicsGetImageFromCurrentImageContext (); UIGraphicsEndImageContext (); 返回受潮湿腐烂; }
对于图像上的一个点(x, y),判断其在不在圆角矩形内,在的话α是原值,不在的话α设为0即可
+(用户界面图像*)dealImage:(界面图像*)img cornerRadius: c (CGFloat)
在Util.m中实现:
+(用户界面图像*)dealImage:(界面图像*)img cornerRadius: c (CGFloat) {//1。CGDataProviderRef把CGImage转二进制流 CGDataProviderRef提供者=CGImageGetDataProvider (img.CGImage); void * imgData=https://www.yisu.com/zixun/(void *) CFDataGetBytePtr (CGDataProviderCopyData(提供者)); int宽度=img.size。宽度* img.scale; int=img.size高度。高度* img.scale;//2。处理imgData//dealImage (imgData、宽度、高度); cornerImage (imgData,宽度,高度,c);//3。CGDataProviderRef把二进制流转CGImage CGDataProviderRef pv=CGDataProviderCreateWithData (NULL, imgData、宽*高* 4,releaseData); CGImageRef内容=CGImageCreate(宽度、高度,8日,32岁的4 *宽度,CGColorSpaceCreateDeviceRGB (), kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast, pv, NULL,真的,kCGRenderingIntentDefault); 用户界面图像*结果=[界面图像imageWithCGImage:内容); CGDataProviderRelease (pv);//释放空间 CGImageRelease(内容); 返回结果; } 空白releaseData (void *信息,const void *数据,size_t大小){ 免费((void *)数据); }//在img上处理图片,测试用 空白dealImage (w UInt32 * img, int, int h) { int num=w * h; UInt32 * cur=img; for (int i=0;我iOS实现高效裁剪图片圆角算法教程