2012-06-05 32 views
6

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

- (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个像素的图片,然后借鉴它的形象?

回答

12

我调整了您的代码,使其工作。基本上它:

  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; 
} 
+0

优良,由于维拉德 – Eugene