android 自定義view

自定義的控件只需繼承android的View,並實現 onDraw()方法即可,上代碼:

  1. public class GameView extends View {  
  2.  
  3.     private Paint paint;  
  4.     public int angle = 10;  
  5.     public int scale = 1;  
  6.  
  7.     public GameView(Context context) {  
  8.         super(context);  
  9.          paint = new Paint();  
  10.         new Thread(new MyThread()).start();  
  11.     }  
  12.  
  13.     public GameView(Context context, AttributeSet attrs) {  
  14.         super(context, attrs);  
  15.         paint = new Paint();  
  16.         new Thread(new MyThread()).start();  
  17.     }  
  18.     //重寫onDraw方法  
  19.     public void onDraw(Canvas canvas){  
  20.         //設置畫筆  
  21.         paint.setColor(Color.RED);  
  22.         paint.setStyle(Paint.Style.FILL);  
  23.           
  24.         //畫一個矩形  
  25.         canvas.drawColor(Color.YELLOW);  
  26.         canvas.drawRect(50,5,90,25,paint);  
  27.  
  28.         //在畫布上畫一個旋轉的文字   
  29.         canvas.save();//先調用save  
  30.         canvas.rotate(30);//旋轉  
  31.         paint.setColor(Color.BLACK);  
  32.         canvas.drawText("tesdsfsdfsdfsdfsdfsdf",0,20,80,60,paint);  
  33.         canvas.restore();//在調用restore,恢復  
  34.  
  35.        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);  
  36.  
  37.         Matrix matrix = new Matrix();  
  38.  
  39.         matrix.setRotate(angle);//控制圖片旋轉  
  40.         matrix.postScale(scale, scale);//控制圖片縮放  
  41.  
  42.         Bitmap dstbmp = Bitmap.createBitmap(bmp, 00, bmp.getWidth(),  
  43.  
  44.                 bmp.getHeight(), matrix, true);  
  45.  
  46.         canvas.drawColor(Color.BLACK);  
  47.  
  48.         canvas.drawBitmap(dstbmp, 1010null);    }  
  49.  
  50.     class  MyThread implements Runnable{  
  51.  
  52.         @Override 
  53.         public void run() {  
  54.             while(!Thread.currentThread().isInterrupted()){  
  55.                 try {  
  56.                     Thread.sleep(1000);  
  57.                 } catch (InterruptedException e) {  
  58.                     Thread.currentThread().interrupt();  
  59.                 }  
  60.                 postInvalidate();//直接更新view  
  61.             }  
  62.         }  
  63.     }  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章