public class HightLightTextView extends TextView { // 存儲view的寬度 private int mTextViewWidth = 0; // 畫筆 private Paint mPaint; // 線性渲染 private LinearGrad... ...
public class HightLightTextView extends TextView { // 存儲view的寬度 private int mTextViewWidth = 0; // 畫筆 private Paint mPaint; // 線性渲染 private LinearGradient mLinearGradient; // 存儲變換的matrix private Matrix matrix; // 移動距離 private int mTranslateX = 0; // 構造方法 public HightLightTextView(Context context) { this(context, null); } public HightLightTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public HightLightTextView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * view的調用過程:構造方法->onFinishInflate->onSizeChanged->onDraw */ @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // 獲取view的寬度,初始化畫筆等初始屬性 if (mTextViewWidth == 0) { mTextViewWidth = getMeasuredWidth(); // 如果寬度大於0的話,則初始化 if (mTextViewWidth > 0) { // 初始化畫筆 mPaint = getPaint(); // 線性渲染 mLinearGradient = new LinearGradient(0, getMeasuredHeight(), mTextViewWidth, 0, new int[]{0X55FFFFFF, 0XFFFFFFFF, 0X55FFFFFF}, new float[]{0, 0.5f, 1}, Shader.TileMode.CLAMP); mPaint.setShader(mLinearGradient); matrix = new Matrix(); } } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (matrix != null) { mTranslateX += mTextViewWidth / 10; // 如果移動的距離大於兩倍的寬度,則重新開始移動 if (mTranslateX > 2 * mTextViewWidth) { mTranslateX = -mTextViewWidth; } // 平移matrix matrix.setTranslate(mTranslateX, 0); // 設置線性變化的matrix mLinearGradient.setLocalMatrix(matrix); // 延遲50ms重繪 (重繪時會重新調用onDraw) postInvalidateDelayed(50); } } }