速读原著-Android应用开发入门教程(使用路径效果(PathEffect))

9.4 使用路径效果(PathEffect)

路径表示一条曲线,在 Android 中通过路径可以更灵活地实现一些效果。
参考示例程序:ApiDemo 的 PathEffects(ApiDemo=>Graphics=>PathEffects)
源代码:android/apis/graphics/PathEffects.java
PathEffects 程序的运行结果如图所示:
在这里插入图片描述
图中的几个路径的曲线的基本走向一致,但是细节的方面各不相同,例如线的方式代码主要是实现了 SampleView,核心部分如下所示:

    private static class SampleView extends View {
        private Paint mPaint;
        private Path mPath;
        private PathEffect[] mEffects;
        private int[] mColors;
        private float mPhase;
        private static PathEffect makeDash(float phase) {
            return new DashPathEffect(new float[] { 15, 5, 8, 5 }, phase);
        }

        private static void makeEffects(PathEffect[] e, float phase) {
            e[0] = null; // 没有效果
            e[1] = new CornerPathEffect(10); // 拐角路径效果
            e[2] = new DashPathEffect(new float[] {10, 5, 5, 5}, phase);
            e[3] = new PathDashPathEffect(makePathDash(), 12, phase,
                    PathDashPathEffect.Style.ROTATE);
            // 破折号式效果
            e[4] = new ComposePathEffect(e[2], e[1]); // 组合路径效果(内外各不同)
            e[5] = new ComposePathEffect(e[3], e[1]); // 组合路径效果
        }

        public SampleView(Context context) {
            super(context);
            setFocusable(true);
            setFocusableInTouchMode(true);
            mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mPaint.setStyle(Paint.Style.STROKE);
            mPaint.setStrokeWidth(6);
            mPath = makeFollowPath();
            mEffects = new PathEffect[6]; // 定义路径效果
            mColors = new int[] { Color.BLACK, Color.RED, Color.BLUE,
                    Color.GREEN, Color.MAGENTA, Color.BLACK
            };
        }
        @Override protected void onDraw(Canvas canvas) {
            canvas.drawColor(Color.WHITE);
            RectF bounds = new RectF();
            mPath.computeBounds(bounds, false);
            canvas.translate(10 - bounds.left, 10 - bounds.top);
            makeEffects(mEffects, mPhase); // 创建几种效果
            mPhase += 1;
            invalidate();
            for (int i = 0; i < mEffects.length; i++) {
                mPaint.setPathEffect(mEffects[i]); // 设置路径效果
                mPaint.setColor(mColors[i]); // 使用不同的颜色
                canvas.drawPath(mPath, mPaint); // 进行路径的绘制
                canvas.translate(0, 28);
            }
        }
        // 省略部分内容
    }

Path 是在 Android 中表示路径的类,路径可以理解成一条曲线,曲线可以由直线、圆弧等组成。

Android中提供了几种不同的绘制效果,PathEffect 是关于几何图形绘制的一个基类,它具有几个继承者:

ComposePathEffect, CornerPathEffect, DashPathEffect, DiscretePathEffect, PathDashPathEffect, SumPathEffect。
发布了1044 篇原创文章 · 获赞 868 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_42528266/article/details/103970468