自定義View實例(一)----微博運動積分的實現

自定義View一直是自己的短板,趁着公司項目不緊張的時候,多加強這方面的練習。這一系列文章主要記錄自己在自定義View的學習過程中的心得與體會。

刷微博的時候,發現微博運動界面,運動積分的顯示有一個很好看的動畫效果。OK,就從這個開始我的自定義view之路!

看一下最後的效果圖:
這裏寫圖片描述

分數顏色,分數大小,外圓的顏色,圓弧的顏色都支持自己設置,整體還是和微博那個挺像的。可以設置初始分數,增加分數,減少分數。一起看看自定義View是怎樣一步一步實現的:

1.自定義view的屬性:
在res/values/ 下建立一個attrs.xml , 在裏面定義我們的屬性以及聲明我們的整個樣式。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    //自定義屬性名,定義公共屬性
    <attr name="titleSize" format="dimension"></attr>
    <attr name="titleColor" format="color"></attr>
    <attr name="outCircleColor" format="color"></attr>
    <attr name="inCircleColor" format="color"></attr>
    <attr name="lineColor" format="color"></attr>

    //自定義控件的主題樣式
    <declare-styleable name="MySportView">
        <attr name="titleSize"></attr>
        <attr name="titleColor"></attr>
        <attr name="outCircleColor"></attr>
        <attr name="inCircleColor"></attr>
    </declare-styleable>
</resources>

依次定義了字體大小,字體顏色,外圓顏色,圓弧顏色4個屬性,format是值該屬性的取值類型。
然後就是在佈局文件中申明我們的自定義view:


                <com.example.tangyangkai.myview.MySportView
                android:id="@+id/sport_view"
                android:layout_width="200dp"
                android:layout_height="200dp"
                android:layout_margin="20dp"
                app:inCircleColor="@color/strong"
                app:outCircleColor="@color/colorAccent"
                app:titleColor="@color/colorPrimary"
                app:titleSize="50dp" />

自定義view的屬性我們可以自己進行設置,記得最後要引入我們的命名空間,
xmlns:app=”http://schemas.android.com/apk/res-auto”

2.獲取自定義view的屬性:

/**
 * Created by tangyangkai on 16/5/23.
 */
public class MySportView extends View {


    private String text;
    private int textColor;
    private int textSize;
    private int outCircleColor;
    private int inCircleColor;
    private Paint mPaint, circlePaint;
    //繪製文本的範圍
    private Rect mBound;
    private RectF circleRect;
    private float mCurrentAngle;
    private float mStartSweepValue;
    private int mCurrentPercent, mTargetPercent;

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

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

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


        //獲取我們自定義的樣式屬性
        TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MySportView, defStyleAttr, 0);
        int n = array.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = array.getIndex(i);
            switch (attr) {
                case R.styleable.MySportView_titleColor:
                    // 默認顏色設置爲黑色
                    textColor = array.getColor(attr, Color.BLACK);
                    break;
                case R.styleable.MySportView_titleSize:
                    // 默認設置爲16sp,TypeValue也可以把sp轉化爲px
                    textSize = array.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(
                            TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics()));
                    break;
                case R.styleable.MySportView_outCircleColor:
                    // 默認顏色設置爲黑色
                    outCircleColor = array.getColor(attr, Color.BLACK);
                    break;
                case R.styleable.MySportView_inCircleColor:
                    // 默認顏色設置爲黑色
                    inCircleColor = array.getColor(attr, Color.BLACK);
                    break;

            }

        }
        array.recycle();
        init();

    }

    //初始化
    private void init() {
        //創建畫筆
        mPaint = new Paint();
        circlePaint = new Paint();
        //設置是否抗鋸齒
        mPaint.setAntiAlias(true);
        //圓環開始角度 (-90° 爲12點鐘方向)
        mStartSweepValue = -90;
        //當前角度
        mCurrentAngle = 0;
        //當前百分比
        mCurrentPercent = 0;
        //繪製文本的範圍
        mBound = new Rect();
    }

自定義View一般需要實現一下三個構造方法,這三個構造方法是一層調用一層的,屬於遞進關係。因此,我們只需要在最後一個構造方法中來獲得View的屬性了。

第一步通過theme.obtainStyledAttributes()方法獲得自定義控件的主題樣式數組;第二步就是遍歷每個屬性來獲得對應屬性的值,也就是我們在xml佈局文件中寫的屬性值;第三步就是在循環結束之後記得調用array.recycle()來回收資源;第四步就是進行一下必要的初始化,不建議在onDraw的過程中去實例化對象,因爲這是一個頻繁重複執行的過程,new是需要分配內存空間的,如果在一個頻繁重複的過程中去大量地new對象會造成內存浪費的情況。

3.重寫onMesure方法確定view大小:
當你沒有重寫onMeasure方法時候,系統調用默認的onMeasure方法:

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

這個方法的作用是:測量控件的大小。其實Android系統在加載佈局的時候是由系統測量各子View的大小來告訴父View我需要佔多大空間,然後父View會根據自己的大小來決定分配多大空間給子View。MeasureSpec的specMode模式一共有三種:

MeasureSpec.EXACTLY:父視圖希望子視圖的大小是specSize中指定的大小;一般是設置了明確的值或者是MATCH_PARENT
MeasureSpec.AT_MOST:子視圖的大小最多是specSize中的大小;表示子佈局限制在一個最大值內,一般爲WARP_CONTENT
MeasureSpec.UNSPECIFIED:父視圖不對子視圖施加任何限制,子視圖可以得到任意想要的大小;表示子佈局想要多大就多大,很少使用。

想要”wrap_content”的效果怎麼辦?不着急,只有重寫onMeasure方法:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int width;
        int height;
        //如果佈局裏面設置的是固定值,這裏取佈局裏面的固定值;如果設置的是match_parent,則取父佈局的大小
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthSize;
        } else {

            //如果佈局裏面沒有設置固定值,這裏取佈局寬度的1/2
            width = widthSize * 1 / 2;
        }

        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightSize;
        } else {
            height = heightSize * 1 / 2;
        }
        setMeasuredDimension(width, height);
    }

4.重寫onDraw方法進行繪畫:

    @Override
    protected void onDraw(Canvas canvas) {
        //設置外圓的顏色
        mPaint.setColor(outCircleColor);
        //設置外圓爲空心
        mPaint.setStyle(Paint.Style.STROKE);
        //畫外圓
        canvas.drawCircle(getWidth() / 2, getWidth() / 2, getWidth() / 2, mPaint);
        //設置字體顏色
        mPaint.setColor(textColor);
        //設置字體大小
        mPaint.setTextSize(textSize);
        //得到字體的寬高範圍
        text = String.valueOf(mCurrentPercent);
        mPaint.getTextBounds(text, 0, text.length(), mBound);
        //繪製字體
        canvas.drawText(text, getWidth() / 2 - mBound.width() / 2, getWidth() / 2 + mBound.height() / 2, mPaint);

        //設置字體大小
        mPaint.setTextSize(textSize / 3);
        //繪製字體
        canvas.drawText("分", getWidth() * 3 / 5, getWidth() / 3, mPaint);

        circlePaint.setAntiAlias(true);
        circlePaint.setStyle(Paint.Style.STROKE);
        //設置圓弧的寬度
        circlePaint.setStrokeWidth(10);
        //設置圓弧的顏色
        circlePaint.setColor(inCircleColor);
        //圓弧範圍
        circleRect = new RectF(20, 20, getWidth() - 20, getWidth() - 20);
        //繪製圓弧
        canvas.drawArc(circleRect, mStartSweepValue, mCurrentAngle, false, circlePaint);
        //判斷當前百分比是否小於設置目標的百分比
        if (mCurrentPercent < mTargetPercent) {
            //當前百分比+1
            mCurrentPercent += 1;
            //當前角度+360
            mCurrentAngle += 3.6;
            //每100ms重畫一次
            postInvalidateDelayed(100);
        }
    }

代碼註釋寫的灰常詳細,這裏和大家分享一個小技巧,就是在重寫onDraw方法的之前,自己在本子上畫一遍,座標,位置等簡單標註一下。真的很實用!!!

這裏寫圖片描述

(1)繪製文本的時候,傳入的第二個參數與第三個參數也就是圖中A點的位置

canvas.drawText(text, getWidth() / 2 - mBound.width() / 2, getWidth() / 2 + mBound.height() / 2, mPaint);

(2)繪製圓弧先確定圓弧的範圍,傳入的四個參數就是圖中內圓的外接正方形的座標

     circleRect = new RectF(20, 20, getWidth() - 20, getWidth() - 20);

(3)繪製圓弧,參數依次是圓弧範圍;開始的角度;圓弧的角度;第四個爲True時,在繪製圓弧時將圓心包括在內,通常用來繪製扇形,我們選false;圓弧畫筆

    canvas.drawArc(circleRect, mStartSweepValue, mCurrentAngle, false, circlePaint);

分數增加與圓弧動畫的實現,這時就需要調用postInvalidateDelayed這個方法,這個方法會每隔指定的時間來調用View的invalidate()方法,最終會重新調用onDraw方法,完成一個週期。所以如果想控制動畫,我們就可以定義一個全局的mCurrentPercent與mCurrentAngle變量,在onDraw方法中不斷的遞增,達到動畫的效果。

然後就是增加分數與減少分數的實現:

   public void setNumber(int size) {
        mCurrentPercent = 0;
        mTargetPercent = size;
        mCurrentAngle = 0;
        postInvalidate();
    }

傳遞一個設置的值,在自定義view中將值都設置爲0,然後重新繪製即可。

最後就是在Activity中的應用了:

    private void initview() {
        view = (MySportView) findViewById(R.id.sport_view);
        view.setmTargetPercent(30);
        sportBtn = (Button) findViewById(R.id.sport_btn);
        sportBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                view.setNumber(40);
            }
        });
        sportDownBtn = (Button) findViewById(R.id.sport_down_btn);
        sportDownBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                view.setNumber(20);
            }
        });

    }

OK,到這裏自定義view的實現就全部結束了,其實重頭梳理一遍,也沒有那麼恐怖。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章