如何使用CGImageCreateWithImageInRect for iPhone 4(HD)?

Vic*_*tor 19 iphone core-graphics high-resolution iphone-4

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

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

iPhone 4自动加载图像的高清版本(sprite@2x.png)而不是sprite.png.原始图像具有比例2,但是得到的图像具有比例1和错误的大小.

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

我已阅读此文档,但关于使用CGImageCreateWithImageInRect这里什么也没说.

Jos*_*erg 32

从我可以告诉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将源图像rect相乘. (3认同)
  • 谢谢.这节省了我的时间:-)另外:我需要将比例因子乘以我的裁剪矩形尺寸,以使结果看起来正确. (2认同)

Dan*_*iel 14

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

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