CoreGraphics在白色画布上绘制图像

Eug*_*ene 6 core-graphics objective-c ios

我有一个可变宽度和高度的源图像,我必须在全屏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;
}
Run Code Online (Sandbox Code Playgroud)

任何人都可以告诉我如何首先绘制一个白色画布,每个方向比源图像大40像素,然后在上面绘制图像?

Vla*_*mir 15

我调整了你的代码以使它工作.它基本上是做什么的:

  1. 将画布大小设置为图像大小+ 2*边距
  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;
}
Run Code Online (Sandbox Code Playgroud)