来自UIImage的SKTexture尊重纵横比

时间:2015-03-11 00:03:09

标签: ios swift uiimage sktexture

我将图片设置为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,将它们混淆了。

2 个答案:

答案 0 :(得分:12)

您可以为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)

答案 1 :(得分: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)
    }
}

}