How to cut a large sprite png into smaller UIImages?

后端 未结 2 1586
暗喜
暗喜 2021-02-15 03:59

For example, the png file is 1200 (h) x 50 (w) pixels, how can I cut the png and loads in 6 UIImages, each 200 (h) x 50 (w). Thanks!

EDIT - thanks

相关标签:
2条回答
  • 2021-02-15 04:47

    Look at CGImageCreateWithImageInRect function. It works with CGImage, but it's easy to convert between that one and UIImage.

    Here's an example (typed from memory, might not compile):

    CGImageRef imageToSplit = [UIImage imageNamed:@"huge.png"].CGImage;
    CGImageRef partOfImageAsCG = CGImageCreateWithImageInRect(imageToSplit, CGRectMake(0, 0, 200, 50));
    CGRelease(imageToSplit);
    UIImage *partOfImage = [UIImage imageWithCGImage:partOfImageAsCG];
    CGImageRelease(partOfImageAsCG);
    
    0 讨论(0)
  • 2021-02-15 04:58

    A reusable method:

    -(UIImage*)ExtractImageOn:(CGPoint)pointExtractedImg ofSize:(CGSize)sizeExtractedImg FromSpriteSheet:(UIImage*)imgSpriteSheet
    {
        UIImage *ExtractedImage;
    
        CGRect rectExtractedImage;
    
        rectExtractedImage=CGRectMake(pointExtractedImg.x,pointExtractedImg.y,sizeExtractedImg.width,sizeExtractedImg.height);
    
        CGImageRef imgRefSpriteSheet=imgSpriteSheet.CGImage;
    
        CGImageRef imgRefExtracted=CGImageCreateWithImageInRect(imgRefSpriteSheet,rectExtractedImage);
    
        ExtractedImage=[UIImage imageWithCGImage:imgRefExtracted];
    
        CGImageRelease(imgRefExtracted);
    
        //CGImageRelease(imgRefSpriteSheet); I have commented it because
        // we should not release the object that we don't own.
        // So why do we release imgRefExtracted alone? because it has 
        // name create in its method so the ownership comes to us so we
        // have to release it.
    
        return ExtractedImage;
    
    }
    

    FYI:

    Even though it has been answered clearly I thought giving it as simple reusable 'Copy-Paste' code snippet would be a lots of help to programmers and I attribute the answer to michal

    0 讨论(0)
提交回复
热议问题