裁剪图像包含在4面(非矩形)多边形中

Ama*_*man 2 objective-c ios

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

Ham*_*ish 6

您可以在Core Graphics中轻松完成此操作.

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

-(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
}
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

并使用以下代码....

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];
Run Code Online (Sandbox Code Playgroud)

这将是输出......

在此输入图像描述

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