java文字垂直居中,如何在Java中绘制一个垂直居中的字符串?

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).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值