如何在UIView中放置CAShapeLayer

如何在UIView中放置CAShapeLayer

本文介绍了如何在UIView中放置CAShapeLayer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在堆栈溢出中看到了很多答案,但是没有一个帮助我.我创建了一个DrawView,可以在其中绘制.我创建了 UIBezierPath 的实例进行绘图.我想在一个小视图上转移我的绘图(图像上的红色视图).那就是我所做的:

I saw many answers on Stack overflow, but none helped me.I created a DrawView where it's possible to draw. I created an instance of UIBezierPath for drawing.I want to transfer my drawing on a little view (the red one on the image). That's what I did:

// 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)
}

以下是该应用的图片:

有任何提示吗?谢谢.

推荐答案

问题是此行:

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

在您所说的 drawingView.frame 处,都说 drawingView.bounds .

(实际上,您应该说的是 drawingView.layer.bounds ,而不只是 drawingView.bounds ,而是它们是同一回事.)

(Actually you should be saying drawingView.layer.bounds, not simply drawingView.bounds, but it happens that they are the same thing.)

但是,还有第二个问题,那就是您的形状图层没有大小.因此,它的 position 与它的左上角相同.出于这个原因,您只需要说

However, there's also a second problem, which is that your shape layer has no size. Therefore its position is the same as its top left corner. For this reason you would be much better off centering it in its superlayer just by saying

shapeLayer.frame = drawingView.layer.bounds

然后,形状层将精确地占据工程图视图.(如果您给形状层一个背景色,您将可以清楚地看到.)现在您的问题将是要确保绘图路径本身在形状层的中居中,但是那是另一回事.

You will then have the shape layer exactly occupying the drawing view. (You will be able to see that clearly if you give the shape layer a background color.) Now your problem will be that you want to make sure the drawing path itself is centered in the shape layer, but that is a different exercise.

这篇关于如何在UIView中放置CAShapeLayer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 02:10