ios - 为 UIImage 添加白色边框

标签 ios objective-c 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, 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;
}

Reference

关于ios - 为 UIImage 添加白色边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27395497/

相关文章:

ios - 缺少 [UIImage imageWithContentsOfURL] 的原因

ios - 如何在swift 4中使用 "WWCalendarTimeSelector"第三方

ios - 从 CGPoints 数组创建 CGContext

iOS 9 UITableView 单元格的文本标签不是 UITableView 的全宽

ios - 内存地址是否遵循 iOS 中的模式?

iphone - 提高 iPhone 上 pdf 渲染的性能

ios - Swift - 将 EPS 文件(或类似文件)转换为 Core Graphics 路径

ios - 导航栏中的自定义图标 Swift 3

ios - UIImage 返回零

ios - 截图时没有相机 View ,只有白色背景