iOS-边框图片,头像边框

项目中偶尔会有带边框图片的需求,或是头像亦或是logo.在原型图片外围加一自定义颜色的边框,思路是根据上下文绘制,写了Demo和解释.
带边框的图片Demo:

-(void)borderImage{
    //1.加载图片
    UIImage *image = [UIImage imageNamed:@"baby"];
    //2.边框宽度
    CGFloat borderW = 10;
    //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)];
    [[UIColor redColor] 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();
    self.imageV.image = newImage;
}

方便调用的UIIamge的分类:

/**
 *  带边框的图片
 *
 *  @param imageName   图片名
 *  @param imageWidth  图片宽度
 *  @param imageHeight 图片高度
 *  @param borderWidth 边框宽度
 *  @param borderColor 边框颜色
 *
 *  @return 带边框的图片
 */
+(UIImage *)imageWithImageName:(NSString *)imageName imageWidth:(CGFloat)imageWidth imageHeight:(CGFloat)imageHeight borderWidth:(CGFloat)borderWidth borderColor:(UIColor *)borderColor{
    UIImage *image = [UIImage imageNamed:imageName];
    CGSize size = CGSizeMake(imageWidth + 2 * borderWidth, imageHeight + 2 * borderWidth);
    UIGraphicsBeginImageContextWithOptions(size, NO, 0);
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];
    [borderColor set];
    [path fill];
    path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderWidth, borderWidth, imageWidth, imageHeight)];
    [path addClip];
    [image drawInRect:CGRectMake(borderWidth, borderWidth, imageWidth, imageHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

完整项目Demo链接:
https://github.com/qxuewei/XWBorderImage

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值