倒计时
public class TimeCountView extends View implements Runnable {
private Paint mPaint;
private int count = 10 ;
private int mWidth;
private int mHeight;
private int mTextSize;
private Thread mThread;
private Rect rect;
private int baseline;
public TimeCountView (Context context) {
this (context, null );
}
public TimeCountView (Context context, @Nullable AttributeSet attrs) {
this (context, attrs, 0 );
}
public TimeCountView (Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super (context, attrs, defStyleAttr);
mTextSize = 200 ;
mThread = new Thread(this );
init();
}
private void init () {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setDither(true );
mPaint.setColor(Color.WHITE);
mPaint.setTextSize(mTextSize);
mPaint.setFakeBoldText(true );
mPaint.setTextAlign(Paint.Align.CENTER);
}
@Override
protected void onDraw (Canvas canvas) {
canvas.drawColor(Color.BLACK);
canvas.drawText(count + "" , rect.centerX(), baseline, mPaint);
}
@Override
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
super .onMeasure(widthMeasureSpec, heightMeasureSpec);
mWidth = getMeasuredWidth();
mHeight = getMeasuredHeight();
measureBaseLine();
}
/**
* 计算文字的基线
*/
private void measureBaseLine () {
rect = new Rect(0 , 0 , mWidth, mHeight);
Paint.FontMetricsInt f = mPaint.getFontMetricsInt();
baseline = rect.centerY() - (f.bottom + f.top) / 2 ;
}
@Override
public void run () {
try {
while (count > 0 ) {
postInvalidate();
count--;
Thread.sleep(1000 );
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 开启倒计时
*/
public void start () {
mThread.start();
}
}