[英]SKTexture from UIImage that respects aspect ratio
我將圖像設置為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
,右邊是圖像不同縱橫比時的結果)
有沒有辦法讓 SKSpriteNode 尊重圖像的原始縱橫比,就像UIImageView
可以設置為使用UIViewContentModeScaleAspectFill
?
編輯更改提UIViewContentModeScaleAspectFit
到UIViewContentModeScaleAspectFill
,讓他們混在一起。
您可以為 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)
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)
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.