Fill a Polygon in Java

0

I'm doing a little program in which I have come across a detail when trying to draw a polygon in a JPanel in which I want the color of its edges to be fully configurable as well as its background. I made an attempt with the following code segment:

//Coloca color de arista y dibuja figura
            g.setColor(Color.BLACK);
            g.drawPolygon(figura);
//Coloca color de fondo y rellena la figura
            g.setColor(Color.WHITE);
            g.fillPolygon(figura);

Note. To avoid extending the code further, the variable figure is of the Polygon type.

The previous code I have also adapted it in a very similar way for figures without vertices like a circle.

            g.setColor(figu.getColorArista());
            g.drawOval(figu.getCentro().x-radio,figu.getCentro().y-radio,radio*2,radio*2);
            g.setColor(figu.getColorFondo());
            g.fillOval(figu.getCentro().x-radio,figu.getCentro().y-radio,radio*2,radio*2);

Without further extending the program .... My results have not been quite good, resulting in something like the following:

As you can see, you can see the change of color only on certain edges of the figure, this depends on the shape of the figure. I thought about making the whole figure of the same color and then simply draw some lines that would unite all the vertices with the color of the edges so that they overlap the edge of the figure. I would appreciate if you shared a more formal or other form than the one that could give me solution to this problem, thank you.

    
asked by Sergio Cortez 25.11.2018 в 04:39
source

1 answer

0

It is most likely to use the fill attributes first (solid figures) and then draw with the draw (contoured figures):

//Coloca color de fondo y rellena la figura
g.setColor(Color.WHITE);
g.fillPolygon(figura);
//Coloca color de arista y dibuja figura
g.setColor(Color.BLACK);
g.drawPolygon(figura);

In that order of ideas you would get something like this:

If you take advantage of the use of Graphics2D you can, if you wish, highlight the overlap of the 'edges' of the figure with the help of the setStroke() method and improve the rendering with setRenderingHints() :

Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
      RenderingHints.VALUE_ANTIALIAS_ON)); //Mejor Renderizado.
g2.setStroke(new BasicStroke(3));          //Grosor de Trazado.
g2.setColor(figu.getColorFondo());
g2.fillOval(figu.getCentro().x-radio,figu.getCentro().y-radio,radio*2,radio*2);
g2.setColor(figu.getColorArista());
g2.drawOval(figu.getCentro().x-radio,figu.getCentro().y-radio,radio*2,radio*2);

With which you get, for example:

Both, both RenderingHints() as BasicStroke() are in java.awt

    
answered by 26.11.2018 / 02:21
source