【问题标题】:How to position CAShapeLayer in a UIView如何在 UIView 中定位 CAShapeLayer
【发布时间】:2020-01-27 18:45:46
【问题描述】:

我在 Stack Overflow 上看到了很多答案,但没有一个对我有帮助。 我创建了一个可以绘制的 DrawView。我创建了一个UIBezierPath 的实例用于绘图。 我想将我的绘图转移到一个小视图(图像上的红色视图)。我就是这样做的:

// This function is called when the user has finished to draw.

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

    //drawingView is the red view where I want to see my drawing in the center. This line of code doesn't work like I expect because the drawing doesn't appear in the center of the view.
    shapeLayer.position = CGPoint(x: drawingView.frame.midX, y: drawingView.frame.midY)

    //I add the shapeLayer to the drawingView.
    drawingView.layer.addSublayer(shapeLayer)
}

这是应用程序的图片:

有什么提示吗?谢谢。

【问题讨论】:

    标签: swift xcode uiview calayer cgpath


    【解决方案1】:

    问题出在这一行:

    shapeLayer.position = CGPoint(x: drawingView.frame.midX, y: drawingView.frame.midY)
    

    无论你在哪里说drawingView.frame,都说drawingView.bounds。

    (其实你应该说drawingView.layer.bounds,而不是简单的drawingView.bounds,但恰好它们是同一个东西。)

    但是,还有第二个问题,即您的形状图层没有大小。因此它的position 与它的左上角相同。出于这个原因,您最好将它集中在它的超层中,只需说一下

    shapeLayer.frame = drawingView.layer.bounds
    

    然后,您将拥有完全占据绘图视图的形状层。 (如果给形状图层设置背景色,您将能够清楚地看到这一点。)现在您的问题是您要确保绘图路径本身位于形状图层的中心in,但是这是一个不同的练习。

    【讨论】:

    • 谢谢,但还是不行,形状出现在初始图附近。
    • 因为路径本身不在形状层的中心。给形状图层一个背景颜色和一个大小(现在它的大小为零);你会看到它现在正确居中。
    • 谢谢!但我不知道如何将路径居中到其层,我在互联网上看到但没有任何帮助
    • 好吧,你还没有展示任何关于路径本身是如何生成的,所以我无法提供进一步的帮助。照我说的做,你会看到形状层现在完全占据了红色绘图视图,这就是你所要求的!
    • 感谢马特,这是关于未居中路径的新问题的问题。 stackoverflow.com/questions/59938161/how-to-center-the-cashapelayer-path-in-the-shape-layer?noredirect=1#comment105998125_59938161
    猜你喜欢
    • 2014-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多