【问题标题】:How use CGImageCreateWithImageInRect for iPhone 4 (HD)?如何为 iPhone 4 (HD) 使用 CGImageCreateWithImageInRect?
【发布时间】:2010-06-30 14:46:01
【问题描述】:

我使用以下代码从精灵中获取图像。除了 iPhone 4(高清版)之外,它在任何地方都可以正常工作。

- (UIImage *)croppedImage:(CGRect)rect {
    CGImageRef image = CGImageCreateWithImageInRect([self CGImage], rect);
    UIImage *result = [UIImage imageWithCGImage:image];
    CGImageRelease(image);
    return result;
}

iPhone 4 会自动加载高清版图像 (sprite@2x.png) 而不是 sprite.png。原始图像的比例为 2,但生成的图像的比例为 1,尺寸错误。

考虑到 iPhone 3G[s] 和 iPhone 4 的不同规模,如何处理这种行为?

我已经阅读了这个document,但是关于使用 CGImageCreateWithImageInRect 这里什么也没说。

【问题讨论】:

  • 如果你能看看我的回答,我会很感兴趣。我确信有更好的方法来实现我们想要的。但在我看来,这里的正确答案并不重要。你能用上面的代码+带有比例的矩形翻译,看看它是否有效?

标签: iphone core-graphics iphone-4


【解决方案1】:

据我所知,CGImageCreateWithImageInRect 会做正确的事。你需要改变的是 UIImage 初始化

http://developer.apple.com/iphone/library/documentation/uikit/reference/UIImage_Class/Reference/Reference.html#//apple_ref/occ/clm/UIImage/imageWithCGImage:scale:orientation:

将其更改为[UIImage imageWithCGImage:image scale:self.scale orientation:self. imageOrientation],它应该可以正常工作。 (这是假设这是 UIImage 上的一个类别,看起来就是这样)

【讨论】:

  • 谢谢。我错过了这个功能。另外,我需要将源图像矩形乘以 self.scale。
  • 谢谢。这节省了我几个小时 :-) 另外:我需要将比例因子乘以我的裁剪矩形尺寸以使结果看起来正确。
  • 是的,将矩形相乘似乎是一种奇怪的解决方法,因为它应该只是“做正确的事”。关键是规模,不是答案中提到的这种方法。
  • 我认为在调用 CGImageCreateWithImageInRect 之前你需要 2x 矩形。
【解决方案2】:

您应该将裁剪矩形乘以图像比例。根据我的经验,没有必要使用任何不同的图像初始化。

- (UIImage *)_cropImage:(UIImage *)image withRect:(CGRect)cropRect
{
    cropRect = CGRectMake(cropRect.origin.x * image.scale,
                          cropRect.origin.y * image.scale,
                          cropRect.size.width * image.scale,
                          cropRect.size.height * image.scale);

    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);

    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];

    CGImageRelease(imageRef);

    return croppedImage;
}

【讨论】:

  • 我发现这行得通,而上面的行不通。可能苹果改变了实现......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-10
  • 1970-01-01
  • 2011-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多