[原创]利用橡皮条技术画图
在进行有绘制图形功能的软件开发中都会面临橡皮条技术,所谓橡皮条技术就是在绘制过程中出现鼠标移动的记录,当鼠标松开时绘制完整的图形。下面给出一个简单的橡皮条技术的应用,该应用是在APPLET上绘制一个矩形,并且只能绘制一个矩形,这对于图象裁剪很有帮助:
/**
* @(#) xortest.java
*
* Copyright 2004 Opensource Develop Team. All rights reserved.
*/
import java.applet.Applet;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
/**
* 在APPLET上绘制一个矩形,当要进行第二次绘制时,上次绘制的矩形消失。
* @author ODT
* @see java.applet.Applet
* @since JDK 1.3
* @version 1.0 07/05/2004
*/
public class xortest extends Applet
{
Point pressed, last; // 记录图形起点和鼠标不停移动时终点坐标
boolean firstRect; // 只画一个矩形
public void init()
{
addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
firstRect = true; // 确保一个矩形
pressed = e.getPoint(); // 获得起点坐标
}
public void mouseReleased(MouseEvent e)
{
if (pressed != null)
{
Point released = e.getPoint();
Rectangle clip = new Rectangle(); // clip为最终确定的矩形
Graphics g = getGraphics();
Dimension size = getSize();
try
{
clip.x = pressed.x;
clip.y = pressed.y;
clip.width = Math.abs(released.x - pressed.x);
clip.height = Math.abs(released.y - pressed.y);
g.clearRect(0, 0, size.width, size.height);
g.drawRect(clip.x, clip.y, clip.width, clip.height); // 画最后的矩形
}
finally
{
g.dispose();
}
}
}
public void mouseClicked(MouseEvent e)
{
repaint();
}
});
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent e)
{
Point loc = e.getPoint(); // 鼠标当前位置
Graphics g = getGraphics();
try
{
g.setXORMode(getBackground()); // 设置绘图模式为XOR,橡皮条颜色为背景灰色
if (firstRect)
{
firstRect = false; // 如果有矩形的画则设置为FALSE
}
else
{
g.drawRect(pressed.x, pressed.y,
Math.abs(pressed.x - last.x),
Math.abs(pressed.y - last.y));
}
g.drawRect(pressed.x, pressed.y,
Math.abs(loc.x - pressed.x),
Math.abs(loc.y - pressed.y));
last = e.getPoint();
}
finally
{
g.dispose();
}
}
});
}
}