• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

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

[复制链接]
菜鸟教程小白 发表于 2022-12-12 18:01:38 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

在将照片剪辑到自定义 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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap