You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决SKScene.scaleMode=.aspectFit旋转时内容裁切问题?

解决SKScene横竖屏完整无裁切显示的方案

核心思路:动态适配SKScene尺寸,保留原始宽高比

你的场景高度远大于宽度,不用改成方形,通过以下方法就能实现横竖屏时完整显示无裁切:


1. 动态计算适配视图的场景尺寸

在setupScene()方法以及横竖屏旋转回调中,根据当前SKView的尺寸,计算出能完整放入视图且保留原始宽高比的场景尺寸:

func updateSceneSize(for skView: SKView) {
    // 原始场景的宽高比(你的场景是高>宽,所以比值>1)
    let originalSceneRatio = ourScene.size.height / ourScene.size.width
    // 当前视图的宽高比
    let viewRatio = skView.bounds.height / skView.bounds.width
    
    var newSceneSize: CGSize
    if viewRatio > originalSceneRatio {
        // 视图比场景更“高”,以视图宽度为基准,按原始比例计算场景高度
        newSceneSize = CGSize(width: skView.bounds.width, height: skView.bounds.width * originalSceneRatio)
    } else {
        // 视图比场景更“宽”,以视图高度为基准,按原始比例计算场景宽度
        newSceneSize = CGSize(height: skView.bounds.height, width: skView.bounds.height / originalSceneRatio)
    }
    
    ourScene.size = newSceneSize
    ourScene.scaleMode = .resizeFill // 让场景完全适配自身尺寸
}
  • 在setupScene()中初始化场景后,立即调用这个方法:
    func setupScene() {
        let skView = self.view as! SKView
        ourScene = YourSceneClass(size: skView.bounds.size) // 初始尺寸先设为视图尺寸
        updateSceneSize(for: skView)
        skView.presentScene(ourScene)
        skView.contentMode = .center // 确保场景居中显示
    }
    
  • 监听横竖屏旋转,在旋转完成后更新场景尺寸:
    override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
        super.viewWillTransition(to: size, with: coordinator)
        coordinator.animate(alongsideTransition: { _ in
            if let skView = self.view as? SKView {
                self.updateSceneSize(for: skView)
            }
        })
    }
    

2. 配合SKView的contentMode设置

将SKView的contentMode设为.center,这样当场景尺寸小于视图时,会自动居中,不会被拉伸或裁切。

3. 无需改为方形场景

改成方形场景会破坏你原本的内容布局,完全没必要。通过动态调整场景尺寸,既能保留原始宽高比,又能保证横竖屏时内容完整显示。


内容的提问来源于stack exchange,提问作者user20439709

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 14:45:31