【问题标题】:SKTexture from UIImage that respects aspect ratio来自 UIImage 的 SKTexture 尊重纵横比
【发布时间】:2015-03-11 00:03:08
【问题描述】:

我将图像设置为SKScene 的背景,代码类似于以下

/* In SKScene subclass */
background = SKSpriteNode()
background.anchorPoint = CGPointMake(0,1)
background.position = CGPointMake(0, size.height)
background.zPosition = Layer.Background
background.size = view!.bounds.size
background.texture = SKTexture(image: <# UIImage #>)
addChild(background)

这可以插入图像作为场景的背景,但如果图像与background 节点的纵横比不同,则会拉伸以填充它。

(左边是裁剪图像以适应SKSpriteNode的纵横比时的结果,右边是图像具有不同纵横比时的结果)

有没有办法让 SKSpriteNode 尊重图像的原始纵横比,例如可以将UIImageView 设置为使用UIViewContentModeScaleAspectFill?

编辑 将UIViewContentModeScaleAspectFit 的提及更改为UIViewContentModeScaleAspectFill,把它们搞混了。

【问题讨论】:

  • 你的背景图片是否覆盖了整个屏幕?
  • 不,它是一个正方形,其尺寸等于设备的宽度(例如,在 4 英寸 iPhone 上为 320x320)。
  • 所以您希望图像始终适合设备的宽度而不更改纵横比?
  • 我刚刚意识到我的问题弄错了。我希望它复制UIViewContentModeScaleAspectFill,而不是Fit,哎呀。所以我希望纹理完全填充场景,同时尊重图像的纵横比,即使它要遗漏图像的某些部分。我将编辑我的问题以反映我的错误。

标签: ios swift uiimage sktexture


【解决方案1】:

您可以为 SKSpriteNode 创建一个扩展来执行此操作。

extension SKSpriteNode {

    func aspectFillToSize(fillSize: CGSize) {

        if texture != nil {
            self.size = texture!.size()

            let verticalRatio = fillSize.height / self.texture!.size().height
            let horizontalRatio = fillSize.width /  self.texture!.size().width

            let scaleRatio = horizontalRatio > verticalRatio ? horizontalRatio : verticalRatio

            self.setScale(scaleRatio)
        }
    }

}

使用它

let background = SKSpriteNode()
background.anchorPoint = CGPointMake(0,1)
background.position = CGPointMake(0, size.height)
background.texture = SKTexture(imageNamed: "1.png")
background.aspectFillToSize(view.frame.size) // Do this after you set texture
addChild(background)

【讨论】:

    【解决方案2】:

    Rakeshbs 的回答很棒。 但我认为这个解决方案的关键是动态改变 SKSpriteNode 的大小。不需要出售节点。所以我更新他的代码如下

    extension SKSpriteNode {
    func aspectFillToSize(fillSize: CGSize) {
        if let texture = self.texture {
            let horizontalRatio = fillSize.width / texture.size().width
            let verticalRatio = fillSize.height / texture.size().height
            let finalRatio = horizontalRatio < verticalRatio ? horizontalRatio : verticalRatio
            size = CGSize(width: texture.size().width * finalRatio, height: texture.size().height * finalRatio)
        }
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-09
      • 2016-01-28
      • 2016-03-21
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      • 2011-10-06
      • 2010-12-14
      相关资源
      最近更新 更多