Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreGraphics draw an image on a white canvas

I have a source image which has a variable width and height, which I must show on a fullscreen iPad UIImageView but with addition of borders around the image itself. So my task is to create a new image with a white border around it, but not overlapping on the image itself. I'm currently doing it with overlapping via this code:

- (UIImage*)imageWithBorderFromImage:(UIImage*)source
{
  CGSize size = [source size];
  UIGraphicsBeginImageContext(size);
  CGRect rect = CGRectMake(0, 0, size.width, size.height);
  [source drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];

  CGContextRef context = UIGraphicsGetCurrentContext();
  CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0);
  CGContextSetLineWidth(context, 40.0);
  CGContextStrokeRect(context, rect);
  UIImage *testImg =  UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return testImg;
}

Can anyone tell me how do I first draw a white canvas that is 40 pixels bigger in each direction than the source image and then draw that image on it?

like image 899
Eugene Avatar asked Jun 05 '12 09:06

Eugene


1 Answers

I adjusted your code to make it work. Basically what it does:

  1. Set canvas size to the size of your image + 2*margins
  2. Fill the whole canvas with background color (white in your case)
  3. Draw your image in the appropriate rectangle (with initial size and required margins)

Resulting code is:

- (UIImage*)imageWithBorderFromImage:(UIImage*)source
{
    const CGFloat margin = 40.0f;
    CGSize size = CGSizeMake([source size].width + 2*margin, [source size].height + 2*margin);
    UIGraphicsBeginImageContext(size);

    [[UIColor whiteColor] setFill];
    [[UIBezierPath bezierPathWithRect:CGRectMake(0, 0, size.width, size.height)] fill];

    CGRect rect = CGRectMake(margin, margin, size.width-2*margin, size.height-2*margin);
    [source drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];

    UIImage *testImg =  UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return testImg;
}
like image 98
Vladimir Avatar answered Oct 06 '22 15:10

Vladimir