Paint中ComposePathEffect的简单使用

在前面,我们认识了PathEffect的两个子类,现在我们来认识一下第三个子类ComposePathEffect,它就很有意思了,它是把两个子类的效果连在一起。记住是两个,不能多了。它是方法是

public ComposePathEffect(PathEffect outerpe, PathEffect innerpe) {
        native_instance = nativeCreate(outerpe.native_instance,
                                       innerpe.native_instance);
    }

它是先表现出innerpe的效果,再表现中outerpe的效果,下面把前两章的两个子类结合一下,看一下代码

public class PathComposePathEffectView extends View {

    private Paint mPaint;

    private Path mPath;
    private PathEffect comPathEffect;
    private PathEffect cornerPathEffect;
    private PathEffect dashPathEffect;

    private PathMeasure mPathMeasure;
    private float mLength;
    private float animValue;

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

    public PathComposePathEffectView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

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

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(5);
        mPaint.setColor(Color.RED);

        mPath = new Path();
        mPath.moveTo(0,100);
        mPath.lineTo(100,150);
        mPath.lineTo(200,50);
        mPath.lineTo(300,200);
        mPath.lineTo(400,150);

        mPathMeasure = new PathMeasure(mPath,false);
        mLength = mPathMeasure.getLength();

        //设置拆线处为圆角
        cornerPathEffect = new CornerPathEffect(30);

        //还记得这个动画吧,让线从无到有的动画
        ValueAnimator animator = ValueAnimator.ofFloat(1,0);
        animator.setDuration(2000);
        animator.setRepeatCount(0);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                animValue = (float)animation.getAnimatedValue();

                dashPathEffect = new DashPathEffect(new float[]{mLength,mLength},mLength * animValue);
                
                //将两个Effect组合起来
                comPathEffect = new ComposePathEffect(cornerPathEffect,dashPathEffect);
                mPaint.setPathEffect(comPathEffect);
                invalidate();
            }
        });
        animator.start();

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawPath(mPath,mPaint);
    }
}

发布了305 篇原创文章 · 获赞 261 · 访问量 184万+

猜你喜欢

转载自blog.csdn.net/chenguang79/article/details/102518925