If you already have the CGPath, you just have to use CGContextAddPath
and CGContextClip
, and after that you can draw your UIImage on that context.
If you just want to display the clipped image, that context could be the current context in the DrawRect
method of your view.
If you actually want to have the clipped image data, the context would probably be a CGBitmapContext
, something like this:
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
size_t bytesPerPixel = 1;
size_t bytesPerRow = bmpWidth * bytesPerPixel;
size_t bmpDataSize = ( bytesPerRow * bmpHeight);
unsigned char *bmpData = malloc(bmpDataSize);
memset(bmpData, 0, bmpDataSize);
CGContextRef bmpCtx = CGBitmapContextCreate(bmpData, bmpWidth, bmpHeight, 8, bytesPerRow, colorSpace, kCGImageAlphaNone | kCGBitmapByteOrderDefault);
(the code example is for a grey scale bitmap because I had that code ready, but it's not hard to figure out what has to be changed for an RGB bitmap.)
then to actually draw the clipped image to the bitmap context you would do something like this (I'm writing this code from memory, so there might be some mistakes):
// theContext could be
// UIGraphicsGetCurrentContext()
// or the bmpCtx
CGContextAddPath(theContext, yourCGPath);
CGContextClip(theContext);
// not sure you need the translate and scale...
CGContextTranslateCTM(theContext, 0, bmpHeight);
CGContextScaleCTM(theContext, 1, -1);
CGContextDrawImage(theContext, rect, yourUIImage.CGImage);