Pitel Pitel - 21 days ago 9
Android Question

How tro draw fading path

How can I draw

Path
with fading (opacity or thicknes) line? Something like this.

Fading example

I know there is
LinearGradient
shader for
Paint
, but it won't bend along the
Path
.

One possible solution might be to get points along the
Path
and just draw it by myself through the segments`. But I coouldn't find any method for that either.

Answer

I came up with the following code. The mos important thing is PathMeasure's getPosTan() method.

if (getGesturePath() != null) {
    final short steps = 150;
    final byte stepDistance = 5;
    final byte maxTrailRadius = 15;
    pathMeasure.setPath(getGesturePath(), false);
    final float pathLength = pathMeasure.getLength();
    for (short i = 1; i <= steps; i++) {
        final float distance = pathLength - i * stepDistance;
        if (distance >= 0) {
            final float trailRadius = maxTrailRadius * (1 - (float) i / steps);
            pathMeasure.getPosTan(distance, pathPos, null);
            final float x = pathPos[0] + RandomUtils.nextFloat(0, 2 * trailRadius) - trailRadius;
            final float y = pathPos[1] + RandomUtils.nextFloat(0, 2 * trailRadius) - trailRadius;
            paint.setShader(new RadialGradient(
                    x,
                    y,
                    trailRadius > 0 ? trailRadius : Float.MIN_VALUE,
                    ColorUtils.setAlphaComponent(Color.GREEN, random.nextInt(0xff)),
                    Color.TRANSPARENT,
                    Shader.TileMode.CLAMP
            ));
            canvas.drawCircle(x, y, trailRadius, paint);
        }
    }
}
Comments