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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值