项目中偶尔会有带边框图片的需求,或是头像亦或是logo.在原型图片外围加一自定义颜色的边框,思路是根据上下文绘制,写了Demo和解释.
带边框的图片Demo:
-(void)borderImage{
UIImage *image = [UIImage imageNamed:@"baby"];
CGFloat borderW = 10;
CGSize size = CGSizeMake(image.size.width+2*borderW, image.size.height+2*borderW);
UIGraphicsBeginImageContextWithOptions(size, NO, 0);
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, size.width, size.height)];
[[UIColor redColor] set];
[path fill];
path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];
[path addClip];
[image drawInRect:CGRectMake(borderW, borderW, image.size.width, image.size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.imageV.image = newImage;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
方便调用的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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
完整项目Demo链接:
https://github.com/qxuewei/XWBorderImage