开发者

clipping a UIImage as per a polygon

开发者 https://www.devze.com 2023-01-15 12:37 出处:网络
How can I let the user of my iphone app to clip a UIImage by a dynamically generated CGPath. Basically I display a rectangle overlaid on a UIImageView and the user can move the 4 corners of the rectan

How can I let the user of my iphone app to clip a UIImage by a dynamically generated CGPath. Basically I display a rectangle overlaid on a UIImageView and the user can move the 4 corners of the rectangle to get a polygon with 4 side开发者_Go百科s. The rectangle is not filled so you see four lines overlaid on an image.

The user should be able to clip out whatever is outside the 4 lines.

Any help or pointers is much appreciated.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号