代碼如下:
- (UIImage *)addBorderToImage:(UIImage *)image {
CGImageRef bgimage = [image CGImage];
float width = CGImageGetWidth(bgimage);
float height = CGImageGetHeight(bgimage);
//建立臨時紋理資料緩沖區
void *data = malloc(width * height * 4);
//将圖檔繪制到緩沖區中
CGContextRef ctx = CGBitmapContextCreate(data,
width,
height,
8,
width * 4,
CGImageGetColorSpace(image.CGImage),
kCGImageAlphaPremultipliedLast);
CGContextDrawImage(ctx, CGRectMake(0, 0, (CGFloat)width, (CGFloat)height), bgimage);
CGFloat lineWidth = 4.0; //線寬
CGContextSetRGBStrokeColor(ctx,205,193,193,1.0);//畫筆線的顔色
CGContextSetLineWidth(ctx, lineWidth);//線的寬度
// x,y為圓點坐标,radius半徑,startAngle為開始的弧度,endAngle為 結束的弧度,clockwise 0為順時針,1為逆時針。
CGContextAddArc(ctx, width/2, width/2, width/2-lineWidth/2, 0, 2*3.14159265358979323846, 0); //添加一個圓
CGContextDrawPath(ctx, kCGPathStroke); //繪制路徑
//繪制
CGContextStrokePath(ctx);
//将其繪制到新的圖檔上
CGImageRef cgimage = CGBitmapContextCreateImage(ctx);
UIImage *newImage = [UIImage imageWithCGImage:cgimage];
CFRelease(cgimage);
CGContextRelease(ctx);
return newImage;
}