Parcourir la source

Merge pull request #2334 from onevcat/fix/image-size-rendering

Fix zero image size rendering for SVG/PDF on macOS
Wei Wang il y a 1 an
Parent
commit
785a029211
2 fichiers modifiés avec 35 ajouts et 4 suppressions
  1. 13 4
      Sources/Image/Image.swift
  2. 22 0
      Tests/KingfisherTests/ImageExtensionTests.swift

+ 13 - 4
Sources/Image/Image.swift

@@ -93,11 +93,20 @@ extension KingfisherWrapper where Base: KFCrossPlatformImage {
     }
     
     var size: CGSize {
-        return base.representations.reduce(.zero) { size, rep in
-            let width = max(size.width, CGFloat(rep.pixelsWide))
-            let height = max(size.height, CGFloat(rep.pixelsHigh))
-            return CGSize(width: width, height: height)
+        // Prefer to use pixel size of the image
+        let pixelSize = base.representations.reduce(.zero) { size, rep in
+            CGSize(
+                width: max(size.width, CGFloat(rep.pixelsWide)),
+                height: max(size.height, CGFloat(rep.pixelsHigh))
+            )
         }
+        // If the pixel size is zero (SVG or PDF, for example), use the size of the image.
+        return pixelSize == .zero ? base.representations.reduce(.zero) { size, rep in
+            CGSize(
+                width: max(size.width, CGFloat(rep.size.width)),
+                height: max(size.height, CGFloat(rep.size.height))
+            )
+        } : pixelSize
     }
     #else
     var cgImage: CGImage? { return base.cgImage }

+ 22 - 0
Tests/KingfisherTests/ImageExtensionTests.swift

@@ -344,4 +344,26 @@ class ImageExtensionTests: XCTestCase {
         // You can not "downsample" an image to a larger size.
         XCTAssertEqual(largerImage?.size, CGSize(width: 64, height: 64))
     }
+
+    #if os(macOS)
+    func testSVGImageSize() {
+        let svgString = """
+        <?xml version="1.0" encoding="UTF-8"?>
+        <svg width="100px" height="200px" viewBox="0 0 100 200" version="1.1" xmlns="http://www.w3.org/2000/svg">
+            <rect width="100" height="200" fill="red"/>
+        </svg>
+        """
+        
+        guard let data = svgString.data(using: .utf8),
+              let image = NSImage(data: data)
+        else {
+            XCTFail("Failed to create image from SVG data")
+            return
+        }
+        
+        let size = image.kf.size
+        XCTAssertEqual(size.width, 100)
+        XCTAssertEqual(size.height, 200)
+    }
+    #endif
 }