重写View.onDraw获得canvas的对象View中的Canvas对象会被当做参数传递过来,我们操作这个Canvas,效果会直接反应在View中。
public class TestActivity extends Activity implements OnClickListener { private MyCountdownView view; private Button startBtn; private int count = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map_test); view = (MyCountdownView) findViewById(R.id.myCountdownView); startBtn = (Button) findViewById(R.id.button_test_start); startBtn.setOnClickListener(this); } @Override public void onClick(View arg0) { new Thread(new Runnable() { @Override public void run() { try { while (count <10) { count++; Thread.sleep(1000); view.setTxtCount(count); } } catch (Exception e) { e.printStackTrace(); } } }).start(); } }
</pre><pre name="code" class="java">public class MyCountdownView extends View { private int textSize; private int mCount=1; private Paint textPoint; public MyCountdownView(Context context) { super(context); initView(); } public MyCountdownView(Context context, AttributeSet attrs) { super(context, attrs); initView(); } public MyCountdownView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initView(); } public void setTxtCount(int mCount){ this.mCount=mCount; //// 使用postInvalidate可以直接在线程中更新界面 postInvalidate(); } private void initView(){ textSize=dip2px(getContext(), 100); textPoint=new Paint(Paint.LINEAR_TEXT_FLAG); textPoint.setAntiAlias(true); textPoint.setColor(Color.parseColor("#000000")); textPoint.setStyle(Style.FILL_AND_STROKE); textPoint.setTextAlign(Align.LEFT); textPoint.setTextSize(textSize); } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); Rect bounds=new Rect(); String middleText=String.valueOf(mCount); textPoint.getTextBounds(middleText, 0, middleText.length(), bounds); canvas.drawText(middleText, getWidth()/2-60, getHeight()/2, textPoint); } //dip与px的互相转换: public static int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5f); } }