[java] 绘图

Graphics类及其子类Graphics2D

  • 它相当于组件的绘图环境,利用它可以进行各种绘图操作
  • 获得Graphics对象常有两种方法
    使用组件的getGraphics()方法
    常用Canvas及JComponent对象来进行绘图,可以Override Canvas的paint(Graphics g)方法,或JComponent的paintComponent(Graphic g)方法
    示例要点:继承JPanel,重写paintComponent();setDoubleBuffered(true);//设置双缓冲
    ``` … SwingUtilities.invokeLater(()->{ JFrame f = new JFrame(“Draw”); f.setLayout(new GridLayout(3,4)); for(int i = 0; i < 16; i ++){ f.add(new FlowerPanel(i)); } f.setSize(400,300); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); });//main函数中 …

class FlowerPanel extends JPanel{ int N = 16; public FlowerPanel(int N){ this.N = N; this.setDoubleBufferd(true); }

@Override proteacted void paintComponent(Graphics g){ super.paintComponent(g); double x0 = getSize().width/2; double y0 = getSize().height/2; double h = Math.min(x0, y0); if(h > 10) h -= 4;

g.setColor(Color.blue);
for(double th = 0; th < 10; th += 0.003){
  double r = Math.cos(N*th)*h;
  double x = r * Math.cos(th) + x0;
  double y = r * Math.sin(th) + y0;
  g.drawOval((int)x-1, (int)y-1, 3, 3);
}

...

} }


## 显示图像
- 利用Graphics类的drawImage()方法显示图像  
示例:

public class DrawImageAnimator extends JPanel{ public DrawImageAnimator(){ try{ final URI dir = getClass().getResource(“.”).toURI();//得到当前路径 System.out.println(dir); String [] files = new File(dir).list(); int num = files.length<=10? files.length : 10; images = new java.util.ArrayList(); for(int i = 0; i < num; i ++){ if(files[i].toLowerCase().endsWith(".png") || files[i].toLowerCase().endsWith(".jpg") || files[i].toLowerCase().endsWith(".gif")){ Image img = javax.imageio.ImageIO.read( new File(new File(dir), files[i])); images.add(img);//用ImageIO读取当前路径下的多个图片文件 } } }catch(Exception ex){ex.printStackTrace();} thread = new MyThread(); thread.start(); }

@Override public void paintComponent(Graphics g){ super.paintComponent(g); if(images == null) return; Image img = images.get(curImage); g.drawImage(img, 0, 0, this); }

private java.util.List images; private volatile int curImage; private boolean bStop; private MyThread thread; class MyThread extends Thread{ public void run(){ while(!bStop){ SwingUtilities.invokeLater(()->{ System.out.println("==" + curImage); repaint(); });

    try{sleep(1000);}catch(InterruptedException e){}
    curImage ++;
    if(curImage == images.size()) curImage = 0;
  }
}   } } ```

图像生成

  • BufferedImage类是Image的子类
  • BufferedImage对象的getGraphics()可以得到一个绘图对象
  • ImageIO类的read及write方法
  • 示例:
    创建一个BufferdImage对象
    使用该对象的getGraphics()得到绘图对象
    使用Graphics的drawLine方法来画图
    保存为文件,或供其他对象绘制
    ``` public static void main(String[] args) throws Exception{ … BufferdImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); drawInBufferedImage(image); … ImageIO.write(image, “JPEG”, file); }//IO过程

public static void drawInBufferdImage(BufferedImage image){ … Graphics g = image.getGraphics();//get一个Graphics对象进行绘制 g.setColor(Color.white); …//具体的绘制过程 } ```

Written on December 26, 2022