ios - 如何将 anchor 视角设置为 0.5 , 0.5 以获得屏幕中心的 View ? (不是场景)

标签 ios swift sprite-kit core-location cgpoint

我想让我的游戏全屏显示,而不是两侧和底部都有黑条。所以我找到了这个代码,它适用于场景,现在它在全屏上,但 Assets 没有正确定位。因为 View 的坐标不同(不知道为什么,也许是因为之前我尝试为 safeAreaLayoutGuide 设置所有内容,但后来我得到了黑条)。那么有什么办法可以将其设置回 0.5 0.5 。否则,我将不得不将场景的 anchorPoint 设置为 View 的 anchorPoint 并据此设置我的 sks 文件中的所有资源。

这是来自 GameViewController 的代码:

class GameViewController: UIViewController {

    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()

        if let view = self.view as! SKView? {
            view.ignoresSiblingOrder = true
            view.showsFPS = true
            view.showsNodeCount = true

            let scene = HomeScene(size: view.bounds.size)
            scene.scaleMode = .aspectFill
            view.presentScene(scene)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        print("---")
        print("∙ \(type(of: self))")
        print("---")
    }
}

这段代码来自HomeScene:

let rectangle1 = SKShapeNode(rect: (self.view?.bounds)!)
rectangle1.strokeColor = .white
rectangle1.lineWidth = 20
addChild(rectangle1)

// Set (0, 0) as the centre of the screen
scene?.anchorPoint = CGPoint(x: 0.5, y: 0.5)

let rectangle = SKShapeNode(rect: self.frame)
rectangle.strokeColor = .green
rectangle.lineWidth = 20
addChild(rectangle)

这就是场景在 0.5、0.5 处的样子,但是 View 位于绿色是场景、白色是 View 和 View 中间的按钮的上方:

enter image description here

谢谢。

最佳答案

您可以使用不同的 anchor 解决问题,或者可以在场景中以不同的方式定位白色“ View ”节点。

有关坐标系(和 anchor )的信息:apple documentation

根据文档,默认 anchor 位置为 (0.5, 0.5)。要将白色 View 放在左下角:减去 x 和 y 的宽度和高度的一半。请注意,线宽也会影响定位。将白色 View 放置在左下角:

let bottomLeft: CGPoint = CGPoint(x: -self.size.width/2 + rectangle1.lineWidth/2,
                                  y: -self.size.height/2 + rectangle1.lineWidth/2)
rectangle1.position = bottomLeft

要将白色 View 置于绿色 View 的中心,请减去矩形1的宽度和高度(再次注意线宽)

let center: CGPoint = CGPoint(x: -rectangle1.frame.size.width/2 + rectangle1.lineWidth/2,
                              y: -rectangle1.frame.size.height/2 + rectangle1.lineWidth/2)
rectangle1.position = center

请注意,您的绿色 View 位于白色 View 上方。将白色 View 的 z 位置设置为某个正数,将其排列在绿色 View 上方

rectangle1.zPosition = 1

关于ios - 如何将 anchor 视角设置为 0.5 , 0.5 以获得屏幕中心的 View ? (不是场景),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54004414/

相关文章:

ios - 引用另一个类中的对象

ios - 无法将由关节连接的 Sprite 移动到正确的位置

iphone - 如何在 mfmailcomposerview 中关闭键盘

html - 如何允许在 iOS 上上传 PDF 文件?

iOS地理围栏,监控开始时进入区域内如何处理?

swift - 如何获取#function 或#line 的期望值?

ios - 表的Firebase查询

ios - "continue userActivity"方法未调用,尽管 Firebase 深层链接已成功打开应用程序

ios - 如何在 Sprite Kit 中执行没有触摸 Action 的平移?

ios - 使用字符串数组填充 UI TableView