我需要创建一个基于首字母生成用户图标的Web服务。类似于the Spring Data documentation Android项目,但在服务器端使用Java。
该图像的大小应该是动态的。我已经有了代码,它会在中间创建一个带有两个字母的矩形,但它不会缩放文本。
到目前为止,这是我的代码:
public BufferedImage getAbbreviationImage(int height, int width, String abbreviation) throws IOException {
int centerX = width/2;
int centerY = height/2;
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.SCALE_SMOOTH);
Graphics2D g = bufferedImage.createGraphics();
Font font = new Font("Helvetica", Font.BOLD, 90);
g.setFont(font);
g.setRenderingHint(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
g.setColor(Color.decode("#3f404c"));
g.fillRect(0, 0, width, height);
// get the bounds of the string to draw.
FontMetrics fontMetrics = g.getFontMetrics();
Rectangle stringBounds = fontMetrics.getStringBounds(abbreviation, g).getBounds();
FontRenderContext renderContext = g.getFontRenderContext();
GlyphVector glyphVector = font.createGlyphVector(renderContext, abbreviation);
Rectangle visualBounds = glyphVector.getVisualBounds().getBounds();
// calculate the lower left point at which to draw the string. note that this we
// give the graphics context the y corridinate at which we want the baseline to
// be placed. use the visual bounds height to center on in conjuction with the
// position returned in the visual bounds. the vertical position given back in the
// visualBounds is a negative offset from the basline of the text.
int textX = centerX - stringBounds.width/2;
int textY = centerY - visualBounds.height/2 - visualBounds.y;
g.setColor(Color.WHITE);
g.drawString(abbreviation, textX, textY);
g.dispose();
return bufferedImage;
}
是否有任何Java库可以执行此类操作,以便我不必编写自己的代码。如果没有,那么根据图像尺寸缩放文本的最佳方法是什么?
答案 0 :(得分:2)
您需要设置附加到Graphics2D对象的字体大小。来自oracle docs:
public abstract void drawString(String str,
int x,
int y)
使用当前文本呈现指定String的文本 Graphics2D上下文中的属性状态
您应该设置适当使用的字体大小以匹配矩形的尺寸。像这样:
int lFontSize = 90 * (originalRectangleWidth / newRectangleWidth);
Font font = new Font("Helvetica", Font.BOLD, lFontSize );
其中:
90是参考字体大小(这是您在示例中设置的内容)
originalRectangleWidth将是当字体看起来很好并且大小为90时使用的矩形的大小
newRectangleWidth将是新的矩形宽度