How to position CAShapeLayer in a UIView

折月煮酒 提交于 2021-01-29 11:46:40

问题


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

Here is an image of the app:

Any hint? Thank you.


回答1:


The problem is this line:

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

Everywhere you are saying drawingView.frame, say drawingView.bounds instead.

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

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.



来源:https://stackoverflow.com/questions/59937082/how-to-position-cashapelayer-in-a-uiview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!