2

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);
holex
  • 23,961
  • 7
  • 62
  • 76
Radek Wilczak
  • 299
  • 5
  • 14
  • I think a little more detail is required. WHen you say 'fill', do you mean fill as in a paint program, or do you mean you just want to paint your image to the context, or do you need to mask your image with your figure? – Gordon Dove Jul 17 '12 at 12:19
  • I have a roundrect figure, and a rect image. First I need stretch image to fit my figure. Secound I want to image corners to be round like in my figure. Do you understand, or I unnecessarily complicate? – Radek Wilczak Jul 17 '12 at 13:19

3 Answers3

3

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();
holex
  • 23,961
  • 7
  • 62
  • 76
0

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.

Gordon Dove
  • 2,537
  • 1
  • 22
  • 23
0

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...

Community
  • 1
  • 1
Peter Pajchl
  • 2,699
  • 21
  • 24
  • [image drawInRect:rect] and CGContextDrawImage(ctx,rect,cgImage) - doesn't work. See my code, which I added to my question. – Radek Wilczak Jul 18 '12 at 07:57
  • the code seems alright; can you verify that the image isn't "null" and also try to draw the image with the figure clipping commented out just to see if the image drawrect does work? – Peter Pajchl Jul 18 '12 at 08:58