4

我正在将图像设置为 a 的背景,其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 尊重图像的原始纵横比,以 aUIImageView可以设置为使用的方式UIViewContentModeScaleAspectFill

编辑 将提及更改UIViewContentModeScaleAspectFitUIViewContentModeScaleAspectFill,将它们混淆了。

4

2 回答 2

17

您可以为 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)
于 2015-03-13T09:04:05.333 回答
0

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)
    }
}

}

于 2020-09-15T09:24:39.650 回答