Java 利用Graphics2D在图片上画出竖排文字与横排文字

时间:2021-11-12 21:55:46
package com;


import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Random;


import javax.imageio.ImageIO;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;


public class TestQrCode {


public static void main(String[] args) {
String path = TestQrCode.createQrcode("gsdw—2017");
File f = new File(path);
new TestQrCode().addtext_QRCode(f,"");

}


public void addtext_QRCode(File qrPic, String test) {
try {
if (!qrPic.isFile()) {
System.out.print("file not find !");
System.exit(0);
}


/**
* 读取二维码图片,并构建绘图对象
*/
BufferedImage image = ImageIO.read(qrPic);
Graphics2D g = image.createGraphics();
//设置字体颜色
g.setColor(Color.BLACK);
//设置字体为系统字体
g.setFont(g.getFont());
//画竖排文字
int x=20,y=50;
String str = "激光与光纤通讯演示仪";
addText_ShuPaiWenzi(x,y,str,g);
int k=50,j=270;
addText_hengpaiwenzi(k,j,str,g);
g.dispose();
ImageIO.write(image, "jpeg", new File("F:\\qrcode\\"+"133.jpg"));
} catch (Exception e) {
e.printStackTrace();
}finally{
if(qrPic!=null){
qrPic.delete();
}
}
}

/**
* 横排文字
* @param x
* @param y
* @param str
* @param g
*/
public void addText_hengpaiwenzi(int x,int y,String str,Graphics2D g){
g.drawString(str, x, y);

}


public void addText_ShuPaiWenzi(int x,int y,String str,Graphics2D g){


int strlength = str.length();
//获取字体宽度
int t = g.getFontMetrics().stringWidth("str");
//竖排文字
for(int i=0;i<strlength;i++){

g.drawString(String.valueOf(str.charAt(i)), x, y);
y +=t;
}
}


}