CoreGraphics在白色画布上绘制图像

时间:2012-06-05 09:43:56

标签: objective-c ios core-graphics

我有一个可变宽度和高度的源图像,我必须在全屏iPad UIImageView上显示,但在图像本身周围添加了边框。所以我的任务是创建一个周围有白色边框的新图像,但不会在图像本身上重叠。我目前通过此代码进行重叠:

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

有人能告诉我如何在每个方向上绘制比源图像大40像素的白色画布,然后在其上绘制图像?

1 个答案:

答案 0 :(得分:15)

我调整了您的代码以使其正常工作。基本上它的作用是什么:

  1. 将画布大小设置为图像大小+ 2 *边距
  2. 用背景颜色填充整个画布(在您的情况下为白色)
  3. 在适当的矩形中绘制图像(具有初始大小和所需边距)
  4. 结果代码是:

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