6

I would like to clip an image with path. In the book Programming with Quartz there is an example on how to draw a circle clipped by a rectangular path (p.37), and there is also a chapter on image masking with existing image as stencil (Ch.10). But I'm still not sure about how to clip an existing image using path. Is there any example or pointer?

Pedja
  • 186
  • 1
  • 8
huggie
  • 17,587
  • 27
  • 82
  • 139

1 Answers1

13

Here is a sample that should work, it sets the clipping area as a path(this path in my case is an elipse, you could use a rect). Then the image that will be clipped is drawn. Method drawRect: is the one that draws the UIView's context in my case.


- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGMutablePathRef path = CGPathCreateMutable();
//or for e.g. CGPathAddRect(path, NULL, CGRectInset([self bounds], 10, 20));
    CGPathAddEllipseInRect(path, NULL, [self bounds]);
    CGContextAddPath(context, path);
    CGContextClip(context);
    CGPathRelease(path);
    [[UIImage imageNamed:@"GC.png"] drawInRect:[self bounds]];
}
krasnyk
  • 3,458
  • 3
  • 24
  • 20
  • Another question: How do I clip in a different region? I tried to use CGAffineTransform instead of the NULL there. But I end up having the image off-centered relative to the view. – huggie Apr 11 '10 at 10:26
  • 1
    BTW, a look into documentation says drawInRect should scale the image as need fit. In my code it doesn't appear to scale (though this is what I want). But I want several UIView with different regions. – huggie Apr 11 '10 at 10:51