九 iOS之 图片剪裁

来源:互联网 发布:卡斯柯除了软件 编辑:程序博客网 时间:2024/04/28 23:01

介绍图片剪裁,以剪裁圆形为例

普通剪裁

这里写图片描述

带圆环的图片

这里写图片描述


拖入一个UIImageView,取名“imageView”到view中

  • 裁剪出一个普通圆形图片
//0 加载图片    UIImage * image = [UIImage imageNamed:@"阿狸"];    //1 开启位图上下文,跟图片尺寸一样大    UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);    //2 设置圆形裁剪区域(改动此方法可改变裁剪形状)    UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, image.size.width, image.size.height)];    //3 把路径设置为剪裁区域    [path addClip];    //3 绘制图片    [image drawAtPoint:CGPointZero];    //4 从上下文中获取图片    UIImage * imageNew = UIGraphicsGetImageFromCurrentImageContext();    //5 关闭上下文    UIGraphicsEndImageContext();    self.imageView.image = imageNew;
  • 裁剪出带圆环的图片(给UIImage添加一个类目方法)
/** 裁剪一个带圆环的图片 @param image 图片 @param borderWidth 圆环宽度 @param color 圆环颜色 @return 裁剪完成的图片 */+(UIImage*)imageWithClipImage:(UIImage*)image borderWidth:(CGFloat)borderWidth borderColor:(UIColor*)color{    //图片的高度和宽度    CGFloat imageWH = image.size.width;    //圆环的宽度    CGFloat border = borderWidth;    //大圆形的宽度和高度    CGFloat ovalWH = imageWH + 2 * border;  //1、开启上下文    UIGraphicsBeginImageContextWithOptions(CGSizeMake(ovalWH, ovalWH), NO, 0);    //2、画大圆    UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, ovalWH, ovalWH)];    [color set];    [path fill];    //3、设置剪裁区域(需先设置)    UIBezierPath * clipPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(border, border, imageWH, imageWH)];    [clipPath addClip];    //4.绘制图片    [image drawAtPoint:CGPointMake(border, border)];    //5、获取图片    UIImage * clipImage = UIGraphicsGetImageFromCurrentImageContext();    //6、关闭上下文    UIGraphicsEndImageContext();    return clipImage;}

github demo : PictureCutDemo

原创粉丝点击