Swing/TextLayout のバックアップの現在との差分(No.1)
TITLE:TextLayoutでFontのメトリック情報を取得する
Posted by aterai at 2012-01-09
TextLayoutでFontのメトリック情報を取得する
TextLayoutからFontのAscent、Descent、Leadingなどのメトリック情報を取得して描画します。- category: swing folder: TextLayout title: TextLayoutでFontのメトリック情報を取得する tags: [Font, TextLayout, GlyphVector, LineMetrics, Graphics] author: aterai pubdate: 2012-01-09T13:16:40+09:00 description: TextLayoutからFontのAscent、Descent、Leadingなどのメトリック情報を取得して描画します。 image:
概要
TextLayout
からFont
のAscent
、Descent
、Leading
などのメトリック情報を取得して描画します。
- &jnlp;
- &jar;
- &zip;
Screenshot
Advertisement
サンプルコード
サンプルコード
String text = "abcdefthijklmnopqrstuvwxyz";
#spandel
Font font = new Font("serif", Font.ITALIC, 64);
#spanend
#spandel
FontRenderContext frc = new FontRenderContext(null,true,true);
#spanend
#spanadd
Font font = new Font(Font.SERIF, Font.ITALIC, 64);
#spanend
#spanadd
FontRenderContext frc = new FontRenderContext(null, true, true);
#spanend
TextLayout tl = new TextLayout(text, font, frc);
#spandel
@Override public void paintComponent(Graphics g) {
#spanend
Graphics2D g2 = (Graphics2D)g;
#spanadd
@Override protected void paintComponent(Graphics g) {
#spanend
Graphics2D g2 = (Graphics2D) g;
int w = getWidth();
float baseline = getHeight()/2f;
float baseline = getHeight() / 2f;
g2.setPaint(Color.RED);
g2.draw(new Line2D.Float(0, baseline, w, baseline));
g2.setPaint(Color.GREEN);
float ascent = baseline - tl.getAscent();
g2.draw(new Line2D.Float(0, ascent, w, ascent));
g2.setPaint(Color.BLUE);
float descent = baseline + tl.getDescent();
g2.draw(new Line2D.Float(0, descent, w, descent));
g2.setPaint(Color.ORANGE);
float leading = baseline + tl.getDescent() + tl.getLeading();
g2.draw(new Line2D.Float(0, leading, w, leading));
g2.setPaint(Color.CYAN);
float xheight = baseline - (float)tl.getBlackBoxBounds(23, 24).getBounds().getHeight();
float xheight = baseline - (float) tl.getBlackBoxBounds(23, 24).getBounds().getHeight();
g2.draw(new Line2D.Float(0, xheight, w, xheight));
g2.setPaint(Color.BLACK);
tl.draw(g2, 0f, baseline);
}
View in GitHub: Java, Kotlin解説
上記のサンプルでは、上の文字列はTextLayoutを使用して、下はGlyphVector+LineMetricsでFontのメトリック情報を取得して描画しています。解説
上記のサンプルでは、上の文字列はTextLayout
を使用して、下はGlyphVector
+ LineMetrics
でFont
のメトリック情報を取得してガイドラインを描画しています。
- Color.RED
-
Color.RED
- ベースライン
- Color.GREEN: Ascent
- ベースライン - Ascent;
- Color.BLUE: Descent
- ベースライン + Descent;
- Color.ORANGE: Leading
- ベースライン + Descent + Leading;
- Color.CYAN: x-height
- ベースライン - 文字"x"の高さ;
-
Color.GREEN
:Ascent
- ベースライン -
Ascent
- ベースライン -
-
Color.BLUE
:Descent
- ベースライン +
Descent
- ベースライン +
-
Color.ORANGE
:Leading
- ベースライン +
Descent
+Leading
- ベースライン +
-
Color.CYAN
:x-height
- ベースライン - 小文字
x
の高さ
- ベースライン - 小文字