Easy Tutorial
❮ Mqtt Intro Python Partial ❯

8.3.12 Paint API - PathEffect (Path Effect)

Category Android Basic Tutorial

Introduction:

>

This section continues to explore the Paint API - PathEffect, where we set the style of the paint to Stroke. This allows us to draw shapes composed of lines. Sometimes these lines may appear monotonous, such as wanting to convert them into dashed lines or making the corners of the paths smoother. In such cases, you can consider using PathEffect to achieve these effects!

Official API documentation: PathEffect. Upon reviewing the documentation, you'll find that PathEffect, like the previously learned MaskFilter and ColorFilter, has very few usable methods.

We typically use its six subclasses:

Below, we analyze their purposes and constructor methods one by one!


1. Subclass Purpose and Constructor Parameter Analysis:


1) CornerPathEffect

CornerPathEffect(float radius)

>

Smooths the angles between connected segments of the path, creating a rounded effect. The radius specifies the radius of the rounding arc.


2) DashPathEffect

DashPathEffect(float[] intervals, float phase)

>

Converts the path's segments into dashed lines. The intervals array defines the lengths of the dashes and gaps, and must have at least two elements. The phase is the offset at which to start the dash pattern.


3) DiscretePathEffect

DiscretePathEffect(float segmentLength, float deviation)

>

Scatters the path's segments, creating a fragmented effect. The segmentLength specifies the maximum length of each segment, and deviation is the amount of random deviation applied to each segment.


4) PathDashPathEffect

PathDashPathEffect(Path shape, float advance, float phase, PathDashPathEffect.Style style)

>

Fills the current path with a shape. The shape is the path used for filling, advance is the spacing between shapes, and style is an enum that can be ROTATE, MORPH, or TRANSLATE.


5) ComposePathEffect

ComposePathEffect(PathEffect outerpe, PathEffect innerpe)

>

Combines two effects. It first applies innerpe, then adds outerpe on top of it.


6) SumPathEffect

SumPathEffect(PathEffect first, PathEffect second)

>

Superimposes two effects. Unlike ComposePathEffect, it independently displays both effects and then overlays them.


2. Code to Demonstrate Each Effect

Talking less and coding more is the best way to understand. Let's write some code to see the effects of these subclasses in action!

Run Effect:

Implementation Code:

We'll create our own View, where the moving effect of the lines is caused by increasing the phase and redrawing the view. PathEffectView.java:

/**
 * Created by Jay on 2015/10/30 0030.
 */
public class PathEffectView extends View {

    private Paint mPaint;
    private Path mPath;
    private float phase = 0;
    private PathEffect[] effects = new PathEffect[7];
    private int[] colors;

    public PathEffectView(Context context) {
        this(context, null);
    }

    public PathEffectView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PathEffectView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    // Initialize the paint
    private void init() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); // Anti-alias
        mPaint.setStyle(Paint.Style.STROKE);       // Stroke style
        mPaint.setStrokeWidth(5);                  // Stroke width
        mPath = new Path();
        mPath.moveTo(0, 0);
        for (int i = 1; i <= 15; i++) {
            // Generate 15 points with random coordinates and connect them with a Path
            mPath.lineTo(i * 40, (float) Math.random() * 100);
        }
        // Initialize 7 colors
        colors = new int[] { Color.RED, Color.BLUE, Color.GREEN,
                Color.YELLOW, Color.BLACK, Color.MAGENTA, Color.CYAN };
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(Color.WHITE);
        // Initialize path effects:
        effects[0] = null;                                    // No effect
        effects[1] = new CornerPathEffect(10);                // CornerPathEffect
        effects[2] = new DiscretePathEffect(3.0f, 5.0f);      // DiscretePathEffect
        effects[3] = new DashPathEffect(new float[] { 20, 10, 5, 10 }, phase);   // DashPathEffect
        Path p = new Path();
        p.addRect(0, 0, 8, 8, Path.Direction.CCW);
        effects[4] = new PathDashPathEffect(p, 12, phase,
                PathDashPathEffect.Style.ROTATE);             // PathDashPathEffect
        effects[5] = new ComposePathEffect(effects[2], effects[4]);    // ComposePathEffect
        effects[6] = new SumPathEffect(effects[2], effects[4]);   // SumPathEffect
        // Move the canvas to (10,10) to start drawing
        canvas.translate(10, 10);
        // Draw the path with 7 different path effects and colors
        for (int i = 0; i < effects.length; i++) {
            mPaint.setPathEffect(effects[i]);
            mPaint.setColor(colors[i]);
            canvas.drawPath(mPath, mPaint);
            canvas.translate(0, 60);
        }
        // Change the phase to create an animation effect
        phase += 2;
        invalidate();
    }
}

The comments in the code are quite clear, so there's no need to elaborate further.


3. Download the Example Code:

PathEffectDemo.zip


Summary:

>

This section didn't cover anything particularly difficult. It simply introduced the effects of the six subclasses of PathEffect and how to apply them using the setPathEffect method on a Paint object. It's quite straightforward. That's all for now, thank you!

Follow on WeChat

❮ Mqtt Intro Python Partial ❯