標籤:
項目中偶爾會有帶邊框圖片的需求,或是頭像亦或是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-邊框圖片,頭像邊框