user565660
user565660

Reputation: 1191

How to draw a shaded area between two lines

How do you draw a shaded area between two lines of a certain color?

I'm using Graphics2D.drawLine() to draw the lines and to have a translucent shaded area of color between the lines.

Upvotes: 2

Views: 2260

Answers (2)

stacker
stacker

Reputation: 68972

This should possible with GradientPaint

Somthing like that:

public void paint(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;

    Polygon p = new Polygon();
    p.addPoint(0,100);
    p.addPoint(100,100);
    p.addPoint(100,200);
    p.addPoint(100,200);

    GradientPaint gp = new GradientPaint(0.0f, 100.0f, Color.red,
             200.0f, 200.0f, Color.green, true);
    g2.setPaint(gp);
    g2.fill(p);
}

For transparency you need to include settings for the alpha channel.

g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
          alpha));

For working examples see this article

Upvotes: 4

Durandal
Durandal

Reputation: 20069

You are thinking the wrong way around. If you want to draw an area, do so. Render the lines on top of the area afterwards. Areas can be rendered with Graphics.drawPolygon.

There are two ways to get translucency. The simplest way (for solid color) is to create the Color instance with alpha (new Color(0xAARRGGBB, true) and use that for drawing. The other way is to use Graphics2D.setComposite with an instance of AlphaComposite (that method also affects the drawing of element that do not make use of the color, e.g. drawImage).

Upvotes: 3

Related Questions