diff --git a/Sources/Image/Image.swift b/Sources/Image/Image.swift index d1e9350d1..7568ffbf3 100644 --- a/Sources/Image/Image.swift +++ b/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 } diff --git a/Tests/KingfisherTests/ImageExtensionTests.swift b/Tests/KingfisherTests/ImageExtensionTests.swift index 64d61ae10..41986e605 100644 --- a/Tests/KingfisherTests/ImageExtensionTests.swift +++ b/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 = """ + + + + + """ + + 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 }