如何根据 iDevice 精确测量 Swift 个节点的大小和位置

How to exactly measure size & position of Swift nodes depending on iDevice

我正在创建我的第一个 Swift + SpriteKit 游戏,我正在处理这个令人头疼的问题,因为必须根据 iDevice 调整我所有东西的大小。

我得到了一个 class,它基于设备的 运行,returns 它的名称。 有了这个名字,我创建了一个基于设备字符串名称的字典,returns 给定设备的分辨率。

然后我创建了 2 个函数 -> getSizeBasedOnDevice() 和 getPositionBasedOnDevice()

自从我为 iPhone 6S 编码我的游戏。我以为得到所有这些尺寸和位置就像做一个简单的数学计算一样简单,但看起来并非如此。

这些是我的功能:

func getSizeBasedOnDevice(width: CGFloat, height: CGFloat) -> CGSize {
    // iPhone 6s w: 375, h: 667

    let deviceName = UIDevice.currentDevice().modelName
    let iphoneNative = ScreenSize(width: 375, height: 667)
    let resolution = Resolutions[deviceName]

    let newWidth = (CGFloat(resolution!.getWidth()) * width ) / iphoneNative.getWidth()
    let newHeight = (CGFloat(resolution!.getHeight()) * height) / iphoneNative.getHeight()

    return CGSize(width: newWidth, height: newHeight)
}

func getPositionBasedOnDevice(x: CGFloat, y: CGFloat) -> CGPoint {

    let deviceName = UIDevice.currentDevice().modelName
    let iphoneNative = ScreenSize(width: 375, height: 667)
    let resolution = Resolutions[deviceName]

    let newX = (CGFloat(resolution!.getWidth()) * x) / iphoneNative.getWidth()
    let newY = (CGFloat(resolution!.getHeight()) * y) / iphoneNative.getHeight()

    return CGPoint(x: newX, y: newY)
}

我的 iPhone 原始高度和宽度是我的 iPhone 6S'。 所以计算对我来说有点简单,但事实并非如此。

所以有这些示例值:

Asset's width = 100 pts
Current Device (iPhone 4S) width = 320 pts
Originally designed Device (iPhone 6S) width = 375 pts

计算公式为:

(320 * 100) / 375 = 85.33

所以在我的 iPhone 6S 上具有 100 点宽度的资产在 iPhone 4S 上具有 85.33 宽度。

起初我觉得这似乎没问题,但看看结果,我发现我做错了。

谁能给我提示?

提前致谢。

让我阻止你:)

我理解你的困难,这不是为不同屏幕尺寸构建游戏的正确方法。

您应该只考虑 Scene.

构建游戏

然后打开GameViewController.swift并寻找这一行

scene.scaleMode = .AspectFill

这一行确实允许您定义场景应如何在屏幕中表示(这对于处理不同的屏幕尺寸尤为重要)。

你有 4 个选项

  • .Fill: Scale the SKScene to fill the entire SKView.
  • .AspectFill: Scale the SKScene to fill the SKView while preserving the scene's aspect ratio. Some cropping may occur if the view has a different aspect ratio.
  • .AspectFit: Scale the SKScene to fit within the SKView while preserving the scene's aspect ratio. Some letterboxing may occur if the view has a different aspect ratio.
  • .ResizeFill: Modify the SKScene's actual size to exactly match the SKView.