Radek Wilczak
Radek Wilczak

Reputation: 299

How to fill CGContext with UIImage?

I subclass UIView, I overwrite -drawRect:, I draw a figure by CGContext. And now I want to fill this figure with UIImage. Any idea how to do it?

EDIT:

My Code from -drawRect:

CGContextBeginPath(ctx);
//here I draw my figure
CGContextClosePath(ctx);
CGContextClip(ctx);

//this doesn't work
UIImage * image = [UIImage imageNamed:@"blackbackground.jgp"];
[image drawInRect:rect];

//this neither
CGImageRef cgImage = image.CGImage;
CGContextDrawImage(ctx, rect,  cgImage);

Upvotes: 2

Views: 9937

Answers (3)

Gordon Dove
Gordon Dove

Reputation: 2577

Assuming that you mean that you want to draw the image 'inside' your figure, the easiest way would be to create a cgpath of your figure, make sure the path is closed, and then CGContextClipToPath( context, path)

ADDED

I've just tested your code, and as Peter said, it should work. I would recommend testing your path ( set the stroke colour and the stroke path), and trying the image without the mask to work out where the problem is.

Upvotes: 0

holex
holex

Reputation: 24041

the proper way to draw an image to the CGContext is this:

UIImage *_originalImage = // your image

UIGraphicsBeginImageContext(_originalImage.size);
CGContextRef _context = UIGraphicsGetCurrentContext(); // here you don't need this reference for the context but if you want to use in the future for drawing anything else on the context you could get it for it
[_originalImage drawInRect:CGRectMake(0.f, 0.f, _originalImage.size.width, _originalImage.size.height)];

UIImage *_newImage = UIGraphicsGetImageFromCurrentImageContext();    
UIGraphicsEndImageContext();

Upvotes: 3

Peter Pajchl
Peter Pajchl

Reputation: 2709

What you need is to clip the context with the figure's path and then draw your image. Have a look at this answer which explains how to do the first part How do I add a gradient to the text of a UILabel, but not the background? and once you have the context clipped simply get the UIImage and call one of the drawing functions such as drawInRect...

Upvotes: 0

Related Questions