杨锴
2025-06-04 ac84f81ca2311300b431c1bfb9f71253b59073f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// SKSpriteNodeExtensions.swift - Copyright 2023 SwifterSwift
 
#if canImport(SpriteKit)
import SpriteKit
 
// MARK: - Methods
 
public extension SKSpriteNode {
    /// SwifterSwift: SKSpriteNode sized with respect to aspect ratio.
    ///
    ///        node.aspectFill(to: CGSize(width: 300, height: 300)
    ///
    /// - Parameter fillSize: fill size to use for aspect ratio calculation.
    func aspectFill(to fillSize: CGSize) {
        if let textureSize = texture?.size() {
            let width = textureSize.width
            let height = textureSize.height
 
            // Avoid division by 0.
            guard width > 0, height > 0 else {
                return
            }
 
            let horizontalRatio = fillSize.width / width
            let verticalRatio = fillSize.height / height
            let ratio = horizontalRatio < verticalRatio ? horizontalRatio : verticalRatio
            size = CGSize(width: width * ratio, height: height * ratio)
        }
    }
}
 
#endif