【问题标题】:How to merge two images for retina display (@2x)?如何合并两个图像以进行视网膜显示(@2x)?
【发布时间】:2012-02-16 09:15:32
【问题描述】:

我想在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;
}

【问题讨论】:

    标签: iphone ios uiimage retina-display


    【解决方案1】:

    您需要根据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;
    

    【讨论】:

    • @rob mayoff 嘿,再见,这也适用于我,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多