Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine width of text in OpenSCAD?

In OpenSCAD, I want to be able to create a module which accepts a string then create a 3-D object with that string embedded in the surface as a text. I want the object to be slightly larger than the text, so I need to know how wide the text is in order to create a properly-sized object.

I'm not sure how to query the width of the text (the height is set by an input variable), or if that's even possible.

If it's not possible, is there a function that will accept a string and a font and predict the width of the rendered text?

like image 341
Gdalya Avatar asked Sep 19 '16 01:09

Gdalya


People also ask

What is the textmodule in OpenSCAD?

< OpenSCAD User Manual The textmodule creates text as a 2D geometric object, using fonts installed on the local system or provided as separate font file. [Note:Requires version 2015.03]

What fonts are included in OpenSCAD?

OpenSCAD font list dialog OpenSCAD includes the fonts Liberation Mono, Liberation Sans, and Liberation Serif. Hence, as fonts in general differ by platform type, use of these included fonts is likely to be portable across platforms. For common/casual text usage, the specification of one of these fonts is recommendedfor this reason.

What is the default text size in textmodule?

The textmodule creates text as a 2D geometric object, using fonts installed on the local system or provided as separate font file. [Note:Requires version 2015.03] Parameters text String. The text to generate. size Decimal. The generated text has an ascent (height above the baseline) of approximately the given value. Default is 10.


2 Answers

There is currently no way to query the actual size of the generated text geometry. However, depending on the model that shall be created, it might be enough to calculate a rough estimation and use scale() to fit the text into the known size.

// Fit text into a randomly generated area

r = rands(10, 20, 2);
length = 3 * r[0];
w = r[1];

difference() {
    cube([length, w, 1]);
    color("white")
        translate([0, w / 2, 0.6])
            linear_extrude(1, convexity = 4)
                resize([length, 0], auto = true)
                    text("This is a Test", valign = "center");
}
like image 56
Torsten Paul Avatar answered Sep 28 '22 07:09

Torsten Paul


If you use one of the Liberation fonts bundled with OpenSCAD or the fonts in the Microsoft Core Fonts pack, you can use my font measurement OpenSCAD library. E.g.:

use <fontmetrics.scad>;
length = measureText("This is a Test", font="Arial:style=Italic", size=20.);

The library is here. I used some Python scripts to extract metrics (including kerning pairs) from the ttf file, and you can use the scripts to add information about more fonts.

like image 40
Alexander Pruss Avatar answered Sep 28 '22 09:09

Alexander Pruss