linebender / piet

An abstraction for 2D graphics.
Apache License 2.0
1.24k stars 93 forks source link

Implement text and bitmap images in piet-svg #475

Closed derekdreery closed 2 years ago

derekdreery commented 2 years ago

The tricky bit is text layout sizing, which I need for my use-case (drawing graphs in svg using piet). I've taken the approach of loading the font on the host machine, then doing a shaping run with rustybuzz and then calculating the dimensions of the run. It doesn't work perfectly but it's OK on my machine. I thought there would be an issue with DPI, but it seems that the SVG renderer (I'm using Firefox) operates at the standard DPI and then scales everything up, so there's no issue. Named font sizing works better than using sans-serif or system-ui, presumably because font-kit and Firefox differ in their opinion of what the default sans-serif font is.

Anyway I'm PRing this because although it is not perfect, it is a significant improvement on what is currently there (nothing). I'm happy to put some effort into getting this through, so please do suggest changes etc. as necessary.

Update The text rendering is more robust now, and I added image rendering as well since it was fairly straightforward (in comparison). Hit tests etc are still not implemented, but I don't think you'll need these often (if ever) on an SVG backend.

derekdreery commented 2 years ago

SVG doesn't have the concept of multiline text or sub-spans of differently styled text, so if we wanted to implement those things, we'd have to render them as a number of separate runs, which would require accurate measuring.

derekdreery commented 2 years ago

Now supports images as well (by embedding them as png).

ratmice commented 2 years ago

I tried this branch out with something, everything went well with translated/rotated text besides having to fudge the font metrics for characters smaller than an em but that is an entirely separate issue...

anyhow, thanks for doing this!

derekdreery commented 2 years ago

I tried this branch out with something, everything went well with translated/rotated text besides having to fudge the font metrics for characters smaller than an em but that is an entirely separate issue...

anyhow, thanks for doing this!

NP! I did test transformed text, but I didn't test clipping. Might be worth someone (e.g. me) doing this, or maybe there is already a clipping test where I just need to check the output.

cmyr commented 2 years ago

We'll also have to fix the example that's causing clippy to balk

derekdreery commented 2 years ago

No worries sorry for the slow reply (Christmas etc.).

derekdreery commented 2 years ago

Urgh I'm sure the CI is fine now but its failing due to failed web request.

cmyr commented 2 years ago

looks good-to-go, thanks!