CoreGraphics在白色的canvas上绘制图像

我有一个具有可变宽度和高度的源图像,我必须在全屏iPad UIImageView上显示,但在图像本身附加了边框。 所以我的任务是创build一个带有白色边框的新图像,但不能与图像本身重叠。 我目前正在通过这个代码重叠:

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

任何人都可以告诉我,我怎么第一次绘制一个白色的canvas,在每个方向比源图像大40个像素,然后在上面画这个图像?

我调整了你的代码,使其工作。 基本上它是这样做的:

  1. 将canvas大小设置为图像大小+ 2 *边距
  2. 用背景颜色填充整个canvas(在你的情况下为白色)
  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; }