简体   繁体   中英

How to create transparent areas in a UIImage?

i'm creating a game for iPhone, with xcode. I have a starting image, from which i'd like to have a second image with some (four) transparent areas in it, eg just like this one:

在此处输入图片说明

The problem is that i don't know how to achieve it; have i to handle the original image and to cut the areas from it? or have i to create a new image where i put only the visible parts from the original one? Any suggestion or snippet would be really appreciated.

Well, I'd do it by creating custom UIView subclass and using its drawRect method to draw the portion. Fo example:

-(void)drawRect:(

CGRect)rect
{
    [super drawRect:rect];

    CGContextRef ctx = UIGraphicsGetCurrentContext(); // get drawing context

    CGContextSaveGState(ctx); //remember current state
    CGContextClipToRect(ctx, CGRectMake(0, 0, 100, 100)); //set clipping
    CGContextDrawImage(ctx, CGRectMake(0, 0, img.size.width, img.size.height), img.CGImage);
    CGContextRestoreGState(ctx); //restore state, so the previous clipping will be canceled

    CGContextSaveGState(ctx);
    CGContextClipToRect(ctx, CGRectMake(100, 100, 100, 100));
    CGContextDrawImage(ctx, CGRectMake(0, 0, img.size.width, img.size.height), img.CGImage);
    CGContextRestoreGState(ctx);
}

This will draw two small rects. In this code img is an UIImage.

However, this is the easiest way to do this, not the most efficient - it requres to redraw for each portion. You might want to check CGContextClipToRects and CGContextClip functions, to make it more efficient and flexible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM