Image srcImg = null;
try {
srcImg = ImageIO.read(inputStream);
} catch (IOException e) {
log.info("occur getGraphics2D fail",e);
throw new ImageException(ResponseCode.GEN_IMAGE_ERROR,e);
}
BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = imageRender.getGraphics2D() ; //
Font font = new Font(fontFamily,fontWeight,fontSize());//字体
g2.setFont(font);
FontMetrics fm = g2.getFontMetrics();//
int totalWidth = buffImg().getWidth()//图片的宽度
int fontLength = getBestFontNumber(totalWidth,fm,g2,itemName,itemName.length());
private int getBestFontNumber(int totalWidth,FontMetrics fm, Graphics2D g2, String text,int length){
Rectangle2D rc = fm.getStringBounds(text.substring(0,length), g2);
double itemNameWidth = rc.getWidth();//计算出文字的宽度
//比文字宽度要长
//30 图片左侧的留白
if(totalWidth - itemNameWidth < 30 ){//行宽不足容纳下文字则减少文字长度再计算
length--;
return getBestFontNumber(totalWidth, fm, g2, text, length);
}
return length;
}