Search code examples
swiftxcodeuiviewcalayercgpath

How to position CAShapeLayer in a UIView


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:

enter image description here

Any hint? Thank you.


Solution

  • 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.