• title: GlyphVectorで文字列を電光掲示板風にスクロール tags: [GlyphVector, LineMetrics, TextLayout, Animation, JComponent] author: aterai pubdate: 2006-11-13 description: GlyphVectorを生成して、これを電光掲示板のようにスクロールさせます。

概要

GlyphVectorを生成して、これを電光掲示板のようにスクロールさせます。

サンプルコード

class MarqueePanel extends JComponent implements ActionListener {
  public final javax.swing.Timer animator;
  private final GlyphVector gv;
  private float xx, yy;
  public MarqueePanel() {
    super();
    animator = new javax.swing.Timer(10, this);
    String text = "asffdfaaAAASFDsfasdfsdfasdfasd";
    Font font = new Font(Font.SERIF, Font.PLAIN, 100);
    FontRenderContext frc = new FontRenderContext(null,true,true);
    gv = font.createGlyphVector(frc, text);
    LineMetrics lm = font.getLineMetrics(text, frc);
    yy = lm.getAscent() / 2f + (float) gv.getVisualBounds().getY();
  }
  @Override public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    int cw = getWidth();
    int ch = getHeight();
    g2.setPaint(Color.WHITE);
    g2.draw(new Line2D.Float(0, ch / 2f, cw, ch / 2f));
    g2.setPaint(Color.BLACK);
    g2.drawGlyphVector(gv, cw - xx, ch / 2f - yy);
    xx = (cw + gv.getVisualBounds().getWidth() - xx > 0) ? xx + 2f : 0f;
  }
  @Override public void actionPerformed(ActionEvent e) {
    repaint();
  }
}
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、GlyphVectorLineMetricsから、テキストのVisualBoundsAscentを取得して、文字列を描画する位置などを計算しています。

以下のようにTextLayoutを使用する方法もあります。

TextLayout tl = new TextLayout(text, font, frc);
Rectangle2D b = tl.getBounds();
yy = tl.getAscent() / 2f + (float) b.getY();

コメント