如何合并两个图像用于视网膜显示(@ 2x)?

Man*_*nni 0 iphone uiimage ios retina-display

我想补充一个UIImageUIImageViewUITableViewCell内部UITableViewController.这很好用:

cell.imageView.image = [UIImage imageNamed:@"myImage.png"];
Run Code Online (Sandbox Code Playgroud)

但现在,我想合并两个图像并使用我在这里找到的代码:

UIImage *mergedImage = [MyUtils mergeImage:@"myBackImage.png" withImage:@"myFrontImage.png"];
Run Code Online (Sandbox Code Playgroud)

这适用于旧的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上合并(WORKS NOT)
- 图像宽度:56.0
- 图像高度:58.0
- 图像比例:1.0

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

如何正确合并两个图像以获得2.0的图像?


附录:我用于合并两个图像的代码(从这里开始)

+ (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;
}
Run Code Online (Sandbox Code Playgroud)

rob*_*off 5

您需要根据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;
Run Code Online (Sandbox Code Playgroud)