假设
试想我们需要在一个 font_max 的长度空间,任意的添加文字,但不能换行,于是,我们就要保证字体的大小能放入这个 font_max 长度,那就需要检验文字的像素长度,他可能包含汉字、英文、符号等,所以不能简单计算。
方法
// 拿到图片的 Graphics2D 画图对象
val imageGraphics: Graphics2D = image.createGraphics()
// 设置字体大小
var fontSize = info.font_size
// 设置字体 style
var font = Font("微软雅黑",Font.PLAIN ,fontSize)
// 获取文字 text 的像素长度
var textWidth = font.getStringBounds(text, imageGraphics.fontRenderContext).width.toInt()
// 只要比 font_max 大,放不下,就按 font_sub 递减,并重新比较
while (textWidth > info.font_max) {
fontSize -= info.font_sub
font = Font("黑体",Font.PLAIN , fontSize)
textWidth = font.getStringBounds(text, imageGraphics.fontRenderContext).width.toInt()
}
其中,获取字符串像素长度的方法是:
val textWidth = font.getStringBounds(text, Graphics2D.fontRenderContext).width.toInt()
Java 同理,库相同