【问题标题】:Create new UIImage from freehand drawn line over UIImage - Swift从 UIImage 上的手绘线创建新的 UIImage - Swift
【发布时间】:2019-05-17 07:59:51
【问题描述】:

这是我的第一个问题,如果我有任何不清楚的地方,请原谅。

我希望能够从现有 UIImage1 上的手绘形状的内容创建新的 UIImage2,以显示在现有 UIImage1 上。

一个视觉示例:UIImage1 是一张城市天际线的照片。用户应该能够在摩天大楼周围绘制轮廓并创建一个新的 UIImage2,该 UIImage2 将堆叠显示在 UIImage1 上,并能够编辑 UIImage 2(大小、颜色等)。

在 UIImage 上画线并不太难,但我还没有弄清楚如何在徒手绘制的形状中捕获 UIImage 的内容,创建一个单独的 UIImage。

非常感谢任何帮助。

【问题讨论】:

  • 嘿 Rob,感谢您要求澄清。捕获的图像应包含原始图像在绘制形状内的部分。
  • 感谢您的提示。我将深入研究这些功能。欣赏!
  • 你是个圣人。感谢您为我指明正确的方向。

标签: swift uiimage image-editing


【解决方案1】:

如果您想从蒙版路径创建图像,您可以:

  • 从用户手势创建UIBezierPath
  • 使用该贝塞尔路径作为图像视图上的CAShapeLayer
  • 完成用户手势后,移除该形状图层,但创建新的形状图层并将其用作蒙版;和
  • 使用 UIGraphicsImageRendererdrawHierarchy 从蒙版图像视图创建图像,以渲染图像中应捕获的任何内容。

例如:

class ViewController: UIViewController {

    @IBOutlet weak var imageView: UIImageView!
    
    private var path: UIBezierPath?
    private var strokeLayer: CAShapeLayer?
    
    @IBAction func didHandlePan(_ gesture: UIPanGestureRecognizer) {
        let location = gesture.location(in: imageView)
        
        switch gesture.state {
        case .began:
            path = UIBezierPath()
            path?.move(to: location)
            strokeLayer = CAShapeLayer()
            imageView.layer.addSublayer(strokeLayer!)
            strokeLayer?.strokeColor = #colorLiteral(red: 1, green: 0.1491314173, blue: 0, alpha: 1).cgColor
            strokeLayer?.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
            strokeLayer?.lineWidth = 5
            strokeLayer?.path = path?.cgPath
            
        case .changed:
            path?.addLine(to: location)
            strokeLayer?.path = path?.cgPath
            
        case .cancelled, .ended:
            // remove stroke from image view
            
            strokeLayer?.removeFromSuperlayer()
            strokeLayer = nil

            // mask the image view
            
            let mask = CAShapeLayer()
            mask.fillColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor
            mask.strokeColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0).cgColor
            mask.lineWidth = 0
            mask.path = path?.cgPath
            imageView.layer.mask = mask

            // get cropped image

            let image = imageView?.snapshot
            imageView.layer.mask = nil

            // perhaps use that image?

            imageView.image = image

        default: break
        }
    }        
}

顺便说一句,要从视图(蒙面或其他方式)创建UIImage,您可以使用:

extension UIView {
    var snapshot: UIImage {
        UIGraphicsImageRenderer(bounds: bounds).image { _ in
            drawHierarchy(in: bounds, afterScreenUpdates: true)
        }
    }
}

这会产生如下内容:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    相关资源
    最近更新 更多