【问题标题】:Getting actual view size in Swift / IOS在 Swift / IOS 中获取实际视图大小
【发布时间】:2016-03-31 21:58:12
【问题描述】:

即使在阅读框架与视图中的几篇文章后,我仍然无法使其正常工作。我打开 Xcode (7.3),为 IOS 创建一个新的游戏项目。在默认场景文件中,在 addChild 之后,我添加了以下代码:

    print(self.view!.bounds.width)
    print(self.view!.bounds.height)

    print(self.frame.size.width)
    print(self.frame.size.height)

    print(UIScreen.mainScreen().bounds.size.width)
    print(UIScreen.mainScreen().bounds.size.height)

我在 iPhone 6s 上运行它时得到以下结果:

 667.0
 375.0
 1024.0
 768.0
 667.0
 375.0

我可以猜测前两个数字是 x2 时的 Retina 像素大小。我想了解为什么帧大小报告为 1024x768?

然后我添加以下代码来调整简单背景图像的大小以填充屏幕:

    self.anchorPoint = CGPointMake(0.5,0.5)

    let theTexture = SKTexture(imageNamed: "intro_screen_phone")
    let theSizeFromBounds = CGSizeMake(self.view!.bounds.width, self.view!.bounds.height)
    let theImage = SKSpriteNode(texture: theTexture, color: SKColor.clearColor(), size: theSizeFromBounds)

我得到的图像小于屏幕尺寸。如果我选择横向模式,图像会显示得更小。

我尝试将边界宽度/高度乘以 2,希望得到实际的屏幕尺寸,但随后图像变得太大。我还尝试了使图像比屏幕略大的帧大小。

除了缺乏知识外,我感到困惑的主要原因是我在课程中看到了这个确切的例子,效果很好。要么我遗漏了一些明显的东西,要么?

【问题讨论】:

    标签: ios xcode swift


    【解决方案1】:

    帧被指定为 1024x768,因为它是以点而不是像素定义的。

    如果您希望您的场景与屏幕大小相同,则在您的 GameViewController 中呈现场景之前:

    skView.presentScene(scene)

    使用这个:

    scene.size = self.view.frame.size

    这将使场景与屏幕的大小完全相同。

    然后您可以轻松地使图像填充场景,如下所示:

        func addBackground() {
    
            let bgTexture = SKTexture(imageNamed: "NAME")
    
            let bgSprite = SKSpriteNode(texture: bgTexture, color: SKColor.clearColor(), size: scene.size)
            bgSprite.anchorPoint = CGPoint(x: 0, y: 0)
            bgSprite.position = self.frame.origin
            self.addChild(bgSprite)
        }
    

    另外,您可能想了解视图边界和框架之间的差异。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多