我在堆栈溢出中看到了很多答案,但是没有一个帮助我。我创建了一个可以绘制的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)
}
这里是应用程序的图像:
有任何提示吗?谢谢。
问题是此行:
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中心,但这是一个不同的运动。