6

我有一个具有可变宽度和高度的源图像,我必须在全屏 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 像素的白色画布,然后在其上绘制该图像?

4

1 回答 1

15

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

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

结果代码是:

- (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;
}
于 2012-06-05T09:57:02.847 回答