ios - 向 UIImage 添加宽度?

标签 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;
}

最佳答案

你快到了。您需要创建目标尺寸的图像上下文,然后以原始尺寸绘制图像。代码中的注释 ** 突出显示我的更改。

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

关于ios - 向 UIImage 添加宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37602300/

相关文章:

ios - 来自 AVCaptureVideoDataOutput 的 CMSampleBuffer 意外地发现 nil

ios - 如何在 swift 更改(Firebase)时接收/更新数据

ios - 在 viewDidLoad 中调用 Web 服务导致屏幕挂起 iOS

ios - 如何在 swift 中实现 uiviewController 的自定义初始化方法

xcode - 如何快速更改按钮图像?

ios - sd_setImageWithUrl 第一次没有显示图像

ios - Twitter SLRequest performRequestWithHandler-无法准备URL请求

iphone - UIImageview 在 iOS7 中没有动画,但在 iOS6 中运行良好

ios - 如何将完整数据加载到PFQueryTableViewController中并实现objectDidLoad?

objective-c - 从 plist 读取数组时是否保证 NSArray/NSMutableArray 顺序?