JAVA缓冲绘制

张开发
2026/5/4 2:30:12 15 分钟阅读
JAVA缓冲绘制
创建 BufferedImage 对象使用BufferedImage构造函数创建一个指定宽度、高度和图像类型的对象。常见的图像类型包括BufferedImage.TYPE_INT_RGB和BufferedImage.TYPE_INT_ARGB。int width 200; int height 200; BufferedImage image new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);获取 Graphics2D 对象通过getGraphics()方法获取Graphics2D对象用于绘制图形和文本。Graphics2D g2d image.createGraphics();设置绘制属性设置画笔颜色、字体等属性。例如设置颜色为红色字体为 Arial。g2d.setColor(Color.RED); g2d.setFont(new Font(Arial, Font.BOLD, 16));绘制图形或文本使用Graphics2D对象的方法绘制图形或文本。例如绘制一个矩形和一段文字。g2d.fillRect(50, 50, 100, 100); g2d.drawString(Hello, BufferedImage!, 30, 30);释放 Graphics2D 资源绘制完成后调用dispose()方法释放Graphics2D对象占用的资源。g2d.dispose();保存或显示图像将BufferedImage保存为文件或显示在界面上。例如保存为 PNG 文件。File output new File(output.png); ImageIO.write(image, png, output);处理异常捕获可能出现的IOException确保程序健壮性。try { ImageIO.write(image, png, output); } catch (IOException e) { e.printStackTrace(); }创建 BufferedImage 对象并绘制白色背景的代码示例展示了 Java 中缓冲图像的基本操作流程// 创建宽度1800像素、高度1600像素的RGB图像 BufferedImage bimg new BufferedImage(1800, 1600, BufferedImage.TYPE_INT_RGB); // 获取图像的图形上下文画笔 Graphics bg bimg.getGraphics(); // 设置绘制颜色为白色并填充整个图像 bg.setColor(Color.WHITE); bg.fillRect(0, 0, 1800, 1600);关键参数说明图像类型参数 原始代码中的数字2对应的是BufferedImage.TYPE_INT_RGB表示24位RGB颜色空间8位红、8位绿、8位蓝。更规范的写法是直接使用常量BufferedImage.TYPE_INT_RGB不透明RGBBufferedImage.TYPE_INT_ARGB带透明通道的RGBBufferedImage.TYPE_BYTE_GRAY灰度图像图形绘制注意事项使用完Graphics对象后应当显式释放资源bg.dispose();对于更复杂的绘图操作可以使用Graphics2DGraphics2D g2d bimg.createGraphics(); // 开启抗锯齿 g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);图像保存示例将缓冲图像保存为文件try { ImageIO.write(bimg, PNG, new File(output.png)); } catch (IOException e) { e.printStackTrace(); }在画图板中的函数public void mouseMoved(MouseEvent e) { int x e.getX(); int y e.getY(); if (n 1 type.equals(选择)) { // 选择图形功能 System.out.println(选择); BufferedImage bimg new BufferedImage(1800, 1600, 2); Graphics bg bimg.getGraphics(); bg.setColor(Color.WHITE); bg.fillRect(0, 0, 1800, 1600); int count 0; for (int i 0; i index; i) { MShape shape shapeList[i]; if (shape.type.equals(签字笔)) { NPointShape nShape (NPointShape) shape; int ic 0; for (int j 0; j nShape.pointList.size(); j) { Point p1 nShape.pointList.get(j); if (Math.abs(p1.x - x) 3 Math.abs(p1.y - y) 3) { nShape.isSelected 1; shape.color2 new Color(114, 218, 18, 50); count; ic; System.out.println(匹配成功); } } if (ic 0) { nShape.isSelected 0; } } else { int sx Math.min(shape.x1, shape.x2); int sy Math.min(shape.y1, shape.y2); int sw Math.abs(shape.x1 - shape.x2); int sh Math.abs(shape.y1 - shape.y2); if (x sx x sx sw y sy y sy sh count 0) { shape.isSelected 1; shape.color2 new Color(114, 218, 18, 50); count; } else { shape.isSelected 0; } } shape.drawShape(bg); } g.drawImage(bimg, 0, 0, null); } }

更多文章