Animate Fill Level On Irregular Shaped Component

Thanks for pointing out the paintable canvas for this, @pturmel. Using it to draw a shape and then fill to a certain level is easy using the clip method. Definitely beats my previous method of creating shapes to fill the area and dynamically calculating their size and position to make it all work!

Below is a basic example, in case it’s helpful to others. It expects the paintable canvas to have a custom property fillPercent used to set the fill level 0-100%:

from java.awt import Color
from java.awt.geom import GeneralPath
from java.awt.geom import Rectangle2D

g = event.graphics

#### Create shapes assuming 250x350 size, then scale the graphics
#### to proper size later

# Silo
silo = GeneralPath()
silo.moveTo(0,0)
silo.lineTo(0,250)
silo.lineTo(75,350)
silo.lineTo(150,250)
silo.lineTo(150,0)
silo.closePath()

# Shape to be clipped to actual empty area
empty = GeneralPath()
empty.moveTo(0.5,0.5)
empty.lineTo(0.5,250)
empty.lineTo(75,350)
empty.lineTo(150,250)
empty.lineTo(150,0.5)
empty.closePath()

# Empty area based on fillPercent property
emptyPercent = 100 - event.source.fillPercent
emptyArea = Rectangle2D.Float(0, 0, 150, 350 * emptyPercent/100)

#### Scale graphics to actual component size
dX = (event.width-1)/151.0
dY = (event.height-1)/351.0
g.scale(dX,dY)

# Paint silo (includes fill for filled area)
g.setPaint(Color.YELLOW)
g.fill(silo)
g.setColor(Color.GRAY)
g.draw(silo)

# Clip empty area to exclude filled area
g.setClip(emptyArea)
g.clip(empty)

# Paint empty area
g.setPaint(Color.DARK_GRAY)
g.fill(empty)

Along with the example the paintable canvas comes prefilled with, the information in the Java 2D Graphics tutorial here filled in the rest needed to accomplish this (and much more).

1 Like