How use CGImageCreateWithImageInRect for iPhone 4 (HD)?

試著忘記壹切 提交于 2019-11-27 12:19:03

问题


I use the following code to getting images from the sprite. And it works fine everywhere except the iPhone 4 (HD version).

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

The iPhone 4 automatically load HD version of the image (sprite@2x.png) instead sprite.png. The original image has a scale 2, but the resulting image has a scale 1 and wrong size.

How to handle this behavior taking into account the different scales for iPhone 3G[s] and the iPhone 4?

I have read this document, but about the use CGImageCreateWithImageInRect here says nothing.


回答1:


From what I can tell the CGImageCreateWithImageInRect will do the right thing. What you need to change is the UIImage initilization

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

Change it to [UIImage imageWithCGImage:image scale:self.scale orientation:self. imageOrientation] and it should work just fine. (this is assuming this is a category on UIImage which it looks like it is)




回答2:


You should multiply the crop rect by the image scale. From my experience, it's unnecessary to use any different image initilization.

- (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;
}


来源:https://stackoverflow.com/questions/3150364/how-use-cgimagecreatewithimageinrect-for-iphone-4-hd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!