【问题标题】:How to center the CAShapeLayer path in the shape layer如何在形状层中居中 CAShapeLayer 路径
【发布时间】:2020-01-27 20:05:25
【问题描述】:

我创建了一个可以绘制的 DrawView。我创建了一个 UIBezierPath 实例用于绘图。

// This function is called when the user has finished drawing.
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    let shapeLayer = CAShapeLayer()

        //The CAShapeLayer has the same path of the drawing (currentPath is the instance of UIBezierPath).
        shapeLayer.path = currentPath?.cgPath
        shapeLayer.strokeColor = UIColor.black.cgColor
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.lineWidth = 10.0

        //Here I set the shapeLayer on the drawingView (the blue one that you can see in the image)
        drawingView.layer.addSublayer(shapeLayer)
        shapeLayer.position = CGPoint(x: drawingView.layer.bounds.midX, y: drawingView.layer.bounds.midY)
        shapeLayer.backgroundColor = UIColor.blue.cgColor
        shapeLayer.frame = drawingView.layer.bounds
}

问题是路径(例如图像中的数字 3)没有以它的 shapeLayer 为中心。

shapeLayer.path?.boundingBoxOfPath = (289.5, 349.5, 525.0, 129.0)

shapeLayer.frame = (0.0, 0.0, 200.0, 200.0)

shapeLayer.position = (100.0, 100.0)

drawingView.frame = (0.0, 912.0, 200.0, 200.0)

有什么提示吗?谢谢

【问题讨论】:

  • 我设置shapeLayer的frame等于drawingView的frame,但是还是不行
  • drawingView的尺寸和shapeLayer一样
  • 试试shapeLayer.position = drawingView.center 我习惯绘制中心在.zero 的形状。
  • 谢谢,但不幸的是,如果我写了那个代码,shapeLayer 甚至都不会出现
  • @LeoDabus 我已经告诉他了,这只是stackoverflow.com/questions/59937082/…的重复@

标签: swift xcode uiview calayer cgpath


【解决方案1】:

忘记绘图视图,只考虑如何在已知大小的形状层中居中路径。这是一个故意的失败:

    let path = UIBezierPath(ovalIn: CGRect(x: 50, y: 50, width: 50, height: 50))
    let lay = CAShapeLayer()
    lay.frame = CGRect(x: 40, y: 40, width: 200, height: 200)
    lay.backgroundColor = UIColor.red.cgColor
    lay.path = path.cgPath
    self.view.layer.addSublayer(lay)

我们得到这个:

实心圆不在红色形状图层的中心。好的,我们知道原因,因为我们知道创建实心圆的贝塞尔路径。但假设我们知道这一点。我们仍然可以在形状层中将形状居中,如下所示:

    let path = UIBezierPath(ovalIn: CGRect(x: 50, y: 50, width: 50, height: 50))
    let lay = CAShapeLayer()
    lay.frame = CGRect(x: 40, y: 40, width: 200, height: 200)
    lay.backgroundColor = UIColor.red.cgColor

    let cgpath = path.cgPath
    let box = cgpath.boundingBoxOfPath
    let xtarget = (lay.bounds.width - box.width)/2
    let ytarget = (lay.bounds.height - box.height)/2
    let xoffset = xtarget - box.minX
    let yoffset = ytarget - box.minY
    var transform = CGAffineTransform(translationX: xoffset, y: yoffset)
    let cgpath2 = cgpath.copy(using: &transform)
    lay.path = cgpath2

    self.view.layer.addSublayer(lay)

结果:

因此,给定一个 CGPath,并给定一个最终边界已知的形状层,您可以使用该技术在形状层中将路径居中。这些情况非常适合您的用例。

【讨论】:

  • 谢谢马特!你帮了我很多!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 2019-03-22
  • 1970-01-01
  • 2019-10-08
  • 1970-01-01
相关资源
最近更新 更多