使用秋千在图像上绘制形状

时间:2015-05-14 12:33:53

标签: java

这是我的代码。我在图像上绘制矩形,椭圆形线条。画一条线很好。我可以绘制矩形,但在鼠标拖动时不可见。如何修改此程序以在鼠标拖动时显示矩形。如何为此程序提供橡皮擦,以便在保留背景图像的同时仅擦除形状。

package com.sobis.hindalco.bean

import java.awt.*;
import java.awt.RenderingHints.Key;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriter;

public class ImageEdit extends JFrame{

    private BufferedImage originalImage;
    private BufferedImage canvasImage;
    private JPanel gui;
    private Color color = Color.WHITE;
    private JLabel output = new JLabel("You DooDoodle!");
    BufferedImage image=null;
    private BufferedImage colorSample = new BufferedImage(
            16,16,BufferedImage.TYPE_INT_RGB);
    private JLabel imageLabel;
    private int activeTool;
    public static final int RECTANGLE_TOOL = 0;
    public static final int DRAW_TOOL = 1;
    public static final int TEXT_TOOL = 2;
    public static final int ERASER_TOOL = 3;
    public static final int OVAL_TOOL = 4;
    Point startDrag, endDrag;
    private Point selectionStart;
    private Rectangle selection;
    private boolean dirty = false;
    // private Stroke stroke = new BasicStroke(
    //   3,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND,1.7f);
    private RenderingHints renderingHints;


    public JComponent getGui() {
        if(gui==null) {
            Map<Key, Object> hintsMap = new
                    HashMap();
            hintsMap.put(RenderingHints.KEY_RENDERING,
                    RenderingHints.VALUE_RENDER_QUALITY);
            hintsMap.put(RenderingHints.KEY_DITHERING,
                    RenderingHints.VALUE_DITHER_ENABLE);
            hintsMap.put(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            renderingHints = new RenderingHints(hintsMap);
            setImage(new BufferedImage(320,240,BufferedImage.TYPE_INT_RGB));
            gui = new JPanel(new BorderLayout(4,4));
            gui.setBorder(new EmptyBorder(5,3,5,3));
            JPanel imageView = new JPanel(new GridBagLayout());
            imageView.setPreferredSize(new Dimension(480,320));
            imageLabel = new JLabel(new ImageIcon(canvasImage));
            JScrollPane imageScroll = new JScrollPane(imageView);
            imageView.add(imageLabel);
            imageLabel.addMouseMotionListener(new
                    ImageMouseMotionListener());
            imageLabel.addMouseListener(new ImageMouseListener());
            gui.add(imageScroll,BorderLayout.CENTER);

            JToolBar tb = new JToolBar();
            tb.setFloatable(false);
            JButton colorButton = new JButton("Color");
            colorButton.setMnemonic('o');            colorButton.setToolTipText("Choose a Color");

            ActionListener colorListener = new ActionListener() {




                public void actionPerformed(ActionEvent arg0) {
                    Color c = JColorChooser.showDialog(
                            gui, "Choose a color", color);
                    if(c!=null) {
                        setColor(c);
                    }
                }



            };


            colorButton.addActionListener(colorListener);
            colorButton.setIcon(new ImageIcon(colorSample));
            tb.add(colorButton);
            setColor(color);
            // final SpinnerNumberModel strokeModel =
            //     new SpinnerNumberModel(3,1,16,1);
            ///   JSpinner strokeSize = new JSpinner(strokeModel);

            ChangeListener strokeListener = new ChangeListener() {

                @Override
                public void stateChanged(ChangeEvent arg0) {
                }
            };

            tb.addSeparator();
            ActionListener clearListener = new ActionListener() {

                public void actionPerformed(ActionEvent arg0) {
                    int result = JOptionPane.OK_OPTION;
                    if(dirty) {
                        result = JOptionPane.showConfirmDialog(
                                gui, "Erase the current painting?");
                    }

                    if(result==JOptionPane.OK_OPTION) {
                        clear(canvasImage);
                    }
                }

            };
            JButton clearButton = new JButton("Clear");
            tb.add(clearButton);
            clearButton.addActionListener(clearListener);
            gui.add(tb, BorderLayout.PAGE_START);
            JToolBar tools = new JToolBar(JToolBar.VERTICAL);
            tools.setFloatable(false);
            JButton crop = new JButton("Crop");
            final JRadioButton select = new JRadioButton("Rectangle", true);
            final JRadioButton eraser = new JRadioButton("Eraser", true);
            final JRadioButton draw = new JRadioButton("Draw");
            final JRadioButton text = new JRadioButton("Text");




            final JRadioButton oval = new JRadioButton("oval");
            tools.add(select);
            tools.add(draw);
            tools.add(text);
            tools.add(eraser);
            tools.add(oval);
            ButtonGroup bg = new ButtonGroup();
            bg.add(select);
            bg.add(text);
            bg.add(draw);
            bg.add(eraser);
            bg.add(oval);

            ActionListener toolGroupListener = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent ae) {
                    if(ae.getSource()==select) {
                        activeTool = RECTANGLE_TOOL;
                    }else if(ae.getSource()==draw) {
                        activeTool = DRAW_TOOL;
                    }else if(ae.getSource()==text) {
                        activeTool = TEXT_TOOL;
                    }else if(ae.getSource()==eraser) {
                        activeTool = ERASER_TOOL;
                    }else if(ae.getSource()==oval) {
                        activeTool = OVAL_TOOL;
                    }
                }

            };
            select.addActionListener(toolGroupListener);
            draw.addActionListener(toolGroupListener);
            text.addActionListener(toolGroupListener);
            eraser.addActionListener(toolGroupListener);
            oval.addActionListener(toolGroupListener);
            gui.add(tools, BorderLayout.LINE_END);
            gui.add(output,BorderLayout.PAGE_END);
            clear(colorSample);
            clear(canvasImage);
        }

        return gui;
    }

    /** Clears the entire image area by painting it with the current color. */
    public void clear(BufferedImage bi) {

        try{
            image = ImageIO.read(new File("D:\\images.jpeg"));
        }catch(Exception e){
        }
        this.originalImage = image;
        int w = image.getWidth();
        int h = image.getHeight();
        canvasImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = this.canvasImage.createGraphics();
        g.setRenderingHints(renderingHints);
        g.drawImage(image, 0, 0, gui);
        g.dispose();
        selection = new Rectangle(0,0,w,h);

        if(this.imageLabel!=null) {
            imageLabel.setIcon(new ImageIcon(canvasImage));
            this.imageLabel.repaint();
        }



        if(gui!=null) {
            gui.invalidate();
        }
    }

    public void setImage(BufferedImage image1) {

        try{
            image = ImageIO.read(new File("D:\\images.jpeg"));
        }catch(Exception e){
        }
        this.originalImage = image;
        int w = image.getWidth();
        int h = image.getHeight();
        canvasImage = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = this.canvasImage.createGraphics();
        g.setRenderingHints(renderingHints);
        g.drawImage(image, 0, 0, gui);
        g.dispose();
        selection = new Rectangle(0,0,w,h);
        if(this.imageLabel!=null) {
            imageLabel.setIcon(new ImageIcon(canvasImage));
            this.imageLabel.repaint();
        }
        if(gui!=null) {
            gui.invalidate();
        }
    }

    /** Set the current painting color and refresh any elements needed. */
    public void setColor(Color color) {

        this.color = color;
        clear(colorSample);
    }

    private JMenu getFileMenu(boolean webstart){

        JMenu file = new JMenu("File");
        file.setMnemonic('f');
        //JMenuItem newImageItem = new JMenuItem("New");
        //newImageItem.setMnemonic('n');
        ActionListener newImage = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {

                BufferedImage bi = new BufferedImage(
                        360, 300, BufferedImage.TYPE_INT_ARGB);
                clear(bi);
                setImage(bi);
            }
        };


        if(webstart) {
            //TODO Add open/save functionality using JNLP API
        }else{
            //TODO Add save functionality using J2SE API
            file.addSeparator();
            ActionListener saveListener = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {

                    JFileChooser ch = getFileChooser();
                    int result = ch.showSaveDialog(gui);
                    if(result==JFileChooser.APPROVE_OPTION ) {
                        try {
                            File f = ch.getSelectedFile();
                            ImageIO.write(ImageEdit.this.canvasImage, "png",
                                    f); ImageEdit.this.originalImage =
                                    ImageEdit.this.canvasImage;
                            dirty = false;
                        } catch (IOException ioe) {
                            showError(ioe);
                            ioe.printStackTrace();
                        }
                    }
                }
            };
            JMenuItem saveItem = new JMenuItem("Save");
            saveItem.addActionListener(saveListener);
            saveItem.setMnemonic('s');
            file.add(saveItem);
        }

        if(canExit()) {
            ActionListener exit = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent arg0) {
                    // TODO Auto-generated method stub
                    System.exit(0);
                }
            };
            JMenuItem exitItem = new JMenuItem("Exit");
            exitItem.setMnemonic('x');
            file.addSeparator();
            exitItem.addActionListener(exit);
            file.add(exitItem);
        }
        return file;
    }

    private void showError(Throwable t) {



        JOptionPane.showMessageDialog(
                gui,
                t.getMessage(),
                t.toString(),
                JOptionPane.ERROR_MESSAGE);
    }
    JFileChooser chooser = null;


    public JFileChooser getFileChooser() {

        if(chooser==null) {
            chooser = new JFileChooser();
            FileFilter ff= new FileNameExtensionFilter( "myfiles","jpg",

                    "jpeg","png");

            chooser.addChoosableFileFilter(ff);
        }
        return chooser;
    }

    public boolean canExit() {

        boolean canExit = false;
        SecurityManager sm = System.getSecurityManager();

        if(sm==null) {
            canExit = true;
        }else{
            try {
                sm.checkExit(0);
                canExit = true;
            } catch(Exception stayFalse) {
            }
        }
        return canExit;
    }

    public JMenuBar getMenuBar(boolean webstart){

        JMenuBar mb = new JMenuBar();
        mb.add(this.getFileMenu(webstart));
        return mb;
    }

    public  void openPanel() {

        Runnable r = new Runnable() {

            @Override
            public void run() {

                try {
                    UIManager.setLookAndFeel(
                            UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                    // use default
                }

                ImageEdit bp = new ImageEdit();
                JFrame f = new JFrame("Image Editing");
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);
                f.setContentPane(bp.getGui());
                f.setJMenuBar(bp.getMenuBar(false));
                f.pack();
                f.setMinimumSize(f.getSize());
                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }

    public void text(Point point) {

        String text = JOptionPane.showInputDialog(gui, "Text to add",
                "Text");

        if(text!=null) {
            Graphics2D g = this.canvasImage.createGraphics();
            g.setRenderingHints(renderingHints);
            g.setColor(this.color);
            // g.setStroke(stroke);
            int n = 0;
            g.drawString(text,point.x,point.y);
            g.dispose();
            this.imageLabel.repaint();
        }
    }

    public void draw(Point point) {

        Graphics2D g = this.canvasImage.createGraphics();
        g.setRenderingHints(renderingHints);
        g.setColor(this.color);
        int n = 0;
        g.drawLine(point.x, point.y, point.x+n, point.y+n);
        g.dispose();
        this.imageLabel.repaint();
    }

    public void drawRectangle() {

        Graphics2D g = this.canvasImage.createGraphics();
        g.setRenderingHints(renderingHints);
        g.setColor(this.color);
        g.drawRect(Math.min(startDrag.x, endDrag.x), Math.min(
                startDrag.y,endDrag.y), Math.abs(startDrag.x -endDrag.x),
                Math.abs(startDrag.y - endDrag.y));
        this.imageLabel.repaint();
    }

    public void eraser(Point point) {

        Graphics2D g = this.canvasImage.createGraphics();
        g.setRenderingHints(renderingHints);
        g.setColor(this.color);
        int n = 0;
        g.clearRect(point.x, point.y, point.x+n, point.y+n);
        g.dispose();
        this.imageLabel.repaint();
    }

    public void oval() {

        Graphics2D g = this.canvasImage.createGraphics();
        g.setRenderingHints(renderingHints);
        g.setColor(this.color);
        //   g.setStroke(stroke);
        int n = 0;
        // g.clearRect(x1,y1,x2,y2);
        g.dispose();
        this.imageLabel.repaint();
    }

    class ImageMouseListener extends MouseAdapter {

        @Override
        public void mousePressed(MouseEvent arg0) {

            if(activeTool==ImageEdit.TEXT_TOOL) {
                // TODO
                text(arg0.getPoint());
            }else  if(activeTool==ImageEdit.ERASER_TOOL) {
                // TODO
                eraser(arg0.getPoint());
            }else  if(activeTool==ImageEdit.ERASER_TOOL) {
                // TODO
                draw(arg0.getPoint());
            }else{
                startDrag = new Point(arg0.getX(), arg0.getY());
                endDrag = startDrag;
            }
        }

        @Override
        public void mouseReleased(MouseEvent arg0) {

            if(activeTool==ImageEdit.RECTANGLE_TOOL) {
                endDrag = new Point( arg0.getX(), arg0.getY());
                drawRectangle();
            }
        }
    }

    class ImageMouseMotionListener implements MouseMotionListener {

        @Override
        public void mouseDragged(MouseEvent arg0) {

            reportPositionAndColor(arg0);
            endDrag = new Point( arg0.getX(), arg0.getY());
            if(activeTool==ImageEdit.DRAW_TOOL) {
                draw(arg0.getPoint());
            }else if(activeTool==ImageEdit.RECTANGLE_TOOL) {
                endDrag = new Point( arg0.getX(), arg0.getY());
            }else if(activeTool==ImageEdit.OVAL_TOOL) {
                oval();
            }
        }
        @Override
        public void mouseMoved(MouseEvent arg0) {

            reportPositionAndColor(arg0);
        }
    }

    private void reportPositionAndColor(MouseEvent me) {

        String text = "";
        if(activeTool==ImageEdit.RECTANGLE_TOOL) {
            text += "Selection (X,Y:WxH): " +
                    (int)selection.getX() +
                    "," +
                    (int)selection.getY() +
                    ":" +
                    (int)selection.getWidth() +
                    "x" +
                    (int)selection.getHeight();
        }else{
            text += "X,Y: " + (me.getPoint().x+1) + "," +
                    (me.getPoint().y+1);
        }
        output.setText(text);
    }
}

1 个答案:

答案 0 :(得分:0)

  

如何修改此程序以在鼠标拖动时显示矩形。

您可以查看Custom Painting Approaches

当您按住鼠标并拖动它时,两种方法都会绘制一个临时矩形。基本上你需要处理mousePressed来跟踪起始点,mouseDragged来获取当前鼠标点(和repaint())和mouseReleased来保存实际的Rectangle。

  

如何为此程序提供橡皮擦,以便在保留背景图像的同时仅删除形状。

您可能希望使用上述链接中的Draw On Component方法。然后,您将遍历形状列表以确定形状是否包含鼠标点。如果是这样,那么您将从列表中删除形状。所以这只能擦除整个形状。