java drawstring 模糊_使用Java Graphics.drawString替换完全合理化?

虽然不是最优雅也不是最强大的解决方案,但这里有一个方法,它将获取当前

Graphics对象的

Font并获取其

FontMetrics,以便找出绘制文本的位置,并在必要时移动到新行:

public void drawString(Graphics g, String s, int x, int y, int width)

{

// FontMetrics gives us information about the width,

// height, etc. of the current Graphics object's Font.

FontMetrics fm = g.getFontMetrics();

int lineHeight = fm.getHeight();

int curX = x;

int curY = y;

String[] words = s.split(" ");

for (String word : words)

{

// Find out thw width of the word.

int wordWidth = fm.stringWidth(word + " ");

// If text exceeds the width, then move to next line.

if (curX + wordWidth >= x + width)

{

curY += lineHeight;

curX = x;

}

g.drawString(word, curX, curY);

// Move over to the right for next word.

curX += wordWidth;

}

}

此实现将使用split方法将给定的String分隔为String数组,并将空格字符作为唯一的单词分隔符,因此它可能不是很健壮.它还假定该单词后跟空格字符,并在移动curX位置时相应地起作用.

如果我是你,我不建议使用这个实现,但是为了进行另一个实现,可能还需要使用FontMetrics class提供的方法.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值