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

38
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, float fontSize, S text) {
  ret renderText(font.deriveFont(fontSize), text);
}
  
static BufferedImage renderText(Font font, S 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   

Travelled to 10 computer(s): aoiabmzegqzx, cbybwowwnfue, cfunsshuasjs, ddnzoavkxhuk, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, tslmcundralx, tvejysmllsmz

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/6
Text MD5: d1f95e8a0b1717c6b74acd288f45f8f9
Author: stefan
Category: javax / imaging
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2017-07-06 01:02:46
Source code size: 1137 bytes / 38 lines
Pitched / IR pitched: No / No
Views / Downloads: 320 / 296
Version history: 5 change(s)
Referenced in: [show references]

Formerly at http://tinybrain.de/1004566 & http://1004566.tinybrain.de