Stroke, MouseSmoothing Demo

What Is It

This demo features four new java.awt.Strokes, and it discusses the MouseSmoothing interface to smooth out the jagged edges in mouse paths.

How To Use It

The strokes are all pretty self-explanatory if you look at their constructors. For example the BristleStroke can be used as follows:

float width = 3;
float thickness = .5f;
long randomSeed = 0;
Stroke s = new BristleStroke(width, thickness, randomSeed);
graphics2D.setStroke(s);

To smooth out jagged user mouse input you can call:

MouseSmoothing s = new BasicMouseSmoothing();
for (Point2D p : mousePoints) {
  s.add((float)p.getX(), (float)p.getY(), 0);
}
Shape smoothedShape = s.getShape();

How It Works

Strokes

The BristleStroke splatters tiny shapes (like shrapnel) over your path. The frequency of the shapes is a little greater in the middle of the stroke, and it tapers off towards the edges ‐ depending on the thickness you've designated.

The BrushStroke uses a MeasuredShape to break up the original path into small sections and paint them in streaks.

The CalligraphyStroke emulates a fixed-angle nib tracing a shape.

The CharcoalStroke starts with another Stroke (by default a BasicStroke) and inserts cracks at a fixed angle into that shape.

Further Reading

Other resources related to custom java.awt.Strokes include:
  1. Jerry Huxtable has an excellent page detailing a few specialized strokes.
  2. Vincent Hardy's book contains a nice wave stroke.
  3. David Flanagan covered the topic in "Java Examples in a Nutshell" (see this page for details).

MouseSmoothing

The MouseSmoothing interface models a class that smooths out incoming mouse data:

public interface MouseSmoothing {
  public void add(float x,float y,long t);
  public void reset();
  public GeneralPath getShape();
  public void getShape(GeneralPath path);
  public boolean isEmpty();
}

The smoothing toggle in this demo uses the BasicMouseSmoothing class to smooth out your drawings, or (when disabled) it renders the points exactly as the MouseEvents capture them.

The BasicMouseSmoothing class tries to simplify the incoming points and, through trial and error, approximate Bézier curves that are a reasonable fit for the incoming user mouse points.