java中的画笔效果

时间:2010-08-26 07:40:40

标签: java graphics

我想在刷子中实现java的效果,鼠标返回点,移动鼠标更快,线条更细。

1 个答案:

答案 0 :(得分:2)

这是一个演示你想要实现的目标的程序。

这个程序并不完美,但是应该让你开始尝试构建它。

import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;

public class PaintBrush {

    JFrame f;
    Canvas c;
    int x=-1, y=-1;

    public PaintBrush() {
        f = new JFrame();
        f.setSize(600, 400);
        c = new Canvas() {
            public void paint(Graphics g) {
                // super.paint(g);
            }
        };
        f.getContentPane().add(c);
        c.addMouseMotionListener(new MouseMotionListener() {

            @Override
            public void mouseMoved(MouseEvent e) {
                // TODO Auto-generated method stub
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                if(x==-1){
                    x = e.getX();
                    y = e.getY();
                }
                int diffx =  Math.abs(x - e.getX());
                int diffy =  Math.abs(y - e.getY());
                System.out.println("diffx:"+diffx+"\t"+"diffy:"+diffy);
                int speed = (int) Math.sqrt((diffx + diffy));
                if(speed>1){
                    c.getGraphics().fillOval(x, y, 20-speed*2, 20-speed*2);
                }else {
                    c.getGraphics().fillOval(x, y, 20, 20);
                }
                System.out.print("Speed:"+speed + "\t");
                System.out.println("x:"+e.getX());
                x = e.getX();
                y = e.getY();
            }
        });
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        new PaintBrush();

    }