Android实现实现文字闪动效果

private LinearGradient mGradient;

private int[] mGradientColors;
private int mGradientIndex;
private Paint mPaint;
private Matrix mMatrix;
private static final int STEP_LENGTH = 5;
private float mDensity;

mGradientColors = new int[] {Color.argb(255, 120, 120, 120),
        Color.argb(255, 120, 120, 120), Color.argb(255, 255, 255, 255)};
mGradient = new LinearGradient(0, 0, 100 * mDensity, 0, mGradientColors,
        new float[] {0, 0.7f, 1}, TileMode.MIRROR);
mGradientIndex = 0;
mPaint = new Paint();
mMatrix = new Matrix();
mPaint.setTextSize(mTextSize);

构造方法里{
mDensity = getResources().getDisplayMetrics().density;
mHandler.sendEmptyMessageDelayed(MSG_REDRAW, DRAW_INTERVAL);
}

在TextView的

onDraw方法里
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    mPaint.setShader(mGradient);
    canvas.drawText(mText, mTextLeft, mTextTop, mPaint);

}
 
  

private Handler mHandler = new Handler() {

    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
        case MSG_REDRAW:
            mMatrix.setTranslate(mGradientIndex, 0);
            mGradient.setLocalMatrix(mMatrix);
            invalidate();
            mGradientIndex += STEP_LENGTH * mDensity;
            if (mGradientIndex > mSlidableLength) {
                mGradientIndex = 0;
            }
            mHandler.sendEmptyMessageDelayed(MSG_REDRAW, DRAW_INTERVAL);
            break;
        }
    }
};



你可能感兴趣的:(Android实现实现文字闪动效果)