Strange textWidth() behavior.....ideas?
in
Programming Questions
•
1 year ago
I use the textWidth() function to allow me to increase or decrease the font size so that my user can continue to type in a box and the text scales to stay within the bounds of the on-screen rectangle. The logic is that if textWidth() of the entered string goes > box width, reduce the font size. If textWidth() goes down, increase the font size to a predetermined font size limit.
The issue is that while this looks ok on-screen until the text reaches the edges of the box and starts to reduce, the font decreases even though the width of the text is well witin the bounds of the box because of the reduced fontSize. txtWidth() continues to return increasing values for the string length even though the font size reduces the actual text width. I had expected textWidth() to decrease when I reduce the font size. I'm missing something obvious here (because my small test programs do give a reduced textWidth value with smaller font size) but after hours of pouring over the code and searching for an answer I'm not getting anywhere.
Thoughts? Here's the code...
- void keyPressed() {
- // onLine2, newLine are global boolean variables
- // Box dims are held in an array as I have several boxes
- // BoxW[] is the box width
- float pixelLength = 0;
- // ==================== Keyboard Entry ==================================
- if ( keyCode == DELETE || keyCode == BACKSPACE ) // catch and process deletions
- {
- if ( inp.length() >= 0 ) { // Check to see if we have any text
- inp = inp.substring(0,inp.length()-1);
- } // now show in the correct onscreen variable
- if (newLine) {
- txtLine2[currentBox] = inp;
- }else{
- txtLine1[currentBox] = inp;
- }
- }else if (key != CODED) {
- if (key == '\n'){ // catch for RETURN
- newLine = true;
- inp = "";
- } else {
- // Otherwise, concatenate the String
- // Each character typed by the user is added to the end of the String variable.
- if (!newLine) { //are we adding to first or second line of text
- onLine2 = false;
- inp = inp + key;
- txtLine1[currentBox] = inp;
- pixelLength = textWidth(txtLine1[currentBox]);
- } else {
- onLine2 = true;
- inp = inp + key;
- txtLine2[currentBox] = inp;
- pixelLength = textWidth(txtLine2[currentBox]);
- }
- }
- }
- //================== Adjust font size to stay within BoxW[] ================
- println(inp +" : PL :"+ pixelLength +" BW :"+BoxW[currentBox]+" FS : "+tagFontSize[currentBox]);
- if (pixelLength > BoxW[currentBox]){
- tagFontSize[currentBox]=tagFontSize[currentBox]-2; //decrese FontSize - by 2 to scale properly
- println("*******************TFS "+currentBox+":"+screenFontSize+":"+tagFontSize[currentBox]);
- }else if(pixelLength < (BoxW[currentBox]-10) && tagFontSize[currentBox] < 36){
- tagFontSize[currentBox]=tagFontSize[currentBox]+2; //increase FontSize;
- println("*******************TFS "+currentBox+":"+screenFontSize+":"+tagFontSize[currentBox]);
- }
- }
1