`
kinganpo
  • 浏览: 50959 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

图片的旋转、翻转、放大和缩小

阅读更多

图片的旋转、翻转、放大和缩小

实际上是重写paint(Graphics g)方法

drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)

放缩图片只需要改变几个int类型的参数即可

Graphics2D的方法rotate(double theta, double x, double y)可以用来旋转图片

第一个参数:旋转的角度,以弧度值为单位

第二、三个参数:分别为旋转原点的X和Y坐标

 

import java.awt.*;
import javax.swing.*;

public class RotatePicture extends JLabel implements Runnable{
	
	static Image img = new ImageIcon("D:/Backup/我的文档/水寒剑.jpg").getImage ();
	static double[] rad = {0,Math.PI/2,Math.PI,-Math.PI/2};
	double theta = 0; 

	public void paintComponent(Graphics g){
 		Graphics2D g2d = (Graphics2D)g;
 		g2d.rotate(theta,250,250);
 		g2d.drawImage(img,100,100,300,300,null);
		
	}
	
	public void run(){
						 	
		for(int i=0;;i++){
			 try{
	 		Thread.sleep (10);
	 		}catch(InterruptedException ie){}
	 		
	 		//可以通过正负号来改变旋转方向
			rotate(Math.toRadians(i));//角度转换为弧度值
		}
	}
	
	public void rotate(double d){
		theta = d;
		repaint();
	}
	
	public static void main(String[] args){
		JFrame jf = new JFrame();
		jf.setSize (500,530);	
		RotatePicture rp = new RotatePicture();	
		RotatePicture rp1 = new RotatePicture();
		MyPicture mp = new MyPicture(img,jf);
		JTabbedPane tabbedPane = new JTabbedPane();
		tabbedPane.add("任意角度旋转", rp);
		tabbedPane.add("90度翻转", rp1);
		tabbedPane.add("放大和缩小", mp);
		jf.add(tabbedPane);
		jf.setTitle ("图片的旋转、翻转、放大和缩小");
		jf.setLocationRelativeTo (null);
		jf.setVisible(true);
		jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
		Thread t1 = new Thread(rp);
		t1.start ();		
		Thread t2 = new Thread(mp);
		t2.start ();
		for(int i=0;i<4;i++){
			 try{
	 		Thread.sleep (1000);
	 		}catch(InterruptedException ie){}
			rp1.rotate(rad[i]);
			if(i==3)i=-1;
		}		
	}
			
}

class MyPicture extends Canvas implements Runnable{	
	Image img ;
	int w;
	int h;
	int width; 
	int height;
	int rate;
	boolean flag;
	
	public MyPicture(Image image,Container c){
		img = image;
		w = 50;
		h = 50;										
		width = c.getWidth();
		height = c.getHeight()-50;
		rate = 10;
		flag = false;
		System.out.println(width+","+height);
	}
	
	public void run(){
		
		while(true){
			
			if(w<=0||h<=0)
				flag = true;
	 		if(w>=width||h>=height)
	 			flag = false;
	 		
			try{
	 			Thread.sleep (100);
	 			
	 		}catch(InterruptedException ie){
	 			ie.printStackTrace ();
	 		}

	 		if(flag){
	 			w+=10;
	 			h+=10;
	 		}
	 		if(!flag){
	 			w-=10;
	 			h-=10;		 			
	 		}
			repaint();	
		}
	}
	
	public void paint(Graphics g){

		//设置图片左上角坐标		
		int x = (width-w)/2;
		int y = (height-h)/2;
		g.drawImage(img, x, y, w, h,null); 
		 
	}
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics