• 追加された行はこの色です。
  • 削除された行はこの色です。
TITLE:GlyphVectorで文字列を電光掲示板風にスクロール
#navi(../)
*GlyphVectorで文字列を電光掲示板風にスクロール [#c40292de]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:2006-11-13~
更新日:&lastmod;
Posted by [[terai]] at 2006-11-13

#contents

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

-&jnlp;
-&jar;
-&zip;

#screenshot

**サンプルコード [#o7b152c4]
#code{{
 class ScrollingMessagePanel extends JComponent implements ActionListener {
   public final javax.swing.Timer animator;
   private final GlyphVector gv;
   private float xx, yy;
 
   public ScrollingMessagePanel() {
     super();
     animator = new javax.swing.Timer(10, this);
 
     String text = "asffdfaaAAASFDsfasdfsdfasdfasd";
     Font font = new 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();
   }
   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;
   }
   public void actionPerformed(ActionEvent e) {
     repaint();
   }
 }
class ScrollingMessagePanel extends JComponent implements ActionListener {
  public final javax.swing.Timer animator;
  private final GlyphVector gv;
  private float xx, yy;

  public ScrollingMessagePanel() {
    super();
    animator = new javax.swing.Timer(10, this);

    String text = "asffdfaaAAASFDsfasdfsdfasdfasd";
    Font font = new 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();
  }
  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;
  }
  public void actionPerformed(ActionEvent e) {
    repaint();
  }
}
}}
-&jnlp;
-&jar;
-&zip;

**解説 [#qe412244]
上記のサンプルでは、GlyphVectorやLineMetricsから、テキストのVisualBoundsやAscentを取得して、文字列を描画する位置などを計算しています。

以下のようにTextLayoutを使用する方法もあります。
#code{{
 TextLayout tl = new TextLayout(text, font, frc);
 Rectangle2D b = tl.getBounds();
 yy = tl.getAscent()/2f + (float)b.getY();
TextLayout tl = new TextLayout(text, font, frc);
Rectangle2D b = tl.getBounds();
yy = tl.getAscent()/2f + (float)b.getY();
}}

//**参考リンク
**コメント [#l55e2ad9]
#comment