自定义的控件只需继承android的View,并实现 onDraw()方法即可,上代码:
- public class GameView extends View {
- private Paint paint;
- public int angle = 10;
- public int scale = 1;
- public GameView(Context context) {
- super(context);
- paint = new Paint();
- new Thread(new MyThread()).start();
- }
- public GameView(Context context, AttributeSet attrs) {
- super(context, attrs);
- paint = new Paint();
- new Thread(new MyThread()).start();
- }
- //重写onDraw方法
- public void onDraw(Canvas canvas){
- //设置画笔
- paint.setColor(Color.RED);
- paint.setStyle(Paint.Style.FILL);
- //画一个矩形
- canvas.drawColor(Color.YELLOW);
- canvas.drawRect(50,5,90,25,paint);
- //在画布上画一个旋转的文字
- canvas.save();//先调用save
- canvas.rotate(30);//旋转
- paint.setColor(Color.BLACK);
- canvas.drawText("tesdsfsdfsdfsdfsdfsdf",0,20,80,60,paint);
- canvas.restore();//在调用restore,恢复
- Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
- Matrix matrix = new Matrix();
- matrix.setRotate(angle);//控制图片旋转
- matrix.postScale(scale, scale);//控制图片缩放
- Bitmap dstbmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
- bmp.getHeight(), matrix, true);
- canvas.drawColor(Color.BLACK);
- canvas.drawBitmap(dstbmp, 10, 10, null); }
- class MyThread implements Runnable{
- @Override
- public void run() {
- while(!Thread.currentThread().isInterrupted()){
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- postInvalidate();//直接更新view
- }
- }
- }
- }
本文出自 “学习笔记” 博客,请务必保留此出处http://maxuefeng.blog.51cto.com/1876326/560642