菜鸟教程小白 发表于 2022-12-12 18:01:38

ios - 将 UIImage 裁剪为自定义 UIBezierPath,同时保留图像质量


                                            <p><p>在将照片剪辑到自定义 UIBezierPath 时遇到问题。它不会显示路径内的区域,而是显示照片的另一部分(大小和位置与应有的位置不同,但仍与绘制的形状相同)。请注意,我还想保留原始照片的全部质量。</p>

<p>我在下面添加了照片和说明,以更深入地解释我的问题。如果有人能给我另一种方法来做这样的事情,我很乐意重新开始。</p>

<p> <img src="/image/dv7eL.png" alt="The user draws a UIBezierPath with his finger"/>
上图是一个 UIImageView 中的 UIImage 的示意图,都在一个 UIView 中,显示 UIBezierPath 的 CAShapeLayer 是它的一个子层。对于这个例子,假设红色的路径是由用户绘制的。</p>

<p> <img src="/image/hLtAc.png" alt="Visualization"/>
此图中是 CAShapeLayer 和使用原始图像大小创建的图形上下文。我将如何剪辑上下文以产生以下结果(请原谅它的困惑)?</p>

<p> <img src="/image/k0BQM.png" alt="The result"/>
这就是我希望在一切都说完之后产生的结果。请注意,我希望它的尺寸​​/质量仍与原件相同。</p>

<p>以下是我的代码的一些相关部分:</p>

<p>这会将图像剪辑到路径</p>

<pre><code>-(UIImage *)maskImageToPath:(UIBezierPath *)path {
    // Precondition: the path exists and is closed
    assert(path != nil);


    // Mask the image, keeping original size
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0);

    ;
    ;

    // Extract the image
    UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return maskedImage;
}
</code></pre>

<p>这会向 UIBezierPath 添加点</p>

<pre><code> - (void)drawClippingLine:(UIPanGestureRecognizer *)sender {
    CGPoint nextPoint = ;

    // If UIBezierPath *clippingPath is nil, initialize it.
    // Otherwise, add another point to it.
    if(!clippingPath) {
      clippingPath = ;
      ;
    }
    else {
      ;
    }

    UIGraphicsBeginImageContext(_image.size);
    ;
    UIGraphicsEndImageContext();


}
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>由于 <code>UIImage</code> 被缩放以适合 <code>UIImageView</code> 的内部,因此您得到了不正确的裁剪。基本上这意味着您必须将 <code>UIBezierPath</code> 坐标转换为 <code>UIImage</code> 内的正确坐标。最简单的方法是使用 <code>UIImageView</code> 类别,它将点从一个 View (在本例中为 <code>UIBezierPath</code>,即使它不是真正的 View )转换为<code>UIImageView</code> 中的正确点。
您可以查看此类类别的示例 <a href="https://github.com/nubbel/UIImageView-GeometryConversion" rel="noreferrer noopener nofollow">here</a> .更具体地说,您需要使用该类别中的 <code>convertPointFromView:</code> 方法来转换 <code>UIBezierPath</code> 中的每个点。
(抱歉没有写完整的代码,我在手机上打字)</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 将 UIImage 裁剪为自定义 UIBezierPath,同时保留图像质量,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/21072009/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/21072009/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 将 UIImage 裁剪为自定义 UIBezierPath,同时保留图像质量