如何为这一层绘制CATransform3D?

How to draw CATransform3D for this layer?

我正在使用 CATransform3D 和 CAShapeLayer 创建一个图层,如下所示

这是我的代码。

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)

输出如下。

形状不同的原因是什么?

backgroundLayer 需要一个框架和一个位置。如果加上这些,结果如下:

来源

这里是您的代码的一个稍微修改的版本,它给出了屏幕截图中显示的结果。

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

}