Question

I have developed an application of tile game for iPhone 3. In which I took an image from my resource and divided it into number of tiles using CGImageCreateWithImageInRect ( originalImage.CGImage, frame ); function.

It works great on all iPhones but now I want it to work on Retina Displays also.

So as per this link I have taken anothe image with its size double the current images size and rename it by adding suffix @2x. But the problem is it takes the upper half part of the retina display image only. I think thats because of the frame I have set while using CGImageCreateWithImageInRect. So What shall be done in respect to make this work.

Any kind of help will be really appreciated.

Thanks in advance...

Was it helpful?

Solution

The problem is likely that the @2x image scale is only automatically set up properly for certain initializers of UIImage... Try loading your UIImages using code like this from Tasty Pixel. The entry at that link talks more about this issue.

Using the UIImage+TPAdditions category from the link, you'll implement it like so (after making sure that the images and their @2x counterparts are in your project):

NSString *baseImagePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *myImagePath = [baseImagePath stringByAppendingPathComponent:@"myImage.png"]; // note no need to add @2x.png here
UIImage *myImage = [UIImage imageWithContentsOfResolutionIndependentFile:myImagePath];

Then you should be able to use CGImageCreateWithImageInRect(myImage.CGImage, frame);

OTHER TIPS

Here's how I got it to work in an app I did:

//this is a method that takes a UIImage and slices it into 16 tiles (GridSize * GridSize)
#define GridSize 4
- (void) sliceImage:(UIImage *)image {
    CGSize imageSize = [image size];
    CGSize square = CGSizeMake(imageSize.width/GridSize, imageSize.height/GridSize);

    CGFloat scaleMultiplier = [image scale];

    square.width *= scaleMultiplier;
    square.height *= scaleMultiplier;

    CGFloat scale = ([self frame].size.width/GridSize)/square.width;

    CGImageRef source = [image CGImage];
    if (source != NULL) {
        for (int r = 0; r < GridSize; ++r) {
            for (int c = 0; c < GridSize; ++c) {
                CGRect slice = CGRectMake(c*square.width, r*square.height, square.width, square.height);
                CGImageRef sliceImage = CGImageCreateWithImageInRect(source, slice);
                if (sliceImage) {
                    //we have a tile (as a CGImageRef) from the source image
                    //do something with it
                    CFRelease(sliceImage);
                }
            }
        }
    }
}

The trick is using the -[UIImage scale] property to figure out how big of a rect you should be slicing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top