Swing/TextLayout のバックアップの現在との差分(No.11)
- バックアップ一覧
- 差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- バックアップ を表示
- Swing/TextLayout へ行く。
- 1 (2012-12-13 (木) 15:52:56)
- 2 (2013-05-24 (金) 17:30:11)
- 3 (2014-11-22 (土) 03:59:58)
- 4 (2015-02-18 (水) 15:10:04)
- 5 (2016-02-09 (火) 02:52:26)
- 6 (2016-05-25 (水) 13:08:43)
- 7 (2017-08-30 (水) 17:46:53)
- 8 (2018-03-20 (火) 13:37:26)
- 9 (2020-03-21 (土) 03:22:08)
- 10 (2021-09-26 (日) 09:48:20)
- 11 (2022-04-11 (月) 17:54:48)
- 追加された行はこの色です。
- 削除された行はこの色です。
---
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: https://lh4.googleusercontent.com/--iErOVV0RYk/TwpnJGdl4OI/AAAAAAAABHs/pHLpQWbpTWg/s800/TextLayout.png
---
* 概要 [#summary]
`TextLayout`から`Font`の`Ascent`、`Descent`、`Leading`などのメトリック情報を取得して描画します。
#download(https://lh4.googleusercontent.com/--iErOVV0RYk/TwpnJGdl4OI/AAAAAAAABHs/pHLpQWbpTWg/s800/TextLayout.png)
* サンプルコード [#sourcecode]
#code(link){{
String text = "abcdefthijklmnopqrstuvwxyz";
Font font = new Font(Font.SERIF, Font.ITALIC, 64);
FontRenderContext frc = new FontRenderContext(null, true, true);
TextLayout tl = new TextLayout(text, font, frc);
@Override protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
int w = getWidth();
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();
g2.draw(new Line2D.Float(0, xheight, w, xheight));
g2.setPaint(Color.BLACK);
tl.draw(g2, 0f, baseline);
}
}}
* 解説 [#explanation]
上記のサンプルでは、上の文字列は`TextLayout`を使用して、下は`GlyphVector` + `LineMetrics`で`Font`のメトリック情報を取得してガイドラインを描画しています。
- `Color.RED`
-- ベースライン
- `Color.GREEN`: `Ascent`
-- ベースライン - `Ascent`
- `Color.BLUE`: `Descent`
-- ベースライン + `Descent`
- `Color.ORANGE`: `Leading`
-- ベースライン + `Descent` + `Leading`
- `Color.CYAN`: `x-height`
-- ベースライン - 小文字`x`の高さ
* 参考リンク [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/java/awt/font/TextLayout.html TextLayout (Java Platform SE 8)]
- [https://docs.oracle.com/javase/tutorial/2d/text/index.html Lesson: Working with Text APIs (The Java™ Tutorials > 2D Graphics)]
* コメント [#comment]
#comment
#comment