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

40
LINES

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

JavaX fragment (include)

static new ThreadLocal<Color> renderText_fg;
static new ThreadLocal<Color> renderText_bg;

sbool renderText_withLeading = true;

static BufferedImage renderText(S fontName, float fontSize, S text) {
  ret renderText(loadFont_cached(fontName), fontSize, text);
}

static BufferedImage renderText(Font font default sansSerif(), float fontSize, S text) {
  ret renderText(font.deriveFont(fontSize), text);
}
  
static BufferedImage renderText(Font font default sansSerif(), O _text) {
  S text = str(_text);
  
  Color background = optPar(renderText_bg, Color.white);
  Color foreground = optPar(renderText_fg, Color.black);

  // for font metrics
  FontMetrics fm = fontMetrics(font);
  int width = fm.stringWidth(text);
  if (width <= 0) null;
  int height = fm.getHeight();
  int y = renderText_withLeading
    ? fm.getLeading() + fm.getMaxAscent()
    : fm.getAscent();
  
  BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    
  Graphics g = imageGraphics(img);
  g.setColor(background);
  g.fillRect(0, 0, width, height);
  g.setColor(foreground);
  g.setFont(font);
  g.drawString(text, 0, y);
  g.dispose();
  
  return img;
}

Author comment

Began life as a copy of #1001425

download  show line numbers  debug dex  old transpilations   

Travelled to 15 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, ddnzoavkxhuk, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt, wnsclhtenguj

No comments. add comment

Snippet ID: #1004566
Snippet name: renderText - renders text line from loaded font (e.g. TTF)
Eternal ID of this version: #1004566/8
Text MD5: dd30aa2ef19aa69ab9e4eb2bdd680f2a
Author: stefan
Category: javax / imaging
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-08-14 22:10:46
Source code size: 1206 bytes / 40 lines
Pitched / IR pitched: No / No
Views / Downloads: 611 / 620
Version history: 7 change(s)
Referenced in: [show references]