xabaras78
xabaras78

Reputation: 187

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, e.g. just like this one:

enter image description here

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.

Upvotes: 1

Views: 282

Answers (1)

Rychu
Rychu

Reputation: 1020

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.

Upvotes: 1

Related Questions