gpt4 book ai didi

iOS:从 UIBezierPath 创建图像剪切路径

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:46:44 25 4
gpt4 key购买 nike

我正在创建一个允许用户剪切部分图像的应用程序。为了做到这一点,他们将创建一堆 UIBezierPaths 来形成剪切路径。我当前的设置如下:

  • UIImageView 显示他们正在剪切的图像。
  • 上面的 UIImageView 是 UIImageView 的自定义子类执行自定义 drawRect: 显示/更新方法用户正在添加的 UIBezierPaths。
  • 当用户单击“完成”按钮时,将创建一个新的 UIBezierPath 对象,该对象包含用户通过循环访问存储路径的数组并调用 appendPath: 自身创建的所有单独路径。这个新的 UIBezierPath 然后关闭它的路径。

就我所知。我知道 UIBezierPath 有一个 addClip 方法,但我无法从文档中弄清楚如何使用它。

一般来说,我看到的所有裁剪示例都直接使用 Core Graphics 而不是 UIBezierPath 包装器。我意识到 UIBezierPath 有一个 CGPath 属性。那么我应该在剪辑时使用它而不是完整的 UIBezierPath 对象吗?

最佳答案

根据 UIImageView class reference,Apple 表示不要将 UIImageView 子类化.感谢@rob mayoff 指出这一点。

但是,如果您要实现自己的 drawRect,请从您自己的 UIView 子类开始。而且,您在 drawRect 中使用 addClip。您可以使用 UIBezierPath 执行此操作,而无需将其转换为 CGPath。

- (void)drawRect:(CGRect)rect
{
// This assumes the clippingPath and image may be drawn in the current coordinate space.
[[self clippingPath] addClip];
[[self image] drawAtPoint:CGPointZero];
}

如果要放大或缩小以填充边界,则需要缩放图形上下文。 (您也可以将 CGAffineTransform 应用于 clippingPath,但这是永久性的,因此您需要先复制 clippingPath。)

- (void)drawRect:(CGRect)rect
{
// This assumes the clippingPath and image are in the same coordinate space, and scales both to fill the view bounds.
if ([self image])
{
CGSize imageSize = [[self image] size];
CGRect bounds = [self bounds];

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextScaleCTM(context, bounds.size.width/imageSize.width, bounds.size.height/imageSize.height);

[[self clippingPath] addClip];
[[self image] drawAtPoint:CGPointZero];
}
}

这将在每个轴上分别缩放图像。如果您想保留其纵横比,则需要计算出整体缩放比例,并可能对其进行平移,使其居中或以其他方式对齐。

最后,如果您的路径被绘制得很多,所有这一切都相对较慢。您可能会发现将图像存储在 CALayer 中会更快,并且 mask CAShapeLayer包含路径。 除测试外,请勿使用以下方法。您将需要分别缩放图像层和蒙版以使它们对齐。优点是您可以在不渲染底层图像的情况下更改 mask 。

- (void) setImage:(UIImage *)image;
{
// This method should also store the image for later retrieval.
// Putting an image directly into a CALayer will stretch the image to fill the layer.
[[self layer] setContents:(id) [image CGImage]];
}

- (void) setClippingPath:(UIBezierPath *)clippingPath;
{
// This method should also store the clippingPath for later retrieval.
if (![[self layer] mask])
[[self layer] setMask:[CAShapeLayer layer]];

[(CAShapeLayer*) [[self layer] mask] setPath:[clippingPath CGPath]];
}

如果您确实使用图层蒙版进行图像剪辑,则不再需要 drawRect 方法。删除它以提高效率。

关于iOS:从 UIBezierPath 创建图像剪切路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6861005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com