Search code examples
objective-ccocoansimage

Add a white background to an NSImage that is larger than the original image


I am currently adding a solid white background to an NSImage so that in the case that the image has a transparent background it becomes opaque.

What I would like to be able to do is increase the size of the white background so that it extends out all around the original image (thus giving it a white border).

This is what I currently have, but I can't work out how to create the white image larger that the original.

NSImage* importedImage = [bitmapImage image];

NSSize imageSize = [importedImage size];
NSImage* background = [[NSImage alloc] initWithSize:imageSize];

[background lockFocus];
[[NSColor whiteColor] setFill];

[NSBezierPath fillRect:NSMakeRect(0, 0, imageSize.width, imageSize.height)];
[background unlockFocus];

theImage = [[NSImage alloc] initWithSize:imageSize];
[theImage lockFocus];
CGRect newImageRect = CGRectZero;
newImageRect.size = [theImage size];
[background drawInRect:newImageRect];
[importedImage drawInRect:newImageRect];
[theImage unlockFocus];

Solution

  • I finally solved this. First I get the size of the original image and create the white background to this size plus twice the width of the border that I want.

    Then, I create a new image and draw in the white background, then the original image making sure that its origin = the border width.

    -(NSImage*) addBorderToImage:(NSImage *)theImage
    {
    
    //get the border slider value...
    float borderWidth = [borderSlider floatValue];
    
    //get the size of the original image and incease it to include the border size...
    NSBitmapImageRep* bitmap = [[theImage representations] objectAtIndex:0];
    NSSize imageSize = NSMakeSize(bitmap.pixelsWide+(borderWidth*2),bitmap.pixelsHigh+(borderWidth*2));
    
    //create a new image with this size...
    NSImage* borderedImage = [[NSImage alloc] initWithSize:imageSize];
    
    [borderedImage lockFocus];
    
    //fill the new image with white...
    [[NSColor whiteColor] setFill];
    [NSBezierPath fillRect:NSMakeRect(0, 0, imageSize.width, imageSize.height)];
    
    //rect of new image size...
    CGRect newImageRect = CGRectZero;
    newImageRect.size = [borderedImage size];
    
    //rect of old image size positioned inside the border...
    CGRect oldImageRect = CGRectZero;
    oldImageRect.size = [theImage size];
    oldImageRect.origin.x = borderWidth;
    oldImageRect.origin.y = borderWidth;
    
    //draw in the white filled image...
    [borderedImage drawInRect:newImageRect];
    //draw in the original image...
    [theImage drawInRect:oldImageRect];
    [borderedImage unlockFocus];
    
    return borderedImage;
    
    }