Adding SVG support to Lona’s file preview
Last week, I made my first contribution to Lona. If you haven’t read my previous post, you can find it here:
I really liked the experience of contributing to this project, and I decided to work on it until the end of the semester. Earlier this week, I had an opportunity to fix the following bug:
Currently Lona Studio displays some image files, e.g. PNG files, when selected in the file navigator. However, it doesn’t display SVG files, which it really should, since it handles them elsewhere correctly. (from the issue description)
Here is how the .png files are displayed:
The .svg files are not displayed at all:
Fix
First, I had to add SVG to the list of supported formats in Info.plist
.
Then, I added the following lines to the implementation of the read
function, which is called on file selection event:
let data = try Data(contentsOf: url, options: NSData.ReadingOptions())if url.pathExtension == "svg" {
let size = CGSize(width: 450, height: 450)
content = SVG.render(contentsOf: url, size: size, resizingMode: .scaleAspectFit)
} else {
content = NSImage(data: data)
}
Let’s walk through this chunk of code.
- It checks the extension of the selected file.
- If the file has an
svg
extension, it sets thecontent
(which has type ofNSImage
) to the result ofrender
function, which was implemented in the SVG enum. - If the file has any other image extensions, it just sets
content
variable toNSImage
withdata
.
And here is the result:
As you can see, the SVG image is rendered when a user selects the image in the file navigator 👍
Enjoyed this post? Feel free to give this post a few claps so others can enjoy it 👏