golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
122.19k stars 17.46k forks source link

x/image/font: make it easier to measure a string's bounds and draw it in a bounding box #14436

Open josharian opened 8 years ago

josharian commented 8 years ago

This issue applies to github.com/golang/freetype, if that is still under development.

I want to accomplish the following (superficially) easy tasks:

I will use this to render a simple, short string into a texture of just the right size, and then upload that texture onto a window for use as a label at a particular origin.

MeasureString looks close, but it only provides the width, not the height. (And I don't see a way to get the line height / leading from a font.) And DrawString is close, but the dot's y offset is the baseline of the text, which I don't see a handy way to calculate.

The fact that these are top-level APIs in Cocoa suggests that these are common needs and that they cover a large portion of use cases. Maybe this should be handled with examples, or maybe with new fundamental APIs, or maybe with convenience APIs. I don't know enough to say.

/cc @nigeltao

nigeltao commented 8 years ago

Yes, this is part of the "TODO: per-font Metrics" in font.go.

BTW, github.com/golang/freetype the project (not the top-level package) is still under development. See also https://github.com/golang/freetype/issues/15

tv42 commented 3 years ago

Of the two tasks, the first one seems supported. https://godoc.org/golang.org/x/image/font#Metrics has Ascent and Descent now, and Drawer.BoundBytes seems to work great.

Second isn't. I would love for someone to provide me a "with this font, at whatever face point size is appropriate (but still let me pick DPI & Hinting?), render this text into a box that shall not exceed H pixels tall and/or W pixels wide". For my current need, I am specifically looking to constrain height only.

For now, I wrote a sort.Search gimmick that looks for a point size between 0 and 72 (one inch tall text) at small increments.