OGeek|极客世界-中国程序员成长平台

标题: ios - 将 UIImage 裁剪为自定义 UIBezierPath,同时保留图像质量 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 18:01
标题: ios - 将 UIImage 裁剪为自定义 UIBezierPath,同时保留图像质量

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

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

The user draws a UIBezierPath with his finger 上图是一个 UIImageView 中的 UIImage 的示意图,都在一个 UIView 中,显示 UIBezierPath 的 CAShapeLayer 是它的一个子层。对于这个例子,假设红色的路径是由用户绘制的。

Visualization 此图中是 CAShapeLayer 和使用原始图像大小创建的图形上下文。我将如何剪辑上下文以产生以下结果(请原谅它的困惑)?

The result 这就是我希望在一切都说完之后产生的结果。请注意,我希望它的尺寸​​/质量仍与原件相同。

以下是我的代码的一些相关部分:

这会将图像剪辑到路径

-(UIImage *)maskImageToPathUIBezierPath *)path {
    // Precondition: the path exists and is closed
    assert(path != nil);


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

    [path addClip];
    [self drawAtPoint:CGPointZero];

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

    return maskedImage;
}

这会向 UIBezierPath 添加点

 - (void)drawClippingLineUIPanGestureRecognizer *)sender {
    CGPoint nextPoint = [sender locationInView:self];

    // If UIBezierPath *clippingPath is nil, initialize it.
    // Otherwise, add another point to it.
    if(!clippingPath) {
        clippingPath = [UIBezierPath bezierPath];
        [clippingPath moveToPoint:nextPoint];
    }
    else {
        [clippingPath addLineToPoint:nextPoint];
    }

    UIGraphicsBeginImageContext(_image.size);
    [clippingPath stroke];
    UIGraphicsEndImageContext();


}



Best Answer-推荐答案


由于 UIImage 被缩放以适合 UIImageView 的内部,因此您得到了不正确的裁剪。基本上这意味着您必须将 UIBezierPath 坐标转换为 UIImage 内的正确坐标。最简单的方法是使用 UIImageView 类别,它将点从一个 View (在本例中为 UIBezierPath,即使它不是真正的 View )转换为UIImageView 中的正确点。 您可以查看此类类别的示例 here .更具体地说,您需要使用该类别中的 convertPointFromView: 方法来转换 UIBezierPath 中的每个点。 (抱歉没有写完整的代码,我在手机上打字)

关于ios - 将 UIImage 裁剪为自定义 UIBezierPath,同时保留图像质量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21072009/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4