/** Java 绘图相关技术的学习*Graphics类相关技术知识:
1.图像的几何变换图像翻转:使用另一个重载的drawImage(Image img,int x_1,int y_1,目标矩形的第一坐标int x_2,int y_2,目标矩形的第二坐标int x1,int y1,源矩形的第一坐标int x2,int y2,源矩形的第二坐标ImageObserver observer)利用非缩放的图像来呈现缩放的矩形,动态执行所需的缩放。图像旋转:利用Graphics2D类的rotate()结合Math.toRadians()方法来实现。图像错切:利用Graphics2D类的shear(double x,double y)结合Math.toRadians()方法来实现。*/
package app;import java.awt.*;
import javax.swing.*;
import java.net.*;
import java.awt.event.*;//包含有main函数的类的类名和文件名必须保持一致
public class DigitalImage extends JFrame
{private static final long serialVersionUID = 1L;private final int width = 500;private final int height =500;private Image img;private int imgW = 500;private int imgH =500;private int x1=0, y1=0;private int x2 = imgW, y2 = imgH;private Canvas canvas = null;private JMenuBar menuBar = null;//图片旋转角度private int m_angle = 0;public DigitalImage(){super();init();}private void init(){this.setSize(width, height);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置窗体面板为绘图面板对象canvas = new Canvas();this.setContentPane(canvas);this.setTitle("绘图");//获取图片URL url = DigitalImage.class.getResource("lena.jpg");img = Toolkit.getDefaultToolkit().getImage(url);//创建菜单栏对象menuBar = new JMenuBar();this.setJMenuBar(menuBar);//创建菜单JMenu menu = new JMenu("几何变换");menuBar.add(menu);//创建菜单项JMenuItem Item1 = new JMenuItem("图像旋转");Item1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){Graphics2D g = (Graphics2D) getGraphics();m_angle = m_angle+15;g.rotate(Math.toRadians(m_angle));//此处画板对象和框架对象存在数据封装,在框架里需要操作画板需要传入指针g.drawImage(img, 0, 0, imgW, imgH, canvas); }});menu.add(Item1);//创建菜单JMenu Item2 = new JMenu("图像翻转");menu.add(Item2);//翻转方向菜单项JMenuItem childMenu1 = new JMenuItem("水平");childMenu1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){//水平方向上,仅更改源矩形和目标矩形的x方向映射关系,即x的值。Graphics g = getGraphics();x1 = Math.abs(x1 - imgW);x2 = Math.abs(x2 - imgW);g.drawImage(img,0,0 ,imgW,imgH, x1,y1,x2,y2,canvas);}});JMenuItem childMenu2 = new JMenuItem("垂直");childMenu2.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){//垂直方向上,仅更改源矩形和目标矩形的y方向映射关系,即y的值。Graphics g = getGraphics();y1 = Math.abs(y1 - imgH);y2 = Math.abs(y2 - imgH);g.drawImage(img,0,0 ,imgW,imgH, x1,y1,x2,y2,canvas);}});Item2.add(childMenu1);Item2.add(childMenu2);//错切变换JMenuItem Item3 = new JMenuItem("图像错切");Item3.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e){Graphics2D g = (Graphics2D)getGraphics();g.shear(0.3,0);g.drawImage(img, 0, 0, imgW, imgH, canvas);}});menu.add(Item3);}public static void main(String[] args){new DigitalImage().setVisible(true);}class Canvas extends JPanel{private static final long serialVersionUID = 1678373920467727747L;public void paint(Graphics g){super.paint(g);g.drawImage(img, 0,0, width, height, this);}}
}