Android自定义View

自定义View_狗哥玩转进度条🐶

2019-03-13  本文已影响357人  BraveJoy

前几天在群里看到过一个朋友发过一个比较炫酷的效果图[gif找不到了],当时思考了一下实现思路,本着能简则简的原则模仿了一下,先来看下效果图。[终于找到了制作gif的好方法,还是Photoshop给力!!!]

狗哥

先来小小的分析一下过程,动画分为两段:①外实内空;②外空内实。主要是根据水波纹填充的区域不同,第一个是填充区域之外的空间是一个二狗子的形状,第二个是填充区域是一个二狗子的形状。想到这里立马茅塞顿开,两张含有透明区域的图片搞定,图片如下:

狗子对比图

实现思路


实现过程

召唤二狗子

/**
 * 二狗子图片
 */
private Bitmap bitmap1 = null;
private Bitmap bitmap2 = null;

bitmap1 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.icon_dog_1);
bitmap2 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.icon_dog_2);

这里主要就是把drawable转换成bitmap,后面我们直接用canvas.drawBitmap把二狗子绘制出来即可,再者就是一些参数的初始化和画笔的初始化等等,就不列举了。

裁切画布

/**
 * 需要裁剪的Path
 */
private Path path = new Path();
//添加一个圆
path.addCircle(w / 2, h / 2, w / 2, Path.Direction.CW);

/**
 * 裁切canvas
 *
 * @param canvas
 */
private void clipCicle(Canvas canvas) {
    canvas.clipPath(path);
    canvas.drawPath(path, mPaintClipPath);
}

绘制水波纹

关于绘制的原理可参考此篇文章,或者翻看高中数据正弦函数 [手动滑稽]
自定义View_做一个与众不同的🥕

/**
 * 填充颜色,绘制水波纹
 */
private void fillWater(Canvas canvas) {
    φ -= mWaterSpeed / 100;
    float y;
    pathWater.reset();
    pathWater.moveTo(0, mCurrentProgressY);
    for (float x = 0; x <= getWidth(); x++) {
        y = (float) (A * Math.sin(ω * x + φ) + K);
        pathWater.lineTo(x, y + mCurrentProgressY);
    }
    pathWater.lineTo(getWidth(), getHeight());
    pathWater.lineTo(0, getHeight());
    pathWater.close();
    canvas.drawPath(pathWater, paintWater);
}

再次召唤二狗子

canvas.drawBitmap(status ? bitmap1 : bitmap2, 0, 0, mPaint);

状态处理及动画控制

/**
 * 开启动画
 */
public void start() {
    if (mValueAnimator != null) {
        mValueAnimator.cancel();
        mValueAnimator = null;
    }
    mValueAnimator = ValueAnimator.ofFloat(getHeight(), -2 * A);
    mValueAnimator.setRepeatCount(ValueAnimator.INFINITE);
    mValueAnimator.setRepeatMode(ValueAnimator.RESTART);
    mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            mCurrentProgressY = (float) valueAnimator.getAnimatedValue();
            invalidate();
        }
    });
    mValueAnimator.addListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationRepeat(Animator animation) {
            super.onAnimationRepeat(animation);
            status = !status;
        }
        @Override
        public void onAnimationCancel(Animator animation) {
            super.onAnimationCancel(animation);
            status = false;
        }
    });
    mValueAnimator.setDuration(4000);
    mValueAnimator.start();
}
/**
 * 停止动画并恢复初始状态
 */
public void stop() {
    if (mValueAnimator != null) {
        mValueAnimator.cancel();
        mValueAnimator = null;
    }
    mCurrentProgressY = getHeight();
    invalidate();
}

完整代码

public class DogView extends View {
    /**
     * 上下文
     */
    private Context mContext;
    /**
     * 记录进度条上升的距离
     */
    private float mCurrentProgressY;
    /**
     * 用来控制bitmap的展示
     */
    private boolean status;

    /**
     * 用来绘制水波纹的画笔
     */
    private Paint paintWater;
    /**
     * 用来绘制最外层圆圈的画笔
     */
    private Paint mPaintCircleLine;
    /**
     * 用来绘制图片bitmap的画笔
     */
    private Paint mPaint;
    /**
     * 用来裁剪canvas
     */
    private Paint mPaintClipPath;
    /**
     * 需要裁剪的Path
     */
    private Path path = new Path();

    /**
     * 二狗子图片
     */
    private Bitmap bitmap1 = null;
    private Bitmap bitmap2 = null;
    /**
     * 振幅
     */
    private int A;
    /**
     * 偏距
     */
    private int K;

    /**
     * 初相
     */
    private float φ;

    /**
     * 角速度
     */
    private double ω;
    /**
     * 波形移动的速度
     */
    private float mWaterSpeed = 50f;
    /**
     * 水波纹Path
     */
    private Path pathWater = new Path();
    /**
     * 绘制动画
     */
    private ValueAnimator mValueAnimator = null;

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

    public DogView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DogView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initView();
    }

    private void initView() {
        A = dip2px(mContext, 5);

        K = A;

        bitmap1 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.icon_dog_1);
        bitmap2 = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.icon_dog_2);

        mPaint = new Paint();
        mPaint.setAntiAlias(true);

        mPaintClipPath = new Paint();
        mPaintClipPath.setAntiAlias(true);
        mPaintClipPath.setColor(Color.WHITE);

        paintWater = new Paint();
        paintWater.setAntiAlias(true);
        paintWater.setColor(Color.RED);

        mPaintCircleLine = new Paint();
        mPaintCircleLine.setAntiAlias(true);
        mPaintCircleLine.setColor(Color.RED);
        mPaintCircleLine.setStyle(Paint.Style.STROKE);
        mPaintCircleLine.setStrokeWidth(dip2px(mContext, 2));
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        //设置bitmap的尺寸
        bitmap1 = resizeImage(bitmap1, w, h);
        bitmap2 = resizeImage(bitmap2, w, h);

        ω = 8 * Math.PI / w;
        mCurrentProgressY = h;
        path.addCircle(w / 2, h / 2, w / 2, Path.Direction.CW);
    }

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

        //裁剪
        clipCicle(canvas);
        //画水波纹
        fillWater(canvas);
        //画狗
        canvas.drawBitmap(status ? bitmap1 : bitmap2, 0, 0, mPaint);
        //画圆圈
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2 - dip2px(mContext, 1), mPaintCircleLine);

    }

    /**
     * 填充颜色,绘制水波纹
     */
    private void fillWater(Canvas canvas) {

        φ -= mWaterSpeed / 100;

        float y;

        pathWater.reset();
        pathWater.moveTo(0, mCurrentProgressY);

        for (float x = 0; x <= getWidth(); x++) {
            y = (float) (A * Math.sin(ω * x + φ) + K);
            pathWater.lineTo(x, y + mCurrentProgressY);
        }

        pathWater.lineTo(getWidth(), getHeight());
        pathWater.lineTo(0, getHeight());
        pathWater.close();
        canvas.drawPath(pathWater, paintWater);

    }


    /**
     * 裁剪canvas
     *
     * @param canvas
     */
    private void clipCicle(Canvas canvas) {
        canvas.clipPath(path);
        canvas.drawPath(path, mPaintClipPath);
    }

    /**
     * 开启动画
     */
    public void start() {
        if (mValueAnimator != null) {
            mValueAnimator.cancel();
            mValueAnimator = null;
        }
        mValueAnimator = ValueAnimator.ofFloat(getHeight(), -2 * A);
        mValueAnimator.setRepeatCount(ValueAnimator.INFINITE);
        mValueAnimator.setRepeatMode(ValueAnimator.RESTART);
        mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                mCurrentProgressY = (float) valueAnimator.getAnimatedValue();
                invalidate();
            }
        });

        mValueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationRepeat(Animator animation) {
                super.onAnimationRepeat(animation);
                status = !status;
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                super.onAnimationCancel(animation);
                status = false;
            }
        });
        mValueAnimator.setDuration(4000);
        mValueAnimator.start();
    }

    /**
     * 停止动画并恢复初始状态
     */
    public void stop() {
        if (mValueAnimator != null) {
            mValueAnimator.cancel();
            mValueAnimator = null;
        }
        mCurrentProgressY = getHeight();
        invalidate();
    }

    /**
     * 缩放bitmap
     *
     * @param bitmap
     * @param w
     * @param h
     * @return
     */
    public Bitmap resizeImage(Bitmap bitmap, int w, int h) {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return resizedBitmap;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    private int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

}

狗哥奉上

狗哥
上一篇下一篇

猜你喜欢

热点阅读