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

标签 ios objective-c

如何裁剪包含在随机多边形(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
}

例如,如果我们对您的问题进行截图(我找不到任何其他图片!)

enter image description here

并使用以下代码....

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

这将是输出...

enter image description here

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

关于ios - 包含在 4 边(非矩形)多边形中的裁剪图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35608928/

相关文章:

ios - 如何从 NSMutableArray 中删除空字符串数据

ios - 以编程方式将新项目添加到 plist

ios - 如何从地址簿中选择一个联系人 ios8

objective-c - 为什么 Xcode 编译器不会针对指针类型安全自动出错?

javascript - 如何计算图像周围的计算透明区域?

ios - 我可以安全地假设 Documents 目录总是存在于 iOS 上吗?

ios - 在另一个 UIView 之上添加带有自己的 UIViewController 的 UIView

ios - 是否存在将我的 cordova 应用程序发布到 IOS 的服务?

ios - AVAudioPlayer在播放时崩溃

objective-c - 在 Cocoa Touch 中读取 .ppt (MS PowerPoint) 文件