Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

71
LINES

< > BotCompany Repo | #1034602 // RenderText - renders text line from loaded font (e.g. TTF)

JavaX fragment (include) [tags: use-pretranspiled]

Transpiled version (12539L) is out of date.

sclass RenderText is MakesBufferedImage {
  settable Color foregroundColor = Color.black;
  settable Color backgroundColor = Color.white;
  settable bool withLeading = true;
  settable Font font = sansSerifFont(20);
  settable Float fontSize; // null to keep size of font
  settable double spacing; // extra spacing per character
  settable S text = "DEMO";
  settable S alignment = "left";
  
  Font scaledFont;
  FontMetrics fm;
  LS lines;
  
  *() {}
  *(Font *font) {}
  
  selfType setFont(S fontSnippetID) {
    ret setFont(fontForName(fontSnippetID));
  }
  
  Font scaledFont() {
    Font font = this.font;
    if (spacing != 0) font = fontWithSpacing(spacing, font);
    ret scaledFont = fontSize == null ? font : font.deriveFont(fontSize);
  }
  
  BufferedImage get(S text) {
    text(text);
    ret this!;
  }

  public BufferedImage get aka image aka getBufferedImage() {
    fm = fontMetrics(scaledFont());
    
    lines = lines(text);
    var lineWidths = map(lines, line -> fm.stringWidth(line));
    int width = intMax(lineWidths);
    if (width <= 0) null;
    
    int lineHeight = fm.getHeight(); 
    int height = lineHeight*l(lines);
    int y = withLeading
      ? fm.getLeading() + fm.getMaxAscent()
      : fm.getAscent();
  
    BufferedImage img = bufferedImageWithoutAlpha(width, height, backgroundColor);
    
    Graphics g = imageGraphics(img);
    g.setColor(foregroundColor);
    g.setFont(scaledFont);
    for i over lines: {
      int x = 0;
      if (eq(alignment, "center"))
        x = (width-lineWidths.get(i))/2;
      g.drawString(lines.get(i), x, lineHeight*i+y);
    }
    g.dispose();
  
    ret img;
  }

  // can the font display all the required characters?
  bool canDisplay() {
    ret canFontDisplay(font, text);
  }
  
  selfType fontSize(float f) { ret fontSize((Float) f); }
  
  toString { ret "RenderText " + quote(shorten(text)); }
}

Author comment

Began life as a copy of #1004566

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, ekrmjmnbrukm, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1034602
Snippet name: RenderText - renders text line from loaded font (e.g. TTF)
Eternal ID of this version: #1034602/19
Text MD5: 017cf9997e413a0444ca08866f034bd6
Author: stefan
Category: javax / imaging
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2023-02-06 14:40:27
Source code size: 1963 bytes / 71 lines
Pitched / IR pitched: No / No
Views / Downloads: 128 / 305
Version history: 18 change(s)
Referenced in: [show references]