Android-DIY-ColorTrackView

Android

Android自定义控件:文字逐渐染色效果


源码传送门


描述

效果展示

类似KTV歌词逐渐染色效果

ColorTrackView

讲解

思路:计算染色进度的长度,使用改变色将该长度的文字和背景染色;然后计算未染色的长度,使用原色重新将该长度文字和背景恢复,达到效果。

注意:对于文字颜色的变化,需要注意文本的长度,文本的长度并非是整个View的长度,所以注意文字染色和未染色的长度。少于文字起始位置,则使用原色;超过文字的结束位置,则使用改变色。

  • 文字染色

    • 横向
      计算的是文字长度

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      /**
      * 绘制的核心就在于利用mProgress和方向去计算应该clip的范围
      *
      * @param canvas View画布
      * @param color 画笔颜色
      * @param startX 染色起始位置
      * @param endX 染色终止位置
      */
      private void drawTextX(Canvas canvas, int color, int startX, int endX)
      {
      mPaint.setColor(color);
      // 需要还原Clip
      // save()先把画布的数据保存了(如matrix等),最后绘制完后再restore()则把中间对画布坐标等操作forget掉
      canvas.save(Canvas.CLIP_SAVE_FLAG);
      // clipRect()截取画布中的一个区域
      canvas.clipRect(startX, 0, endX, getMeasuredHeight());
      canvas.drawText(mText, mTextStartX, getMeasuredHeight() / 2 - ((mPaint.descent() + mPaint.ascent()) / 2), mPaint);
      // restore()最后要将画布回复原来的数据(记住save()跟restore()要配对使用)
      canvas.restore();
      }
    • 纵向
      计算的是文字高度

      1
      2
      3
      4
      5
      6
      7
      8
      private void drawTextY(Canvas canvas, int color, int startY, int endY)
      {
      mPaint.setColor(color);
      canvas.save(Canvas.CLIP_SAVE_FLAG);
      canvas.clipRect(0, startY, getMeasuredWidth(), endY);
      canvas.drawText(mText, mTextStartX, getMeasuredHeight() / 2 - ((mPaint.descent() + mPaint.ascent()) / 2), mPaint);
      canvas.restore();
      }
  • 背景染色

    同理文字染色,进度的长度计算则以整个View尺寸基准。

使用

  • xml布局
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<com.excellence.shimmer.Widget.ColorTrackView
android:id="@+id/colortrackview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:background="@drawable/selector"
android:focusable="true"
android:padding="40dp"
app:background_horizontal_padding="18dp"
app:background_vertical_padding="18dp"
app:direction="left"
app:foreground_change_color="@color/colorPrimaryDark"
app:foreground_origin_color="@color/colorAccent"
app:progressable="true"/>
  • 属性

    • text_origin_color 文字原始色,默认黑色
    • text_change_color 文字目标色,默认白色
    • foreground_origin_color 背景原始色,默认透明
    • foreground_change_color 背景目标色,默认透明
    • direction 方向,枚举类型:left、right、top、bottom
    • text 文本
    • text_size 文本大小,默认30px
    • max 最大进度,默认100
    • progress 进度,默认0
    • progressable 是否开启背景染色,默认不开启

感谢

谢谢老板,请尽情用红包来蹂躏我吧!!!
0%