java字体边框
使用java在图形上绘制文字,给文字增加边框
思路:将字体转换为图形对象shape,然后分别用不用颜色绘制图形的内部与边框。
@Test
void drawImage() throws Exception {
Font font;
// 加载字体文件,防止中文乱码
try (InputStream fontStream = CvUtil.class.getResourceAsStream("/fonts/msyh.ttc")) {
if (fontStream == null) {
throw new BusinessException(ErrorCodeEnum.Unknow);
}
font = Font.createFont(Font.TRUETYPE_FONT, fontStream).deriveFont(Font.BOLD, 148);
} catch (Exception e) {
throw new BusinessException(e);
}
BufferedImage bufferedImage = ImageIO.read(new File("1.jpg"));
// 拿到2d 图形
Graphics2D g2 = bufferedImage.createGraphics();
// 将字体转换为图形 shape
FontRenderContext fontRenderContext = g2.getFontRenderContext();
GlyphVector v = font.createGlyphVector(fontRenderContext, "祝愿祖国早日实现世界和平");
Shape shape = v.getOutline();
// 设置接下来要绘制的位置
g2.translate(100, 150);
// 设置接下来绘制使用的颜色
g2.setColor(Color.WHITE);
// 绘制图形shape内部
g2.fill(shape);
// 设置接下来绘制使用的颜色
g2.setColor(Color.BLACK);
// 设置描边样式
g2.setStroke(new BasicStroke(3));
// 绘制图形shape边缘
g2.draw(shape);
g2.dispose();
ImageIO.write(bufferedImage, "jpg", new FileOutputStream("C:\\Users\\80511\\Pictures\\1_ok1.jpg"));
}