Skip to content

Commit

Permalink
Merge pull request #2334 from onevcat/fix/image-size-rendering
Browse files Browse the repository at this point in the history
Fix zero image size rendering for SVG/PDF on macOS
  • Loading branch information
onevcat authored Dec 17, 2024
2 parents 670ebed + 55266a4 commit 785a029
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
17 changes: 13 additions & 4 deletions Sources/Image/Image.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
22 changes: 22 additions & 0 deletions Tests/KingfisherTests/ImageExtensionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

0 comments on commit 785a029

Please sign in to comment.