iphone - 如何合并两张图片用于视网膜显示(@2x)?

标签 iphone ios uiimage retina-display

我想在 UITableViewController 内的 UITableViewCellUIImageView 中添加一个 UIImage。这很好用:

cell.imageView.image = [UIImage imageNamed:@"myImage.png"];

但是现在,我想合并两个图像并使用代码 I've found here :

UIImage *mergedImage = [MyUtils mergeImage:@"myBackImage.png" withImage:@"myFrontImage.png"];

这在旧 iPhone (320x480) 上效果很好,但在视网膜显示屏上效果不佳。在我的项目中,每个图像都有“@2x”版本。我分析代码并对问题有解释。

a) 在 iPhone 3 上不合并 (WORKS)
- 图片宽度:28.0
- 图片高度:29.0
- 图像比例:1.0

b) 在 iPhone 3 上合并 (WORKS)
- 图片宽度:28.0
- 图片高度:29.0
- 图像比例:1.0

c) 在 iPhone 4 上不合并 (WORKS)
- 图片宽度:28.0
- 图片高度:29.0
- 图像比例:2.0

d) 在 iPhone 4 上合并(不工作)
- 图片宽度:56.0
- 图片高度:58.0
- 图像比例:1.0

如您所见,合并将“28.0/29.0/2.0”图像转换为“56.0/58.0/1.0”图像。并且此图像在视网膜显示器上显示得很大。

如何正确合并两张图片以获得比例为 2.0 的图片?


附录:我用于合并两个图像的代码 (from here)

+ (UIImage*)mergeImage:(UIImage*)first withImage:(UIImage*)second
{
 // get size of the first image
 CGImageRef firstImageRef = first.CGImage;
 CGFloat firstWidth = CGImageGetWidth(firstImageRef);
 CGFloat firstHeight = CGImageGetHeight(firstImageRef);

 // get size of the second image
 CGImageRef secondImageRef = second.CGImage;
 CGFloat secondWidth = CGImageGetWidth(secondImageRef);
 CGFloat secondHeight = CGImageGetHeight(secondImageRef);

 // build merged size
 CGSize mergedSize = CGSizeMake(MAX(firstWidth, secondWidth), MAX(firstHeight, secondHeight));

 // capture image context ref
 UIGraphicsBeginImageContext(mergedSize);

 //Draw images onto the context
 [first drawInRect:CGRectMake(0, 0, firstWidth, firstHeight)];
 [second drawInRect:CGRectMake(0, 0, secondWidth, secondHeight)];

 // assign context to new UIImage
 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

 // end context
 UIGraphicsEndImageContext();

 return newImage;
}

最佳答案

您需要根据 UIImage 大小而不是 CGImage 大小来计算合并后的大小,并且您需要使用图像的最大比例来创建图形上下文.试试这个:

CGSize firstSize = first.size;
CGSize secondSize = second.size;
CGSize mergedSize = CGSizeMake(MAX(firstSize.width, secondSize.width),
    MAX(firstSize.height, secondSize.height));
CGFloat mergedScale = MAX(first.scale, second.scale);

UIGraphicsBeginImageContextWithOptions(mergedSize, NO, mergedScale);

[first drawAtPoint:CGPointZero];
[second drawAtPoint:CGPointZero];

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

关于iphone - 如何合并两张图片用于视网膜显示(@2x)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9308401/

相关文章:

iphone - Core Data Cocoa 错误 1570。无法保存多个实体对象

ios - iOS 应用程序的视频启动画面

javascript - Cordova /电话间隙 : AJAX calls not working on iOS device

ios - 在不压缩的情况下调整 UIImage 的大小

ios - 在 for 循环中将 PFFile 数组转换为 UIImage 返回空数组 Swift

ios8 UIImage imageNamed : crash

iphone - 如何创建自定义 UIWebView 页面

ios - 重置dispatch_once是否安全(不涉及线程)

ios - 上传到 iTunes 错误 : "app references non-public symbols"

ios - 捏合缩放 UIImage