【发布时间】:2017-04-27 23:15:45
【问题描述】:
我需要用Graphics#drawString来绘制文字
我在宽度和高度都发生变化(通过拖动)的 JPanel 上绘图。
我正在寻找一种生成边界的解决方案,以便我可以自动扭曲线条并相应地调整文本,而不会溢出。
我想我可以通过使用 fontMetrics 获取以像素为单位的长度来自己对其进行硬编码,但是,我宁愿有一个自动执行此操作的组件(drawString 也不支持 '\n')。
在文档以及this 其他答案中,我发现了这个:
Graphics2D g = ...;
Point2D loc = ...;
Font font = Font.getFont("Helvetica-bold-italic");
FontRenderContext frc = g.getFontRenderContext();
TextLayout layout = new TextLayout("This is a string", font, frc);
layout.draw(g, (float)loc.getX(), (float)loc.getY());
Rectangle2D bounds = layout.getBounds();
bounds.setRect(bounds.getX()+loc.getX(),
bounds.getY()+loc.getY(),
bounds.getWidth(),
bounds.getHeight());
g.draw(bounds);
它确实绘制了字符串和边界,但它们没有效果,所以这里没有运气。
我可以使用任何类吗?
【问题讨论】:
标签: java swing layout graphics