栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > iOS

iOS如何将图片裁剪成圆形

iOS 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

iOS如何将图片裁剪成圆形

本文实例为大家分享了iOS将图片裁剪成圆形的具体代码,供大家参考,具体内容如下

原图:

圆形图片裁剪效果:

裁剪成带边框的圆形图片:

核心代码:

#import 

@interface UIImage (image)



+ (UIImage *)imageWithClipImage:(UIImage *)image;


+ (UIImage *)imageWithBorder:(CGFloat)borderW color:(UIColor *)borderColor image:(UIImage *)image;

@end
#import "UIImage+image.h"

@implementation UIImage (image)

+ (UIImage *)imageWithClipImage:(UIImage *)image{
+ 
  //1.开启跟原始图片一样大小的上下文
  UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
  //2.设置一个圆形裁剪区域
  //2.1绘制一个圆形
  UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
  //2.2.把圆形的路径设置成裁剪区域
  [path addClip];//超过裁剪区域以外的内容都给裁剪掉
  //3.把图片绘制到上下文当中(超过裁剪区域以外的内容都给裁剪掉)
  [image drawAtPoint:CGPointZero];
  //4.从上下文当中取出图片
  UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  //5.关闭上下文
  UIGraphicsEndImageContext();

  return newImage;
}

+ (UIImage *)imageWithBorder:(CGFloat)borderW color:(UIColor *)borderColor image:(UIImage *)image{

  //1.开启一个上下文
  CGSize size = CGSizeMake(image.size.width + 2 * borderW, image.size.height + 2 * borderW);
  UIGraphicsBeginImageContextWithOptions(size, NO, 0);
  //2.绘制大圆,显示出来
  UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];
  [borderColor set];
  [path fill];
  //3.绘制一个小圆,把小圆设置成裁剪区域
  UIBezierPath *clipPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];
  [clipPath addClip];
  //4.把图片绘制到上下文当中
  [image drawAtPoint:CGPointMake(borderW, borderW)];
  //5.从上下文当中取出图片
  UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
  //6.关闭上下文
  UIGraphicsEndImageContext();

  return newImage;
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/165848.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号