Android自定義View之實現簡單炫酷的球體進度球

前言

最近一直在研究自定義view,正好項目中有一個根據下載進度來實現球體進度的需求,因此本身寫了個進度球,代碼很是簡單。先看下效果: php

在這裏插入圖片描述
效果仍是很是不錯的。

準備知識

要實現上面的效果咱們只要掌握兩個知識點就行了,一個是Handler機制,用於發消息刷新咱們的進度球,一個是clipDrawable。網上關於Handler的教程不少,這裏重點介紹一下clipDrawable,進度球的實現全靠clipDrawable。 clipDrawable 以下圖所示:ClipDrawable和InsertDrawable同樣繼承DrawableWrapper,DrawableWrapper繼承Drawable。 java

在這裏插入圖片描述
ClipDrawable是能夠進行裁剪操做的drawable,提供了函數 setLevel(@IntRange(from=0,to=10000) int level)來設置裁剪的大小。level越大圖片越大。level=0時圖片徹底不顯示,level=10000時圖片徹底顯示。

ClipDrawable clipDrawable =  (ClipDrawable) getContext().getResources().getDrawable(R.drawable.bottom_top_clip_gradient_color);//獲取圖片
		clipDrawable.setLevel(100);//進行裁剪
複製代碼

通常還要設置裁剪的方向,垂直裁剪仍是水平裁剪,咱們這個進度球用的是垂直從下向上裁剪。 思路:知道了ClipDrawable的用法,進度球就好實現了。只須要一個球形的圖片,從下往上裁剪,經過設置setLevel從0到10000,就能夠實現進度球從0到進度100的效果了。android

實現

一、定義BallProgress,BallProgress繼承View,重寫onDraw()方法,用於實現進度球的view。canvas

/** * Created time 15:02. * * @author huhanjun * @since 2018/12/26 */
public class BallProgress extends View {
    private float mProgress = 0.0f;   //取值位 0 - 1.0

    private boolean selected = true;

    public BallProgress(Context context) {
        super(context);
    }

    public BallProgress(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public BallProgress(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mProgressPaint = new Paint();//初始化,定義畫筆。
        mProgressPaint.setAntiAlias(true);//設置抗鋸齒
    }

    public float getProgress() {
        return mProgress;
    }

    public void setProgress(float progress) {//設置進度,經過進度的大小實現裁剪的大小
        mProgress = progress;
        invalidate();
    }

    private Paint mProgressPaint;


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Bitmap dst = getRectangleBitmap();//獲取bitmap
        setLayerType(LAYER_TYPE_HARDWARE, null);  //開啓硬件離屏緩存
        canvas.drawBitmap(dst, 0, 0, mProgressPaint);
    }
    private Bitmap getRectangleBitmap() {
        int width = getWidth();
        int height = getHeight();
        
        Bitmap dstBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        
        ClipDrawable clipDrawable = null;
            clipDrawable = (ClipDrawable) getContext().getResources().getDrawable(R.drawable.bottom_top_clip_single_color);//獲取球形的背景圖片,用於裁剪,就是上面看到的進度球中的圖片
            
        clipDrawable.setBounds(new Rect(0, 0, width, height));//設置邊界
        
        clipDrawable.setLevel((int) (10000 * mProgress));//設置進度,
        
        Canvas canvas = new Canvas(dstBitmap);//設置畫布
        
        clipDrawable.draw(canvas);//繪製
        
        return dstBitmap;//將bitmap返回
    }

}
複製代碼

有了自定義的BallProgress,就能夠在佈局中使用了,定義的xml文件以下:api

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">

    <com.example.admin.floatprogressbar.BallProgress android:id="@+id/progress" android:layout_width="@dimen/progress_size" android:layout_height="@dimen/progress_size" android:layout_centerInParent="true" />
    <ImageView android:layout_width="@dimen/progress_size" android:layout_height="@dimen/progress_size" android:layout_centerInParent="true" android:background="@drawable/main_tab_un_select_bg" />

</RelativeLayout>
複製代碼

上面佈局中的ImageView是懸浮球的邊界。在MainActivity中來定時的改變進度球的大小。代碼以下:緩存

public class MainActivity extends AppCompatActivity {
    private final int PROGRESS_MESSAGE = 0;
    private float progress = 0.0f;
    private BallProgress mBallProgress;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case PROGRESS_MESSAGE:
                    progress = (progress > 0.9f) ? 0.9f : progress;
                    mBallProgress.setProgress(progress);//接收消息,改變進度球的進度
                    break;
            }
            return true;
        }
    });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initAction();
    }

    private void initView() {
        mBallProgress = findViewById(R.id.progress);
    }
    //發消息
    private void initAction() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    progress += 0.02f;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    mHandler.sendEmptyMessage(PROGRESS_MESSAGE);//每隔100毫秒發送一次消息,對進度球進度進行更新。
                }
            }
        }).start();
    }

}
複製代碼

上面代碼在inAction()中開一個線程,每隔100毫秒發送消息,在handler中處理更新,在handler使用中並無直接重寫hanldeMessage方法,而是傳入Handler.Callback並在callback中實現handleMessage方法,這樣能夠防止內存泄漏。實際應用中,能夠是跟業務相關的具體進度。app

總結

自定義進度球,用的是繼承view,而且經過自定義畫筆,重寫onDraw()方法來實現,通常自定義view都會重寫onDraw()方法,通常進度條都是ClipDrawable來實現的。 源碼地址:進度球代碼ide

帶波浪的進度球

上面已經實現了簡單的進度球,可是效果不是很好,根據評論區中的提議加上動畫和貝塞爾曲線波紋實現了下面的效果,只取了進度處於某一固定進度的動畫效果如圖: 函數

在這裏插入圖片描述

準備知識

二階貝塞爾曲線 貝塞爾曲線是用一系列點來控制曲線狀態的,將這些點簡單分爲兩類: 佈局

在這裏插入圖片描述
二階貝塞爾曲線的路徑由給定點P0、P一、P2的函數B(t)函數方程以下:
在這裏插入圖片描述
二階曲線由兩個數據點(P0 和 P2),一個控制點(P1)來描述曲線狀態,大體以下:
在這裏插入圖片描述
android中自帶實現二階貝塞爾曲線的api,在Path類中的函數quadTo 。

public void quadTo (float x1, float y1, float x2, float y2) 複製代碼

其中(x1,y1)是上圖中控制點p1的座標,(x2,y2)是上圖中數據點結束位置p2的座標,數據點p0的默認座標是(0,0),也能夠用函數moveTo(x,y)來改變p0座標。要實現上面進度球進度的波動效果,就要將兩個貝塞爾曲線結合起來,而且動態的改變兩個貝塞爾曲線的數據點和控制點,這樣就會使用戶感受到波動的效果。 實現

/** * Created time 17:24. * * @author huhanjun * @since 2019/1/2 */
public class BezierFloatView extends View {

    private double rArc=0;
    private double percent=0;

    public BezierFloatView(Context context) {
        super(context);
    }

    public BezierFloatView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initPaint();
        initAnimator();
    }
    private RectF rectF;
    private int mWidth, mHeight;//畫布的寬帶和高度
    private float cycleWidth, cycleHeight = 30f;//週期的寬度和高度
    private Path pathRipple;//畫的路徑
    private Paint paintRipple;//畫筆
    private float moveSet = 0;//移動的值
    private ValueAnimator animator;//動畫
    private boolean isStart = false;

    /** * 初始化動畫 */
    private void initAnimator() {
        animator = ValueAnimator.ofFloat(0, mWidth);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setDuration(800);
        animator.setInterpolator(new LinearInterpolator());
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                percent=valueAnimator.getAnimatedFraction();
                moveSet = valueAnimator.getAnimatedFraction() * mWidth;
                invalidate();
            }
        });
    }

    /** * 初始化畫的路徑 */
    private void initPath() {
        rArc = mWidth*(1-2*percent);
        double angle= Math.acos(rArc/mWidth);
        pathRipple = new Path();
        pathRipple.moveTo(-6 * cycleWidth + moveSet, 0);
        pathRipple.quadTo(-5 * cycleWidth + moveSet, cycleHeight, -4 * cycleWidth + moveSet, 0);
        pathRipple.quadTo(-3 * cycleWidth + moveSet, -cycleHeight, -2 * cycleWidth + moveSet, 0);
        pathRipple.quadTo(-cycleWidth + moveSet, cycleHeight, moveSet, 0);
        pathRipple.quadTo(cycleWidth + moveSet, -cycleHeight, 2 * cycleWidth + moveSet, 0);
        pathRipple.addArc(rectF,0,180);
        pathRipple.close();
        pathRipple.setFillType(Path.FillType.WINDING);
    }

    /** * 初始化畫筆 */
    private void initPaint() {
        paintRipple = new Paint();
        paintRipple.setStrokeWidth(2);
        paintRipple.setStyle(Paint.Style.FILL);
        paintRipple.setColor(Color.BLUE);
        paintRipple.setAntiAlias(true);
    }

    /** * 畫波紋 * * @param canvas */
    private void drawRipple(Canvas canvas) {
        initPath();
        canvas.drawPath(pathRipple, paintRipple);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mHeight = h;
        mWidth = w;
        cycleWidth = mWidth / 4;
        float r = Math.min(mWidth,mHeight)*0.48f;
        rectF = new RectF(-r,-r,r,r);
        initAnimator();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.translate(mWidth / 2, mHeight / 2);
        drawRipple(canvas);
    }

    /** * 開始動畫 */
    public void start() {
        if (isStart) return;
        isStart = true;
        if (animator == null) {
            initAnimator();
        }
        animator.start();
    }

    /** * 結束動畫 */
    public void stop() {
        if (!isStart) return;
        isStart = false;
        moveSet = 0;
        animator.cancel();
        animator = null;
        invalidate();
    }

}
複製代碼

initPath()中繪製了兩條貝塞爾曲線,經過動態的改變moveset的值來改變p0,p2的值,造成波動效果,經過pathRipple.addArc(rectF,0,180);實現一個與貝塞爾曲線造成包圍的半圓,經過start()來開始動畫,經過stop()來結束動畫。

相關文章
相關標籤/搜索