I need to draw a ring, with given thickness, that looks something like this:
The center must be transparent, so that it doesn't cover previously drawn shapes. (or other rings) I've tried something like this:
//g is a Graphics2D object
g.setColor(Color.RED);
g.drawOval(x,y,width,height);
g.setColor(Color.WHITE);
g.drawOval(x+thickness,y+thickness,width-2*thickness,height-2*thickness);
which draws a satisfactory ring, but it covers other shapes; the interior is white, not transparent. How can I modify/rewrite my code so that it doesn't do that?
You could use
graphics.setStroke(...)
for this. This way the center will be fully transparent and therefore won't cover previously drawn shapes. In my example I had to do some additional calculations because of this method though, to make sure the displayedx
andy
coordinates are actually the same as the ones of theRing
instance:You can use the
Shape
andArea
classes to create interesting effects:Using an Area you can also add multiple Shapes together or get the intersection of multiple Shapes.
You can create an
Area
from anEllipse2D
that describes the outer circle, andsubtract
the ellipse that describes the inner circle. This way, you will obtain an actualShape
that can either be drawn or filled (and this will only refer to the area that is actually covered by the ring!).The advantage is that you really have the geometry of the ring available. This allows you, for example, to check whether the ring shape
contains
a certain point, or to fill it with aPaint
that is more than a single color:Here is an example, the relevant part is the
createRingShape
method: