sasha sasha - 21 days ago 6
iOS Question

add white border to UIImage

My question might be very easy for you.

I am trying to add white border to

UIImage
in my photo editing app. I found some questions and answers How can i take an UIImage and give it a black border?.

Most answers are for adding border to
UIImageView
. In my case, I need to add a border to
UIImage
with adjustable border width.

Could you help me please?

Answer

You can set the border properties on the CALayer by accessing the layer property of the UIImageView.

First, add Quartz

#import <QuartzCore/QuartzCore.h>

Set properties:

[[yourImageView layer] setBorderWidth:2.0f];
[[yourImageView layer] setBorderColor:[UIColor whiteColor].CGColor];

Edit 1

As you need to save the image with border, use below.

- (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

Comments