textWidth or font problem when exporting to PDF
in
Core Library Questions
•
1 month ago
The following code writes two lines with the same font and settings, but the first one using the existing text() method, while the other one uses a function called drawChars() which writes a given string character by character. Each line of text has a line underneath (I draw it as a way of measuring the length of the strings) that is supposed to have the same length as the text string, however one of the strings is displayed differently, looks shorter, like more squeezed as in the following image:
I need this drawChars() function to draw strings character by character, while I also need to know the exact pixel length of the complete string being drawn. Right now there is an inconsistency between them. Any ideas about how to solve or work around this?
When I switch from size(800, 400, PDF, "test.pdf") at the beginning to simply size(800, 400) and also comment out the exit() command in order to display the text on the screen instead of writing it to a PDF file, everything looks as expected: Both lines of strings have the same length. So there must be something wrong with the way the font is drawn on the PDF file and Processing not being able to give the right information about it when textWidth() is called. I had the same results both with and without textMode(SHAPE). Here is the code with PDF export that displays the above results, with Processing 2.0.1 on OSX 10.7.5:
-
import processing.pdf.*;
String msg = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam cursus. Morbi ut mi. Nullam enim leo, egestas id, condimentum at, laoreet mattis, massa.";
PFont f;
void setup() {
size(800, 400, PDF, "test.pdf");//size(800, 400);textMode(SHAPE);f = createFont("HelveticaNeue", 11, true);smooth();noLoop();}
void draw() {background(255);noFill();int xLine,yLine;
textFont(f);yLine=50;xLine=10;//drawChars(msg, 10, yLine);fill(0);text(msg, xLine, yLine);noFill();strokeWeight(1);line(xLine, yLine, xLine+textWidth(msg), yLine);
yLine=100;drawChars(msg, 10, yLine);noFill();strokeWeight(1);line(xLine, yLine, xLine+textWidth(msg), yLine);
println("Finished.");exit();}
void drawChars(String s, int px, int py) {println(textWidth(s));fill(0);float dx=0;char currentChar;for (int i = 0; i < s.length(); i++){currentChar = s.charAt(i);text(currentChar, px+dx, py);dx += textWidth(currentChar);}}
1