public void paintComponent(Graphics g) { super.paintComponent(g); if (image != null) { Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int x = (getWidth() - image.getWidth(null)) / 2; int y = (getHeight() - image.getHeight(null)) / 2; AffineTransform transform = new AffineTransform(); transform.translate(x, y); if (drawingMode == DrawingMode.LINE) { g2d.setColor(Color.BLUE); g2d.draw(new Line2D.Double(0, getHeight() / 2, getWidth(), getHeight() / 2)); } else if (drawingMode == DrawingMode.RECTANGLE) { g2d.setColor(Color.RED); g2d.draw(new Rectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1)); } else if (drawingMode == DrawingMode.ELLIPSE) { g2d.setColor(Color.GREEN); g2d.draw(new Ellipse2D.Double(0, 0, getWidth() - 1, getHeight() - 1)); } else if (drawingMode == DrawingMode.POLYGON) { if (polygonPath != null) { g2d.setColor(Color.ORANGE); g2d.draw(polygonPath); } } g2d.drawImage(image, transform, null); } } }
时间: 2024-02-14 10:21:40 浏览: 112
Show-Image-From-Storage.rar_图片显示_Java_
这段代码是 ImagePanel 类的 paintComponent 函数的实现。它继承了 JPanel 的 paintComponent 函数,用于在面板上绘制图形。在绘制之前,先调用了父类的 paintComponent 函数进行清空面板操作。然后根据当前绘制模式,绘制不同的图形。最后,通过 AffineTransform 对象对图形进行变换,将图像居中显示。如果 ImagePanel 对象包含了一个 image 对象,那么在绘制完图形之后,还会将该 image 对象绘制到面板上。
阅读全文