How to draw a triangle with border with Java Graph

2019-09-20 21:40发布

问题:

I'm trying to draw a triangle with a border using the Graphics.drawPolygon() method

The triangle is properly drawn, but how can I calculate the 3 points of the border?

I already did it with a circle, but I can't seem to find a solution for triangle.

A requirement of the instructor as that it cannot use Graphics2D.

My code:

if (xPoints != null && yPoints != null) {
    int[] nXPoints = new int[] { xPoints[0] - borderThickness, xPoints[1] - borderThickness,
            xPoints[2] - borderThickness };
    int[] nYPoints = new int[] { yPoints[0] - borderThickness, yPoints[1] - borderThickness,
            yPoints[2] - borderThickness };

    g.setColor(borderColor);
    g.fillPolygon(nXPoints, nYPoints, 3);

    g.setColor(fillColor);
    g.fillPolygon(xPoints, yPoints, 3);
}

Edit: Expected result

回答1:

Use the Graphics methods drawPolygon() to render the outline and fillPolygon() to fill its interior; both have the required signature, as shown here.

Because "operations that draw the outline of a figure operate by traversing an infinitely thin path between pixels with a pixel-sized pen," cast the graphics context to Graphics2D so that you can use draw() and fill() on the corresponding Shape. This will allow you to specify the outline using setStroke(), illustrated here.

image2 http://i52.tinypic.com/ndo51u.png

I need it to have a custom thickness…I also don't want to use Graphics2D.

Custom thickness is not supported in the Graphics API. As suggested here, the actual graphics context received by paintComponent() is an instance of Graphics2D, which does support custom stroke geometry.

The things is teacher haven't taught me Graphics2D, so I'm not supposed to use it.

Then simply paint the larger triangle and then the smaller. If this isn't working, then you have an error in you calculation of the larger triangle, and you should edit your question to include a complete example.