带有边框的图片裁剪

创建UIImage的分类

.h文件

#import 

@interface UIImage (image)

//给图片设置边框
//borderW:边框宽度
//borderColor:边框颜色
//image:要设置边框的图片.
+ (UIImage *)imageWithBorderWidth:(CGFloat)borderW borderColor:(UIColor *)color image:(UIImage *)image;
@end

.m文件

#import "UIImage+image.h"

@implementation UIImage (image)


+ (UIImage *)imageWithBorderWidth:(CGFloat)borderW borderColor:(UIColor *)color image:(UIImage *)image{
    
    //3.开启图片上下文.
    CGSize size = CGSizeMake(image.size.width + 2 * borderW, image.size.height + 2 * borderW);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    //4.先描述一个大圆,设为填充
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];
    //设置边框的颜色
    [color set];
    [path fill];
    //5.再添加一个小圆,把小圆设裁剪区域
    
    path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];
    [path addClip];
    
    //6.把图片给绘制上下文.
    [image drawInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];
    //7.生成一张新的图片
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //8.关闭上下文.
    UIGraphicsEndImageContext();
    
    return newImage;
    
}


@end

带有边框的图片裁剪_第1张图片
效果图:边框是圆形的绿色

你可能感兴趣的:(带有边框的图片裁剪)