我有96x96的图像,我想为它添加额外的宽度,以便新图像为120 x 96,图像居中。
以上是我所拥有的一个例子。下面是我想要的(添加宽度与原始图像居中)。
我尝试了以下内容,但是我得到了一个奇怪的裁剪图像:
- (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;
}
答案 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;
}