如何裁剪包含在随机多边形(4 边但不是矩形)内的图像部分。只是想知道遵循哪种方法而不是代码。
最佳答案
您可以在 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
}
例如,如果我们对您的问题进行截图(我找不到任何其他图片!)
并使用以下代码....
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];
这将是输出...
如果您要定期裁剪图像,您甚至可以将其添加到 UIImage
类别。
关于ios - 包含在 4 边(非矩形)多边形中的裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35608928/