How to draw a diamond shape in java?

2019-07-23 05:18发布

问题:

So i have to draw a diamond shape. Not a Static diamond but a diamond that i will myself drag and draw. I've used General Path to do it but it is drawing a diamond that is not straight; the diamond is bend to the left and it's not being drawn to where my mouse is pointed.

Here is my code to create the diamond shape. Can someone please help me solve this?

 private GeneralPath drawDiamond(int x1, int y1, int x2, int y2){
            
            int x = Math.min(x1, x2);
            int y = Math.min(y1, y2);

            // Gets the difference between the coordinates and

            int width = Math.abs(x1 - x2);
            int height = Math.abs(y1 - y2);
            
            Rectangle2D.Double diamond = new Rectangle2D.Double(x1,y1,width,height);
            
            GeneralPath connectedDiamond = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
            
            connectedDiamond.append(diamond, true);
            
            AffineTransform at = new AffineTransform();
            at.rotate(Math.toRadians(20));
            connectedDiamond.transform(at);
            
            return connectedDiamond;
        }

Here is my paint method:

public void paint(Graphics g) {           

            graphSettings = (Graphics2D) g;           

            graphSettings.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);

            graphSettings.setStroke(new BasicStroke(4));
           
            Iterator<Color> strokeCounter = shapeStroke.iterator();
            for (NamedShape s : shapes) {

                graphSettings.draw(s.getShape());

            }

            if (drawStart != null && drawEnd != null) {
                
                graphSettings.setComposite(AlphaComposite.getInstance(
                        AlphaComposite.SRC_OVER, 0.40f));

                graphSettings.setPaint(Color.LIGHT_GRAY);

                Shape aShape = null;
                    
                if(currentAction == 7){
                    
                    aShape = drawDiamond(drawStart.x, drawStart.y, drawEnd.x, drawEnd.y);
                }

                graphSettings.draw(aShape);
            }
        }

Can someone please help me to do this?

回答1:

How about instead of rotating a rectangle, you draw lines between 4 points inside a rectangle:

the points:

excuse my poor mspaint skills.

but i hope u get what i mean. u take the top center, middle right, bottom center and middle left points and draw lines between those (using generalPath, i think)



回答2:

It would be simpler to create diamond as polygon with vertices

(x + Width/2, y)
(x + Width, y + Height/2)
(x + Width/2, y + Height)
(x, y + Height/2)


回答3:

The 2D Shape API is actually really powerful, one of my favourite classes is the Path2D, it allows you to simply "draw" a virtual shape, for example

public class Diamond extends Path2D.Double {

    public Diamond(double width, double height) {
        moveTo(0, height / 2);
        lineTo(width / 2, 0);
        lineTo(width, height / 2);
        lineTo(width / 2, height);
        closePath();
    }

}

Now, you need to make use of an AffineTransformation or translate the Graphics context to position it, but that's not that hard

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class JavaApplication251 {

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

    public JavaApplication251() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private Diamond diamond;

        public TestPane() {
            diamond = new Diamond(100, 100);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            int x = (getWidth() - diamond.getBounds().width) / 2;
            int y = (getHeight()- diamond.getBounds().height) / 2;
            AffineTransform at = AffineTransform.getTranslateInstance(x, y);
            Shape shape = at.createTransformedShape(diamond);
            g2d.setColor(Color.YELLOW);
            g2d.fill(shape);
            g2d.setColor(Color.RED);
            g2d.draw(shape);
            g2d.dispose();
        }

    }

    public class Diamond extends Path2D.Double {

        public Diamond(double width, double height) {
            moveTo(0, height / 2);
            lineTo(width / 2, 0);
            lineTo(width, height / 2);
            lineTo(width / 2, height);
            closePath();
        }

    }

}