iOS如何将图片裁剪成圆形

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

原图:

圆形图片裁剪效果:

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

核心代码:

#import <UIKit/UIKit.h>

@interface UIImage (image)

/**
 * 生成一张圆形图片
 *
 * @param image    要裁剪的图片
 *
 * @return 生成的圆形图片
 */

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

/**
 * 生成一张带有边框的圆形图片
 *
 * @param borderW   边框宽度
 * @param borderColor 边框颜色
 * @param image    要添加边框的图片
 *
 * @return 生成的带有边框的圆形图片
 */
+ (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;
}

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

若文章对您有帮助,帮忙点个赞!

0
-3
发布时间 2020-02-22 12:00:54
0 条回复(回复会通过微信通知作者)
点击加载更多评论
登录 后再进行评论
(微信扫码即可登录,无需注册)