添加宽度到UIImage?

时间:2016-06-02 21:19:21

标签: ios objective-c uiimage cgimage

我有96x96的图像,我想为它添加额外的宽度,以便新图像为120 x 96,图像居中。

enter image description here

以上是我所拥有的一个例子。下面是我想要的(添加宽度与原始图像居中)。

enter image description here

我尝试了以下内容,但是我得到了一个奇怪的裁剪图像:

- (UIImage*)imageWithAddedWhitespaceFromImage:(UIImage *)image {

    CGSize size = CGSizeMake(96, 96);
    UIGraphicsBeginImageContext(size);
    [image drawInRect:CGRectMake(12, 0, size.width + 24, size.height)];

    UIImage *newImage =  UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

1 个答案:

答案 0 :(得分:1)

你几乎就在那里。您需要创建目标大小的图像上下文,然后以原始大小绘制图像。使用**的代码中的注释突出显示了我的更改。

- (UIImage*)imageWithAddedWhitespaceFromImage:(UIImage *)image {
    // ** Create context at target size of 120x96
    CGSize size = CGSizeMake(120, 96);
    // ** Use this API for properly scaled image (instead of UIGraphicsGetImageFromCurrentImageContext)
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    // ** Now draw the image offset by 12px
    [image drawInRect:CGRectMake(12, 0, image.size.width, image.size.height)];    
    UIImage *newImage =  UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}