从Jframe创建图像

问题描述 投票:0回答:2

我使用JFrame和秋千创建了一个饼图。但是我想将饼图转换为图像并保存在桌面/本地路径中。但不知道如何使用JFrame Pie创建图像。

package test;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

class Main1 {
  double value;
  Color color;


  public Main1(double value, Color color) {
    this.value = value;
    this.color = color;
  }
}

class MyComponent extends JComponent {
    Main1[] slices = { new Main1(1, Color.black), new Main1(1, Color.green),
      new Main1(1, Color.yellow), new Main1(1, Color.red) };

  MyComponent() {

  }
  public void paint(Graphics g) {
    drawPie((Graphics2D) g, getBounds(), slices);
  }

  void drawPie(Graphics2D g, Rectangle area, Main1[] slices) {
    double total = 0.0D;
    for (int i = 0; i < slices.length; i++) {
      total += slices[i].value;
    }

    double curValue = 0.0D;
    int startAngle = 0;
    for (int i = 0; i < slices.length; i++) {
      startAngle = (int) (curValue * 360 / total);
      int arcAngle = (int) (slices[i].value * 360 / total);

      g.setColor(slices[i].color);
      g.fillArc(area.x, area.y, area.width, area.height, startAngle, arcAngle);
      curValue += slices[i].value;
    }
  }
}

public class Main2 {
     public JPanel contentPane;
  public static void main(String[] argv) {
    JFrame frame = new JFrame();
    frame.getContentPane().add(new MyComponent());
    frame.setSize(300, 200);
    frame.setVisible(true);   
  }

}
java image swing jcomponent
2个回答
3
投票

创建Swing组件的图像的基本逻辑是:

Dimension d = component.getSize();
BufferedImage image = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
component.print( g2d );
g2d.dispose();
ImageIO.write(image, ".jpg", new File(...));

[您也可以签出Screen Image类以获取方便的方法,这些方法可以绘制整个框架,框架上的组件或框架上的组件的矩形。

请注意,以上建议假设您正确进行了自定义绘画,这意味着您:

  1. 扩展JPanel
  2. 覆盖paintComponent(...),而不是paint(...)
  3. 调用super.paintComponent(...)

如果要扩展JComponent,则需要:

  1. 覆盖paintComponent(...);
  2. 在调用drawPie(...)方法之前先填充组件的背景

1
投票

但是我想将饼图转换为图像

创建BufferedImage并对其进行绘制

BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bi.createGraphics();
new MyComponent().drawPie(g2d, new Rectangle(0, 0, 200, 200), slices);
g2d.dispose();

并保存在桌面/本地路径中

使用ImageIO

ImageIO
© www.soinside.com 2019 - 2024. All rights reserved.