gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:42:41 27 4
gpt4 key购买 nike

我想在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com