按照多边形剪切UIImage [英] clipping a UIImage as per a polygon

查看:120
本文介绍了按照多边形剪切UIImage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让我的iphone应用程序的用户通过动态生成的CGPath剪辑UIImage。基本上我在UIImageView上显示一个覆盖的矩形,用户可以移动矩形的4个角来获得4边的多边形。矩形未填充,因此您会在图像上看到四条线。

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 sides. The rectangle is not filled so you see four lines overlaid on an image.

用户应该可以剪掉4行以外的任何内容。

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

非常感谢任何帮助或指示。

Any help or pointers is much appreciated.

推荐答案

如果您已经拥有CGPath,则只需使用 CGContextAddPath CGContextClip ,之后您可以在该上下文中绘制UIImage。
如果您只想显示剪切的图像,那么该上下文可能是您视图的 DrawRect 方法中的当前上下文。
如果你真的想要剪切图像数据,那么上下文可能是 CGBitmapContext ,如下所示:

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

(代码示例是灰度位图,因为我准备好了代码,但并不难找出RGB位图需要更改的内容。)

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

这篇关于按照多边形剪切UIImage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆