iosswiftcore-graphicscatransform3d

How to draw CATransform3D for this layer?


I'm using CATransform3D and CAShapeLayer to create a layer like below enter image description here

Here is my code.

let path = CGMutablePath()
        let startPoint = CGPoint(x: center.x - width / 2, y: center.y - height / 2)
path.move(to: startPoint)

path.addLine(to: CGPoint(x: startPoint.x + width, y: startPoint.y))

path.addLine(to: CGPoint(x: startPoint.x + width, y: startPoint.y + height))

path.addLine(to: CGPoint(x: startPoint.x, y: startPoint.y + height))

path.closeSubpath()

    let backgroundLayer = CAShapeLayer()
backgroundLayer.path = path
backgroundLayer.fillColor = UIColor.clear.cgColor
backgroundLayer.strokeColor = boarderColor.cgColor
var transform = CATransform3DIdentity
transform.m34 = -1 / 500
let angle = 45.toRadians
backgroundLayer.transform = CATransform3DRotate(transform, angle, 1, 0, 0)

The output is like below.

enter image description here

What is the reason for the difference of shape?


Solution

  • The backgroundLayer needs a frame and a position. If these are added, the result is as follows:

    result with frame and position

    Source

    Here a slightly modified version of your code that gives the result shown in the screenshot.

    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            let boarderColor = UIColor.red
            let height: CGFloat = 400
            let width: CGFloat = 250
            let center = CGPoint(x: width / 2.0, y: height / 2)
    
            let path = CGMutablePath()
            let startPoint = CGPoint(x: center.x - width / 2, y: center.y - height / 2)
            path.move(to: startPoint)
            path.addLine(to: CGPoint(x: startPoint.x + width, y: startPoint.y))
            path.addLine(to: CGPoint(x: startPoint.x + width, y: startPoint.y + height))
            path.addLine(to: CGPoint(x: startPoint.x, y: startPoint.y + height))
            path.closeSubpath()
    
            let backgroundLayer = CAShapeLayer()
            backgroundLayer.path = path
            backgroundLayer.fillColor = UIColor.clear.cgColor
            backgroundLayer.strokeColor = boarderColor.cgColor
            //these two lines are missing
            backgroundLayer.frame = CGRect(x: 0, y: 0, width: width, height: height)
            backgroundLayer.position = CGPoint(x: self.view.bounds.width / 2.0, y: self.view.bounds.height / 2)
    
            var transform = CATransform3DIdentity
            transform.m34 = -1 / 500
            let angle = CGFloat(45 * Double.pi / 180.0)
            backgroundLayer.transform = CATransform3DRotate(transform, angle, 1, 0, 0)
    
            self.view.layer.addSublayer(backgroundLayer)
        }
    
    }