裁剪图像包含在4面(非矩形)多边形中 [英] Crop image enclosed in a 4 sided (not rectangle) polygon

查看:101
本文介绍了裁剪图像包含在4面(非矩形)多边形中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何裁剪随机多边形(四边但不是矩形)内的图像部分。只是想知道要遵循哪种方法而不是代码。

How to crop image portion that is enclosed inside a random polygon (4 sided but not rectangle). Just wanted to know which method to follow not the code.

推荐答案

您可以在Core Graphics中轻松完成此任务。



您只需要创建一个新的图像上下文,添加上下文的路径,然后将上下文裁剪到路径。然后,您可以在此处绘制图像并获得裁剪后的图像。

You can do this easily in Core Graphics.

You just need to create a new image context, add the path to the context, then crop the context to the path. You can then draw your image in this and get out a cropped image.

-(UIImage*) cropImage:(UIImage*)image withPath:(UIBezierPath*)path { // where the UIBezierPath is defined in the UIKit coordinate system (0,0) is top left

    CGRect r = CGPathGetBoundingBox(path.CGPath); // the rect to draw our image in (minimum rect that the path occupies).

    UIGraphicsBeginImageContextWithOptions(r.size, NO, image.scale); // begin image context, with transparency & the scale of the image.
    CGContextRef ctx = UIGraphicsGetCurrentContext();

    CGContextTranslateCTM(ctx, -r.origin.x, -r.origin.y); // translate context so that when we add the path, it starts at (0,0).

    CGContextAddPath(ctx, path.CGPath); // add path.
    CGContextClip(ctx); // clip any future drawing to the path region.

    [image drawInRect:(CGRect){CGPointZero, image.size}]; // draw image

    UIImage* i = UIGraphicsGetImageFromCurrentImageContext(); // get image from context
    UIGraphicsEndImageContext(); // clean up and finish context

    return i; // return image
}

例如,如果我们截取您的问题的屏幕截图(我找不到任何其他图片!)

For example, if we take a screenshot of your question (I couldn't find any other images lying about!)

并使用以下代码....

and use the following code....

UIImage* i = [UIImage imageNamed:@"3.png"];

UIBezierPath* p = [UIBezierPath bezierPath];
[p moveToPoint:CGPointMake(0, 0)];
[p addLineToPoint:CGPointMake(1500, 500)];
[p addLineToPoint:CGPointMake(500, 1200)];

UIImage* i1 = [self cropImage:i withPath:p];

这将是输出......

This would be the output...

您甚至可以将其添加到 UIImage 类别,如果您要定期裁剪图像。

You could even add this to a UIImage category if you're going to be cropping images regularly.

这篇关于裁剪图像包含在4面(非矩形)多边形中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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