【问题标题】:Clipping an image with a given path [duplicate]使用给定路径剪切图像[重复]
【发布时间】:2016-04-09 00:41:35
【问题描述】:

有没有一种标准的方法可以根据给定的路径(CGPath)来剪辑一大块图像(UIImage)? (路径是椭圆、星形、多边形……) 我现在的问题与这个有关: AVCaptureStillImageOutput area selection 暂时没有答案,我仍然没有解决方案。

【问题讨论】:

标签: ios swift uiimage cgpath image-clipping


【解决方案1】:

使用此代码

CGPathRef path = CGPathCreateWithEllipseInRect(CGRectMake(50.0,50.0,300.0,200.0), nil);

UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextSetStrokeColorWithColor(UIGraphicsGetCurrentContext(), [UIColor blackColor].CGColor);
CGContextAddPath(UIGraphicsGetCurrentContext(), path);
CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), [UIColor redColor].CGColor);
CGContextDrawPath(UIGraphicsGetCurrentContext(), kCGPathFillStroke);
UIImage *maskImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

UIImage *originalImage = [UIImage imageNamed:@"image"];
UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextClipToMask(UIGraphicsGetCurrentContext(), CGRectMake(0.0,0.0,300.0,200.0), maskImage.CGImage);
[captureImage drawAtPoint:CGPointZero];
UIImage *clippedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

【讨论】:

  • 谢谢!我正在尝试使用这个不错的代码,但面临一些问题。生成的图像方向错误,并且存在缩放问题,蒙版被缩小。我必须修复一些细节,但我认为基本想法很好,我想让它发挥作用。
  • 是的,你是对的。您必须考虑方向和比例因子。
  • 是的,这似乎比我最初想象的要困难。我或多或少地解决了剪辑方面的问题,但是我无法按照我想要的方式将不同的剪辑保存为 PNG 文件。实际上我什至做了一个特殊的应用程序来测试这方面的事情,并附上一个寻求帮助的帖子:stackoverflow.com/questions/34646982/…
  • 这可能对你有帮助stackoverflow.com/questions/7645454/…
  • Swift 的答案展示了如何使用 UIBezierPath 进行剪辑并获取具有 PNG 格式的 alpha 通道的图像。它还展示了如何将剪辑保存到相机胶卷以及如何将其放入粘贴板。 stackoverflow.com/questions/49853122/…
猜你喜欢
  • 2016-08-01
  • 2017-06-04
  • 1970-01-01
  • 1970-01-01
  • 2011-10-15
  • 2014-02-09
  • 1970-01-01
  • 2015-08-11
  • 1970-01-01
相关资源
最近更新 更多