如何在Java中绘制一个垂直居中的字符串? [英] How do you draw a string centered vertically in Java?

查看:238
本文介绍了如何在Java中绘制一个垂直居中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个简单的概念,但我正在努力处理字体指标。

我尝试过使用FontMetrics getAscent,getLeading,getXXXX方法以各种组合方式,但无论我如何使用FontMetrics getAscent,getLeading,getXXXX方法已经试过文字总是被几个像素关闭。有没有一种方法来衡量文本的确切高度,以便它正好居中。

注意,你 做需要精确地考虑垂直居中的含义。

字体呈现在基线上,沿着文字底部运行。垂直空间分配如下:

  --- 
^
|领先
|
-
^ Y Y
| Y Y
| Y Y
|上升你是
| Y y y
| Y y y
- 基线______Y________y_________
| y
v descent yy
-

领先是简单的字体推荐空间在线之间。为了在两点之间垂直居中,你应该忽略领先(它是领先的,顺便说一句,不是leeding;一般印刷术中,它是/插在印刷版中的行间的引线间距)。



因此,为了使文本上下文居中,您需要

  baseline =(top +((bottom + 1-top)/ 2) - ((上升+下降)/ 2)+上升; 

如果没有最终的+上升,你就有了字体顶部的位置;因此,从顶部到底部添加了上升。



另外,请注意字体高度应该包括前导,但是一些字体不包括它,并且由于舍入差异,字体高度可能不完全相等(前导+上升+下降)。

I know it's a simple concept but I'm struggling with the font metrics. Centering horizontally isn't too hard but vertically seems a bit difficult.

I've tried using the FontMetrics getAscent, getLeading, getXXXX methods in various combinations but no matter what I've tried the text is always off by a few pixels. Is there a way to measure the exact height of the text so that it is exactly centered.

解决方案

Note, you do need to consider precisely what you mean by vertical centering.

Fonts are rendered on a baseline, running along the bottom of the text. The vertical space is allocated as follows:

---
 ^
 |  leading
 |
 -- 
 ^              Y     Y
 |               Y   Y
 |                Y Y
 |  ascent         Y     y     y 
 |                 Y      y   y
 |                 Y       y y
 -- baseline ______Y________y_________
 |                         y                
 v  descent              yy
 --

The leading is simply the font's recommended space between lines. For the sake of centering vertically between two points, you should ignore leading (it's ledding, BTW, not leeding; in general typography it is/was the lead spacing inserted between lines in a printing plate).

So for centering the text ascenders and descenders, you want the

baseline=(top+((bottom+1-top)/2) - ((ascent + descent)/2) + ascent;

Without the final "+ ascent", you have the position for the top of the font; therefore adding the ascent goes from the top to the baseline.

Also, note that the font height should include leading, but some fonts don't include it, and due to rounding differences, the font height may not exactly equal (leading + ascent + descent).

这篇关于如何在Java中绘制一个垂直居中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆