码迷,mamicode.com
首页 > 移动开发 > 详细

iOS-边框图片,头像边框

时间:2016-08-09 10:48:32      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:

项目中偶尔会有带边框图片的需求,或是头像亦或是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

iOS-边框图片,头像边框

标签:

原文地址:http://blog.csdn.net/qxuewei/article/details/52160259

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!