您的位置:首页 > 其它

自定义View之王者荣耀等级进度条

2018-01-06 12:31 197 查看


Demo效果

这里用王者荣耀的等级做了一个demo



实现思路

由进度条想到ProgressBar,继承自ProgressBar,可以在onDraw()中通过getProgress()和getMax()的比值来得到当前的进度

动画效果其实就是间歇性地增加进度,这里采用Handler的sendEmptyMessageDelayed()方法每隔一定的时间对进度进行加1,直到指定的等级

根据当前进度和等级值来给文字设置不同的颜色,以实现高亮的效果

颜色渐变的效果通过给Paint设置LinearGradient来实现

实现步骤

自定义属性

自定义的属性包括两部分,一部分是在xml布局文件中实现的,一部分是在java代码中实现的。

XML中的属性

像一些和尺寸、颜色相关的属性,建议放在xml文件中实现。本demo中,我在xml里实现了如下属性:

levelTextSize    等级文本字体大小

levelTextChooseColor   等级文本选中时的字体颜色

levelTextUnChooseColor   等级文本非选中时的字体颜色

progressStartColor   在进度为0的位置,进度条的颜色

progressEndColor   在进度为Max的位置,进度条的颜色

progressBgColor   进度条的背景颜色

progressHeight   进度条的高度

有了这些XML属性,到时候UI想换个颜色或者改个大小啥的,直接在XML文件里改就行,处理起来很方便~

XML中的属性使用有三步:

在资源文件中定义(在values文件夹下新建一个attr.xml用于存放定义的属性)
<resources>
   <declare-styleable name="LevelProgressBar">
       <attr name="levelTextSize" format="dimension"/>
       <attr name="levelTextChooseColor" format="color"/>
       <attr name="levelTextUnChooseColor" format="color"/>
       <attr name="progressStartColor" format="color"/>
       <attr name="progressEndColor" format="color"/>
       <attr name="progressBgColor" format="color"/>
       <attr name="progressHeight" format="dimension"/>
   </declare-styleable>
</resources>


在XML中设置属性值
<com.example.lenovo.speedprogressbar.LevelProgressBar
   android:id="@+id/progress_bar"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:paddingLeft="10dp"
   android:paddingRight="10dp"
   app:levelTextChooseColor="#000000"
   app:levelTextSize="15dp"
   app:levelTextUnChooseColor="#999999"
   app:progressBgColor="#CCCCCC"
   app:progressEndColor="#00FF00"
   app:progressHeight="10dp"
   app:progressStartColor="#CCFFCC" />


通过构造方法中的AttributeSet获取XML中设置的属性
public LevelProgressBar(Context context, AttributeSet attrs, int defStyleAttr) {
   super(context, attrs, defStyleAttr);
   // 获取xml中设置的属性值
   obtainStyledAttributes(attrs);
}

private void obtainStyledAttributes(AttributeSet attrs) {
   TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.LevelProgressBar);
   levelTextUnChooseColor = a.getColor(R.styleable.LevelProgressBar_levelTextUnChooseColor, 0x000000);
   levelTextChooseColor = a.getColor(R.styleable.LevelProgressBar_levelTextChooseColor, 0x333333);
   levelTextSize = (int) a.getDimension(R.styleable.LevelProgressBar_levelTextSize, dpTopx(15));
   progressStartColor = a.getColor(R.styleable.LevelProgressBar_progressStartColor, 0xCCFFCC);
   progressEndColor = a.getColor(R.styleable.LevelProgressBar_progressEndColor, 0x00FF00);
   progressBgColor = a.getColor(R.styleable.LevelProgressBar_progressBgColor, 0x000000);
   progressHeight = (int) a.getDimension(R.styleable.LevelProgressBar_progressHeight, dpTopx(20));
}


Java代码中的属性

另外一些与逻辑相关的属性,可以放在java代码中实现。本demo中,我在java代码里实现了如下属性:

levels   等级数

currentLevel   当前等级

levelTexts   等级文本(数组)

animInterval   动画时间间隔

这些属性值通过在LevelProgressBar中暴露方法来实现,需要在使用前设置值:
myProgressBar = (LevelProgressBar) findViewById(R.id.progress_bar);
myProgressBar.setLevels(4);
String[] texts = {"倔强青铜", "持续白银", "荣耀黄金", "尊贵铂金"};
myProgressBar.setLevelTexts(texts);
myProgressBar.setCurrentLevel(1);
myProgressBar.setAnimInterval(10);


setAnimInterval()方法需要在最后调用,调用了它动画效果就开始了

确定宽高

确定宽高的部分由onMeasure()方法来处理。若自定义的View中宽高不使用wrap_content模式,则不需重写onMeasure()方法,若要使用wrap_content模式,则需要重写onMeasure()方法,并在其中对wrap_content模式做特殊的处理。因为wrap_content时,默认大小为父View允许的最大空间,这时需要设置View需要的具体大小,否则最后的效果会和match_parent一样(不理解的朋友可以看看任玉刚《Android开发艺术探索》中自定义View的那章中的解释)。
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
   int width = MeasureSpec.getSize(widthMeasureSpec);
   int height = MeasureSpec.getSize(heightMeasureSpec);
   int heightMode = MeasureSpec.getMode(heightMeasureSpec);

   // layout_height为wrap_content时计算View的高度
   if (heightMode != MeasureSpec.EXACTLY) {
       textHeight = (int) (mPaint.descent() - mPaint.ascent());
       // 10dp为等级文字和进度条之间的间隔
       height = getPaddingTop() + getPaddingBottom() + textHeight + progressHeight +dpTopx(10);
   }

   setMeasuredDimension(width, height);

   mTotalWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
}


对于LevelProgressBar,我想把它的高度设为wrap_content,因此,这里我对高度为wrap_content的模式进行了处理,算出LevelProgressBar的具体宽度,然后调用setMeasuredDimension()方法对算出的高度进行设置,而宽度就使用widthMeasureSpec中的默认值。

这里高度为顶部padding+底部padding+文本高度+进度条高度+10dp(文本和进度条之间的距离,这个属性也可以做成可在XML中自定义的)

其中,textHeight的获取方式为:
textHeight = (int) (mPaint.descent() - mPaint.ascent())


其中mPaint.descent() - mPaint.ascent()得到的是基于当前文本类型和文本大小,文本区域可能的最大高度

绘制内容

绘制内容主要通过重写View的onDraw()方法来实现。

首先绘制等级文字
// 绘制等级文字
for (int i = 0; i < levels; i++) {
   int textWidth = (int) mPaint.measureText(levelTexts[i]);
   mPaint.setColor(levelTextUnChooseColor);
   mPaint.setTextSize(levelTextSize);
   // 到达指定等级时,设置相应的等级文字颜色为深色
   if (getProgress() == targetProgress && currentLevel >=1 && currentLevel <= levels && i == currentLevel-1) {
       mPaint.setColor(levelTextChooseColor);
   }
   canvas.drawText(levelTexts[i], mTotalWidth / levels * (i + 1) - textWidth, textHeight, mPaint);
}


这里用到的关键方法是Canvas的drawText()方法,这个方法的参数如下
public void drawText(@NonNull String text, float x, float y,@NonNull Paint paint)


其中需要特别关注的是x和y,它表示文字的绘制区域的起点,它是框住文本区域的矩形的左下角的点(开始以为是左上角的点,发现文字怎么也画不到指定位置orz)

接着绘制进度条背景
// 绘制进度条底部
mPaint.setColor(progressBgColor);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(progressHeight);
canvas.drawLine(0 + progressHeight / 2, lineY, mTotalWidth - progressHeight / 2, lineY, mPaint);


这里用到的关键方法是Canvas的drawLine()方法,这个方法的参数如下
public void drawLine(float startX, float startY, float stopX, float stopY,@NonNull Paint paint)


这里需要特别注意的是,由于设置了StrokeCap为Round,因此,startX和stopX要考虑半圆的宽度,不然开始和结尾处的笔尖圆形会画到区域之外

最后绘制进度条
// 绘制进度条
int reachedPartEnd = (int) (getProgress() * 1.0f / getMax() * mTotalWidth);
if (reachedPartEnd > 0) {
   mPaint.setStrokeCap(Paint.Cap.ROUND);
   // 设置进度条的渐变色
   Shader shader = new LinearGradient(0, lineY,
           getWidth(), lineY,
           progressStartColor, progressEndColor, Shader.TileMode.REPEAT);
   mPaint.setShader(shader);
   canvas.drawLine(0 + progressHeight / 2, lineY, reachedPartEnd - progressHeight / 2, lineY, mPaint);
   mPaint.setShader(null);
}


进度通过getProgress()和getMax()的比值得到,通过为Paint设置LinearGradient来设置渐变,LinearGradient继承自Shader,它的构造函数如下:
public LinearGradient(float x0, float y0, float x1, float y1, int color0, int color1,TileMode tile)


(x0,y0)和color0,表示渐变起始点的坐标和颜色;(x1,y1)和color1表示渐变终点的坐标和颜色。TileMode表示图像超出原始边界时的呈现方式,这里由于起始和终止点为0和getWidth()(内容的宽度),因此内容始终不会超出原始边界,所以设置成什么方式都没关系。

调用

在MainActivity里面调用自定义的LevelProgressBar:
@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main);

   myProgressBar = (LevelProgressBar) findViewById(R.id.progress_bar);
   myProgressBar.setLevels(4);
   String[] texts = {"倔强青铜", "持续白银", "荣耀黄金", "尊贵铂金"};
   myProgressBar.setLevelTexts(texts);

   Button button1 = (Button) findViewById(R.id.level1);
   button1.setOnClickListener(this);
   Button button2 = (Button) findViewById(R.id.level2);
   button2.setOnClickListener(this);
   Button button3 = (Button) findViewById(R.id.level3);
   button3.setOnClickListener(this);
   Button button4 = (Button) findViewById(R.id.level4);
   button4.setOnClickListener(this);
}

@Override
public void onClick(View v) {
   int id = v.getId();
   switch (id) {
       case R.id.level1:
           myProgressBar.setCurrentLevel(1);
           myProgressBar.setAnimInterval(10);
           break;
       case R.id.level2:
           myProgressBar.setCurrentLevel(2);
           myProgressBar.setAnimInterval(10);
           break;
       case R.id.level3:
           myProgressBar.setCurrentLevel(3);
           myProgressBar.setAnimInterval(10);
           break;
       case R.id.level4:
           myProgressBar.setCurrentLevel(4);
           myProgressBar.setAnimInterval(10);
           break;
   }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: