当前位置:首页 > 通信资讯 > 正文

ios怎么把图片裁剪成圆形(怎么裁剪圆形头像)

本文实例为大家介绍了ios裁剪圆形头像的详细代码,供大家参考,具体内容如下

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 - (void)viewdidload { [super viewdidload]; //加载图片 uiimage *image = [uiimage imagenamed:@"菲哥"]; //获取图片尺寸 cgsize size = image.size; //开启位图上下文 uigraphicsbeginimagecontextwithoptions(size, no, 0); //创建圆形路径 uibezierpath *path = [uibezierpath bezierpathwithovalinrect:cgrectmake(0, 0, image.size.width, image.size.height)]; //设置为裁剪区域 [path addclip]; //绘制图片 [image drawatpoint:cgpointzero]; //获取裁剪后的图片 _imageview.image = uigraphicsgetimagefromcurrentimagecontext(); //关闭上下文 uigraphicsendimagecontext(); }

再来一张菲哥的头像

ios怎么把图片裁剪成圆形(怎么裁剪圆形头像)

如果想要在圆形头像外加一个边框,思路是先绘制一个大圆,然后在这个圆尺寸范围内绘制一个图片大小的圆。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 - (void)viewdidload { [super viewdidload]; //加载图片 uiimage *image = [uiimage imagenamed:@"大菲哥"]; //设置边框宽度 cgfloat border = 3; cgfloat imagewh = image.size.width; //计算外圆的尺寸 cgfloat ovalwh = imagewh + 2 * border; //开启上下文 uigraphicsbeginimagecontextwithoptions(image.size, no, 0); //画一个大的圆形 uibezierpath *path = [uibezierpath bezierpathwithovalinrect:cgrectmake(0, 0, ovalwh, ovalwh)]; [[uicolor orangecolor]set]; [path fill]; //设置裁剪区域 uibezierpath *path1 = [uibezierpath bezierpathwithovalinrect:cgrectmake(border, border, imagewh, imagewh)]; [path1 addclip]; //绘制图片 [image drawatpoint:cgpointmake(border, border)]; //从上下文中获取图片 _imageview.image = uigraphicsgetimagefromcurrentimagecontext(); //关闭上下文 uigraphicsendimagecontext(); }

效果如图:

ios怎么把图片裁剪成圆形(怎么裁剪圆形头像)

屏幕截图代码:
原理就是把屏幕上控件的layer渲染到上下文中

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 - (void)viewdidload { [super viewdidload]; //开启上下文 uigraphicsbeginimagecontextwithoptions(self.view.bounds.size, no, 0); //获取上下文 cgcontextref ctx = uigraphicsgetcurrentcontext(); //把控件上的图层渲染到上下文 [self.view.layer renderincontext:ctx]; //获取上下文中的图片 uiimage *image = uigraphicsgetimagefromcurrentimagecontext(); //关闭上下文 uigraphicsendimagecontext(); //保存图片到相册 uiimagewritetosavedphotosalbum(image, nil, nil, nil); }

以上就是本文的全部内容,希望对大家的学习有所帮助。

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。