JAVA Graphics2D 使用记录

画线条

/**
 * 卡片尺寸
 */
int width = 500;
int height = 300;
BufferedImage outImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR_PRE);
Graphics2D card = outImage.createGraphics();
// 画四条实线边框
card.setStroke(new BasicStroke(1));
card.drawLine(0, 0, width, 0);
card.drawLine(0, 0, 0, height);
card.drawLine(0, height - 1, width - 1, height - 1);
card.drawLine(width - 1, 0, width - 1, height - 1);
  • (x1,y1)与(x2,y2)实际为两个点,所画的线条就是两个点的连线

写文本

// 字体设置
card.setFont(new Font("微软雅黑", Font.BOLD, 14));
// 设置画笔颜色
card.setPaint(Color.RED);
card.drawString("我是红色微软雅黑大小为14的加粗字体", 20, 20);
card.setFont(new Font("宋体", Font.PLAIN, 17));
card.setPaint(Color.BLACK);
card.drawString("我是黑色宋体大小为17的字体", 20, 50);

写可设置字体间距的文本

/**
     * 写有间距的文字
     * @param str 文字内容
     * @param x 开始x位置
     * @param y 开始y位置
     * @param rate 间距(x倍)
     * @param g Graphics对象
     */
    public static void myDrawString(String str, int x, int y, double rate, Graphics g) {
        String tempStr;
        int orgStringWight = g.getFontMetrics().stringWidth(str);
        int orgStringLength = str.length();
        int tempx = x;
        int tempy = y;
        while (str.length() > 0) {
            tempStr = str.substring(0, 1);
            str = str.substring(1);
            g.drawString(tempStr, tempx, tempy);
            tempx = (int) (tempx + (double) orgStringWight / (double) orgStringLength * rate);
        }
    }

添加图片

// 将logo画到画板上
BufferedImage img = ImageIO.read(this.getClass().getResourceAsStream(logoPath));
card.drawImage(img.getScaledInstance(64, 18, Image.SCALE_DEFAULT), 31, 23, null);

剪切图片

card.setClip(new RoundRectangle2D.Double(0, 0, width, height, 0, 0));
card.dispose();
outImage.flush();

消除抗锯齿

card.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

导出图片

BufferedImage image = outImage;

try {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.flush();
    ImageIO.write(image, "png", baos);
    BufferedImage newBufferedImage = new BufferedImage(
            width, height,
            BufferedImage.TYPE_INT_RGB);
    newBufferedImage.createGraphics().drawImage(image, 0, 0, Color.WHITE, null);
    ImageIO.write(newBufferedImage, "png",
            new File(fileName));
    baos.close();
    image.flush();
} catch (IOException e) {
    e.printStackTrace();
}
posted @ 2023-02-13 14:22  云の彼端  阅读(147)  评论(0)    收藏  举报