Search code examples
androidandroid-custom-viewpaintandroid-paint

Android PathDashPathEffect: the path shape does not work for a straight line


I am trying to build a custom view that draws a line with diagonal stripes pattern. It should look similar to this:

enter image description here

I think using PathDashPathEffect should do, but when I set the path shape to be a straight line path, the view doesn't draw anything. If I add more segments to the path so that it can close, for example make it a triangle, then the view shows.

Here's my path shape:

    Path pathShape = new Path();
    pathShape.moveTo(0, 10);
    pathShape.lineTo(10, 0);

The above doesn't work, the view shows nothing. The below works and shows triangles as the pattern on the line:

    Path pathShape = new Path();
    pathShape.moveTo(0, 0);
    pathShape.lineTo(10, 10);
    pathShape.lineTo(10, 0);

My entire custom view:

private final Paint paint;
private final Path path;

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
    paint = new Paint();
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(20);
    paint.setColor(Color.RED);
    Path pathShape = new Path();
    pathShape.moveTo(0, 0);
    pathShape.lineTo(10, 10);
    pathShape.lineTo(10, 0);
    PathDashPathEffect pathEffect = new PathDashPathEffect(pathShape, 30, 30, PathDashPathEffect.Style.ROTATE);
    paint.setPathEffect(pathEffect);
    path = new Path();
}

@Override
protected void onDraw(Canvas canvas) {
    path.reset();
    path.moveTo(0, getHeight() / 2);
    path.lineTo(getWidth(), getHeight() / 2);
    canvas.drawPath(path, paint);
}

Does anyone knows how to achieve that?

Many thanks!


Solution

  • Eventually I achieved this by changing the Path to be a shape that closes other than a Path. I made the shape to be a tilted rectangle with width 1 and that worked. So I guess lessons learned: PathDashPathEffect does not work if the PathEffect is a Path that is not closed.