繁体   English   中英

根据多边形裁剪UIImage

[英]clipping a UIImage as per a polygon

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

用户应该能够剪切掉4行之外的任何内容。

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

如果已经有了CGPath,则只需使用CGContextAddPathCGContextClip ,然后可以在该上下文上绘制UIImage。 如果只想显示剪切的图像,则该上下文可以是视图的DrawRect方法中的当前上下文。 如果您实际上想获取裁剪的图像数据,则上下文可能是CGBitmapContext ,如下所示:

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位图进行哪些更改。)

然后将剪切后的图像实际绘制到位图上下文中,您将执行以下操作(我是从内存中编写此代码的,因此可能会有一些错误):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM