自定义View实例(一)----微博运动积分的实现

来源:互联网 发布:占星骰子在线软件 编辑:程序博客网 时间:2024/06/10 17:22

自定义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的实现就全部结束了,其实重头梳理一遍,也没有那么恐怖。

源码地址:

https://github.com/18722527635/MyCustomView

欢迎star,fork,提issues,一起进步!

下一篇自定义View再见~~

6 0
原创粉丝点击