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)

1  
static new ThreadLocal<Color> renderText_fg;
2  
static new ThreadLocal<Color> renderText_bg;
3  
4  
sbool renderText_withLeading = true;
5  
6  
static BufferedImage renderText(S fontName, float fontSize, S text) {
7  
  ret renderText(loadFont_cached(fontName), fontSize, text);
8  
}
9  
10  
static BufferedImage renderText(Font font default sansSerif(), float fontSize, S text) {
11  
  ret renderText(font.deriveFont(fontSize), text);
12  
}
13  
  
14  
static BufferedImage renderText(Font font default sansSerif(), O _text) {
15  
  S text = str(_text);
16  
  
17  
  Color background = optPar(renderText_bg, Color.white);
18  
  Color foreground = optPar(renderText_fg, Color.black);
19  
20  
  // for font metrics
21  
  FontMetrics fm = fontMetrics(font);
22  
  int width = fm.stringWidth(text);
23  
  if (width <= 0) null;
24  
  int height = fm.getHeight();
25  
  int y = renderText_withLeading
26  
    ? fm.getLeading() + fm.getMaxAscent()
27  
    : fm.getAscent();
28  
  
29  
  BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
30  
    
31  
  Graphics g = imageGraphics(img);
32  
  g.setColor(background);
33  
  g.fillRect(0, 0, width, height);
34  
  g.setColor(foreground);
35  
  g.setFont(font);
36  
  g.drawString(text, 0, y);
37  
  g.dispose();
38  
  
39  
  return img;
40  
}

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: 613 / 623
Version history: 7 change(s)
Referenced in: [show references]