ios – 为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];

编辑1

由于需要使用边框保存图像,请使用以下内容.

- (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,(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,height);
    CGContextAddLinetoPoint(ctx,0.0);
    CGContextAddLinetoPoint(ctx,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;
}

Reference

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...