web analytics
July 9, 2015

Display – Drawing Text

Text is drawn similarly to how you print to the Serial console. You set the text color and size, set the cursor to the position where you want to draw text, and then proceed to print the text you want to display. This text can include numbers and symbols.

Text Background

Text is drawn on top of an unknown surface. To make sure text is always drawn correctly, you have to make sure the background of the text is known. This can be done by drawing the background of the text whenever text is updated, or by setting a text background color.

Examples

#include "Phoenard.h"

void setup() {
  display.setTextSize(4);         // Use size 4x
  display.setTextColor(WHITE);    // Draw in white
  display.setCursor(10, 90);      // Set to (x=10, y=90)
  display.print("Hello, World!"); // Draw text
}

void loop() {
}

Drawing simple text

#include "Phoenard.h"

void setup() {
  // Start at (x=10, y=10)
  display.setCursor(10, 10);
  
  // Draw each size in a random color
  for (int sz = 1; sz <= 7; sz++) {
    display.setTextColor(random(0xFFFF));
    display.setTextSize(sz);
    display.print("Size ");
    display.println(sz);
  }
}

void loop() {
}

Drawing text in various styles

#include "Phoenard.h"

void setup() {
}

void loop() {
  long currentTime = millis();    // Read current time in ms
  display.setTextSize(4);         // Use size 4x

  // Use a white color with a black background
  // The black background ensures previous text is erased
  display.setTextColor(WHITE, BLACK);

  display.setCursor(10, 90);      // Set to (x=10, y=90)
  display.print("Time: ");        // Draw text
  display.print(currentTime);     // Draw time
  delay(300);                     // Wait shortly
}

Drawing dynamic text

#include "Phoenard.h"

void setup() {
}

void loop() {
  display.setTextColor(GREEN, BLACK);
  display.setTextSize(4);
  display.setCursor(40, 80);
  display.print("A0: ");         //4-chars long
  display.print(analogRead(A0)); //1-4 chars long
  
  // Pad the current line to 8 characters
  // When the value decreases in text length,
  // this makes sure the space after is erased.
  display.printPadding(8);
}

Drawing text of varying length

#include "Phoenard.h"

void setup() {
  display.setTextColor(YELLOW);
  
  // Draw text in the middle, size is automatic
  // Parameters: (x, y, width, height, text)
  display.drawStringMiddle(10, 10, 300, 200, "This is multiple\n"
                                             "lines of text that\n"
                                             "would require many\n"
                                             "separate print calls\n");
}

void loop() {
  // Quick-and-dirty printing of text in white
  // Parameters: (x, y, size, value)
  display.debugPrint(110, 170, 4, analogRead(A0));
}

Helpful text drawing utilities

Next up: Drawing images