<分区>
我的问题对你来说可能很简单。
我正在尝试在我的照片编辑应用程序中向 UIImage
添加白色边框。我找到了一些问题和答案How can i take an UIImage and give it a black border? .
大多数答案都是为 UIImageView
添加边框。在我的例子中,我需要向 UIImage
添加一个边框宽度可调的边框。
你能帮帮我吗?
<分区>
我的问题对你来说可能很简单。
我正在尝试在我的照片编辑应用程序中向 UIImage
添加白色边框。我找到了一些问题和答案How can i take an UIImage and give it a black border? .
大多数答案都是为 UIImageView
添加边框。在我的例子中,我需要向 UIImage
添加一个边框宽度可调的边框。
你能帮帮我吗?
最佳答案
您可以通过访问 UIImageView 的图层属性来设置 CALayer 的边框属性。
首先,添加Quartz
#import <QuartzCore/QuartzCore.h>
设置属性:
[[yourImageView layer] setBorderWidth:2.0f];
[[yourImageView layer] setBorderColor:[UIColor whiteColor].CGColor];
因为你需要保存带边框的图片,使用下面的。
- (UIImage *)addBorderToImage:(UIImage *)image {
CGImageRef bgimage = [image CGImage];
float width = CGImageGetWidth(bgimage);
float height = CGImageGetHeight(bgimage);
// Create a temporary texture data buffer
void *data = malloc(width * height * 4);
// Draw image to buffer
CGContextRef ctx = CGBitmapContextCreate(data,
width,
height,
8,
width * 4,
CGImageGetColorSpace(image.CGImage),
kCGImageAlphaPremultipliedLast);
CGContextDrawImage(ctx, CGRectMake(0, 0, (CGFloat)width, (CGFloat)height), bgimage);
//Set the stroke (pen) color
CGContextSetStrokeColorWithColor(ctx, [UIColor greenColor].CGColor);
//Set the width of the pen mark
CGFloat borderWidth = (float)width*0.05;
CGContextSetLineWidth(ctx, borderWidth);
//Start at 0,0 and draw a square
CGContextMoveToPoint(ctx, 0.0, 0.0);
CGContextAddLineToPoint(ctx, 0.0, height);
CGContextAddLineToPoint(ctx, width, height);
CGContextAddLineToPoint(ctx, width, 0.0);
CGContextAddLineToPoint(ctx, 0.0, 0.0);
//Draw it
CGContextStrokePath(ctx);
// write it to a new image
CGImageRef cgimage = CGBitmapContextCreateImage(ctx);
UIImage *newImage = [UIImage imageWithCGImage:cgimage];
CFRelease(cgimage);
CGContextRelease(ctx);
// auto-released
return newImage;
}
关于ios - 为 UIImage 添加白色边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27395497/