views:

38

answers:

1

I have created a CGBitmapContext of 256 x 256 and I have a CGImageRef that I want to draw into this context. My goal is to crop the image (and ultimately create tiles of an image), but if I use CGContextDrawImage, Core Graphics scales the image to fit the context.

So the question is, how do I make sure that only a portion of the CGImageRef is drawn into the CGBitmapContext (no scaling)?

+2  A: 

CGContextDrawImage takes a CGRect parameter. It sounds like you are passing the bounds of your context. Instead, try passing the bounds of the image, offset appropriately to draw the desired part of it.

JWWalker
For example, to draw a 32x32 chunk of the source image starting at (10, 20), you'd do: `CGContextDrawImage(theContext, CGRectMake(10, 20, 32, 32), theImage);`
Jonathan Grynspan
@Jonathan Grynspan: no, that would scale the image. Suppose the source image is 1024x1024, and you want the lower right 256x256 corner to fill the context. Then I think you'd say `CGContextDrawImage(context, CGRectMake( -768, 0, 1024, 1024 ), theImage)`.
JWWalker
Erm... yeah. What was I thinking? I use Quartz every day! To crop, you need to first set the clipping area of the context with `CGContextClipToRect()`.
Jonathan Grynspan
The question wasn't completely clear, but my interpretation was that bare_nature wants to clip to the bounds of the context, in which case a clipping area wouldn't be needed.
JWWalker
Thanks for the comments. This was exactly what I did, but I made a beginners mistake by using the -size of the NSImage to determine its width and height and this does not necessarily give you the width and height in pixels. All is working well now. Also, clipping is not necessary in my case.
bare_nature