Bold text in text function

edited March 2018 in How To...

How would you do to write bold text when using text(String,int,int)?
Would I need to change the font to get the effect? And is it possible to know what is the current font being used by Processing?

Kf

Tagged:

Answers

  • How would you do to write bold text

    1. if you aren trying to make it all bold, use a bold font.
    2. if you are trying to make one word or phrase bold, you can't.

    BUT:

    If you want to treat any part of a text string differently, you can simulate this by breaking your one call to text() up into multiple text() calls using the bricklaying method recently discussed in another thread: https://forum.processing.org/two/discussion/comment/80759/#Comment_80759

    So, you print your words or phrases one at a time, and when you get to that word or phrase you want to be bold, you either change the font to a bold version of the font or you do pseudo-bold -- for example by drawing the word several times with 1px offsets.

    is it possible to know what is the current font being used by Processing?

    The easiest way is to set the font explicitly at the start of your sketch -- then you know what font it is. See the Typography tutorial for details, which also explains how to find the list of currently available fonts for loading: https://processing.org/tutorials/typography/

  • Thxs @jeremydouglass. Setting the font works for me as my text messages are handled by different text calls.

    Kf

  • @jeremydouglass Do you have any idea how bold actually works in the fonts? So far, every font I've seen has a bold and an italics option. Is there some simple algorithm for it?

  • One can generate bolder-looking text with an algorithm, but font weights like bold are also carefully designed by typographers -- there is an art to it. Some parts get thicker, other parts stay the same, depending on the letter, the kind of curve, and the style of font etc.

    For more info see:

    Also, the Processing tutorial on Typography!

  • Typographers have designed multiple types for so many thousands of different fonts. Impressive.

  • edited March 2018 Answer ✓

    I made a small mark up language here:

    • You must have space sign before < and after >, but never inside < and >.

    you can use

    <Bold> glamorous </Bold>
    <Italic> surprising </Italic>
    <Col255,0,0> anyone </Col> : all colors with 3 parameters, no spaces inside `<>` 
    

    Hope this helps.

    Best, Chrisir ;-)

    Keywords: bricklaying, markup, mark up language, formatting text

    //===========================================================================
    // FINAL FIELDS:
    final int Y_OFFSET=100;
    final int TEXT_SIZE=14;
    
    final int fontSituationNormal=0; 
    final int fontSituationBold=1; 
    final int fontSituationItalic=2; 
    
    //===========================================================================
    // GLOBAL VARIABLES:
    
    int fontSituation = fontSituationNormal;
    PFont fontNormal, fontBold, fontItalic;
    
    String [] poem = new String[15]; 
    
    //===========================================================================
    // PROCESSING DEFAULT FUNCTIONS:
    
    void setup() {
    
      size(1500, 600);
    
      // printArray(PFont.list());
    
      fontNormal = createFont("Arial", TEXT_SIZE);
      fontBold   = createFont("Arial Bold", TEXT_SIZE);
      fontItalic = createFont("Arial Italic", TEXT_SIZE);
    
      textFont(fontNormal);
    
      rectMode(CENTER);
    
      fill(255);
      strokeWeight(2);
      textSize(TEXT_SIZE);
    
      poem[0]="i love you much <Bold> glamorous </Bold> darling ";
      poem[1]="i love you much <Italic> surprising </Italic> darling ";
      poem[2]="more than <Col255,0,0> anyone </Col> on the earth and i";
      poem[3]="like you better than everything in the sky";
      poem[4]="-sunlight and singing welcome your coming";
      poem[5]="although winter may be everywhere";
      poem[6]="with such a silence and such a darkness";
      poem[7]="noone can <Col255,0,255> quite begin to guess";
      poem[8]="(except my life)the true time of year-";
      poem[9]="and if what calls itself a </Col> world should have";
      poem[10]="the luck to hear such singing (or glimpse such";
      poem[11]="sunlight as will leap higher than high";
      poem[12]="through gayer than gayest someone's heart at your each";
      poem[13]="nearness) <Col0,0,255> everyone certainly </Col> would (my";
      poem[14]="most beautiful darling) believe in nothing but love.";
    }
    
    void draw() {
      background(0);
      showRawData();
    }
    
    //===========================================================================
    // PROCESSING DEFAULT INPUT FUNCTIONS:
    
    void keyPressed() {
      if (key==' ')
      {
      }
    }//func 
    
    //===========================================================================
    // OTHER FUNCTIONS:
    
    void showRawData() {
    
      String textAdd;
      int textWidthBold=0;
    
      fill(255); // white is default 
    
      // for all lines in the poem 
      for (int i=0; i<poem.length; i++) {
    
        String[] line1 = split (poem[i], " ");
        textAdd="";
        textWidthBold=0;
    
        // for all words in the poem
        for (int i2=0; i2<line1.length; i2++) {
          // println(line1[i2]); 
    
          // Is it  mark up entry?
          if (  startOfMarkUp(line1[i2])   ) {
            // Yes. 
            analyzeMarkUpEntry(line1[i2]); 
            //
          }//if mark up entry 
          // -----------------
          else {
            // normal word
            // the x-value is a little tricky here since bold is wider than normal (or italic)
            // textWidth() calculates with current font.
            // This won't work in all situations. 
            textFont(fontNormal);
            float textWidthResult=textWidth(textAdd)+textWidthBold;
            restoreFont();   
            text(line1[i2], float(300)+ textWidthResult, Y_OFFSET + i*2*TEXT_SIZE);
            if (fontSituation==fontSituationBold)
              textWidthBold=6; 
            textAdd+=line1[i2]+" ";
          }//else
        }//for
      }//for
      //
    }
    
    // ------------------------------------------
    
    void analyzeMarkUpEntry( String str ) {
    
      // Is it an ending sign? 
      if ( startOfEndingMarkUp(str)) {
    
        // it is an ending mark up like </...>, e.g. </Bold>
    
        if (isEndingColor(str)) {
          fill(255); // white is default
        } else if (isEndingBold(str)) {
          textFont(fontNormal);
          fontSituation=fontSituationNormal;
        } else if (isEndingItalic(str)) {
          textFont(fontNormal);
          fontSituation=fontSituationNormal;
        } else {
          println ("unknown ending sign: "
            + str);
          exit();
        }
      } else {
        // it's a starting mark up like <Bold>
        if (isStartingColor(str)) {
          // set color is handled in function isStartingColor
        } else if (isStartingBold(str)) {
          fontSituation=fontSituationBold;
        } else if (isStartingItalic(str)) {
          fontSituation=fontSituationItalic;
        } else {
          println ("unknown starting sign: " 
            + str);
          exit();
        }
      } //else
    }//func
    
    //--------------------------------------------
    
    boolean  startOfMarkUp(String str) {
      if (str.trim().length()<=0) 
        return false;
    
      if (str.trim().charAt(0)=='<') 
        return true;
    
      return false;
    }
    
    boolean  startOfEndingMarkUp(String str) {
      if (str.trim().length()<=2) 
        return false;
    
      if (str.trim().charAt(0)=='<' && 
        str.trim().charAt(1)=='/') 
        return true;
    
      return false;
    }
    
    //------------------------------
    
    boolean  isEndingColor(String str) {
      if (str.trim().length()<=2) 
        return false;
    
      if (str.trim().equals("</Col>"))
        return true;
    
      return false;
    }
    
    boolean  isEndingBold(String str) {
      if (str.trim().length()<=2) 
        return false;
    
      if (str.trim().equals("</Bold>"))
        return true;
    
      return false;
    }
    
    boolean  isEndingItalic(String str) {
      if (str.trim().length()<=2) 
        return false;
    
      if (str.trim().equals("</Italic>"))
        return true;
    
      return false;
    }
    
    // ----------------------------------------------
    
    boolean  isStartingColor(String str) {
      if (str.trim().length()<=2) 
        return false;
    
      if (str.trim().contains("<Col")) {
        str=str.trim();
        str=str.replace("<Col", ""); 
        str=str.replace(">", ""); 
        String[] colorValues = split(str, ",");
        if (colorValues.length==3)
          fill(int(colorValues[0]), 
            int(colorValues[1]), 
            int(colorValues[2]));
        return true;
      }
    
      return false;
    }
    
    boolean  isStartingBold(String str) {
      if (str.trim().length()<=2) 
        return false;
    
      if (str.trim().equals("<Bold>"))
        return true;
    
      return false;
    }
    
    boolean  isStartingItalic(String str) {
      if (str.trim().length()<=2) 
        return false;
    
      if (str.trim().equals("<Italic>"))
        return true;
    
      return false;
    }
    
    //------------------------------
    
    void restoreFont() {
      switch(fontSituation) {
      case fontSituationBold:
        textFont(fontBold);
        break;
    
      case fontSituationItalic:
        textFont(fontItalic);
        break;
    
      case fontSituationNormal:
        textFont(fontNormal);
        break;
      }//switch
    }
    //
    
  • edited March 2018 Answer ✓

    Thanks for sharing this, @Chrisr -- how great!

    This could easily be easily become a library for marking up font color and style in a sketch. I could also imagine it being extended in the future to support sizes, e.g. <24> large text </24>.

    One note about your demo sketch above: I'm on a macOS 10.12, and I don't have "Arial Bold" or "Arial Italic" installed, so that part of the sketch does nothing. These are the Arial fonts on my system:

    [37] "Arial-Black"
    [38] "Arial-BoldItalicMT"
    [39] "Arial-BoldMT"
    [40] "Arial-ItalicMT"
    [47] "ArialMT"
    [48] "ArialNarrow"
    [49] "ArialNarrow-Bold"
    [50] "ArialNarrow-BoldItalic"
    [51] "ArialNarrow-Italic"
    [52] "ArialRoundedMTBold"
    [53] "ArialUnicodeMS"
    

    To get your sketch working quickly, I changed these lines to Courier:

    fontNormal = createFont("Courier", TEXT_SIZE);
    fontBold   = createFont("Courier-Bold", TEXT_SIZE);
    fontItalic = createFont("Courier-Oblique", TEXT_SIZE);
    

    I imagine this could be made more robust by using a Processing built-in font (?), or by checking the font list for multiple candidates that might appear on Mac / Linux / Windows systems and then loading one that is available. (Or, of course, by bundling a set of built-in fonts with the library / sketch.)

  • edited March 2018 Answer ✓

    Thanks a lot! Yes, I am on Win 10 system.

    Also I didn't take into account a italic bold combination...

    ;-)

  • @Chrisir

    I agree with @jeremydouglass, you should consider encapsulating this in a library. Really neat effort and could potentially replaced or expand the simple text() function implemented within the PDE.

    Kf

  • edited March 2018

    I like the custom format for defining specific colors inline: <Col255,0,0>

    HTML-like?

    Another way might be to implement just a few full tags that are standardized to look just like HTML -- including <bold>, <strong>, <em>, <i>.

    Advantages:

    1. broadly understood
    2. there are two familiar syntaxes for html text coloring. This would require implementing keywords, and isn't as compact, but is very readable.

      <font color="red">
      <span style="color:green;">
      

    Downsides:

    Might be misleading.

    1. implies that many other HTML tags might be supported, but they aren't.
    2. implies that tags might be nested

    Markdown-like?

    An alternative approach would be to implement simple Markdown rules for bold and italics:

    _italics_
    *italics*
    **bold**
    

    Advantages:

    Very easy to write, familiar (the forum uses it!), cross-compatible with thousands of software systems.

    Downsides:

    1. you would have to do some actual parsing in the code in order to handle cases with single * and _ characters.
    2. no built-in syntax for color other than inline-html or making up your own syntax -- or just use the existing <col > method.
    3. implies that tags might be nested
  • nice ideas! I don't have the time at the moment

  • HTML-like?

    Downsides:

    Might be misleading

    What is you make the disadvantage an advantage @jeremydouglas?

    Kf

  • But anyone feel free to use my code. I don’t know how to make a library anyway

Sign In or Register to comment.