ios - 如何为这一层绘制CATransform3D?

标签 ios swift core-graphics catransform3d

我正在使用 CATransform3D 和 CAShapeLayer 创建如下所示的图层 enter image description here

这是我的代码。

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)

输出如下。

enter image description here

形状不同的原因是什么?

最佳答案

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

result with frame and position

来源

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

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

}

关于ios - 如何为这一层绘制CATransform3D?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51146625/

相关文章:

swift - SCNCamera 不会更新位置

objective-c - 我可以用一种颜色和不同颜色的边框描边路径吗?

ios - 如何绘制相对于 UIView 大小的点网格?

Swift:使用 UIBezierPath 绘制文本

ios - 如何在 iOS 中创建类似于 WhatsApp 中的多行导航栏?

ios - 更改 UIWindow 的 rootViewController

ios - 在 Swift 中导入扩展文件

ios - 使用模型中的 Firestore 数据初始化对象

swift - 使用 NSRegularExpression 结果对字符串进行子字符串化的正确方法是什么?

ios - Swift Mapkit 未指向位置