【Android隨記】-- Android自定義控件效果實現

 效果圖:


看代碼,不難:

  1. package com.example.test; 
  2.  
  3. import android.content.Context; 
  4. import android.graphics.Bitmap; 
  5. import android.graphics.Canvas; 
  6. import android.graphics.Color; 
  7. import android.graphics.Paint; 
  8. import android.util.AttributeSet; 
  9. import android.util.Log; 
  10. import android.widget.RelativeLayout; 
  11.  
  12. public class MyLayout extends RelativeLayout { 
  13.  
  14.     String title; 
  15.  
  16.     public MyLayout(Context context, AttributeSet attrs, int defStyle) { 
  17.         super(context, attrs, defStyle); 
  18.         // TODO Auto-generated constructor stub 
  19.     } 
  20.  
  21.     public MyLayout(Context context, AttributeSet attrs) { 
  22.         super(context, attrs); 
  23.         // TODO Auto-generated constructor stub 
  24.     } 
  25.  
  26.     public MyLayout(Context context, String title) { 
  27.         super(context); 
  28.         // TODO Auto-generated constructor stub 
  29.         this.title = title; 
  30.     } 
  31.  
  32.     @Override 
  33.     protected void dispatchDraw(Canvas canvas) { 
  34.          
  35.         Paint paint = new Paint(); 
  36.         paint.setColor(Color.BLACK); 
  37.         int width = getWidth(); 
  38.         int height = getHeight(); 
  39.         int empty = 25
  40.  
  41.         Paint paint2 = new Paint(); 
  42.          
  43.         paint2.setColor(Color.BLACK); 
  44.         paint2.setTextSize(25); 
  45.         paint2.setAntiAlias(true); 
  46.         canvas.drawColor(Color.WHITE); 
  47.         float length=paint2.measureText(title); 
  48.         Log.e("length", length+""); 
  49.          
  50.         canvas.drawText(title, empty*2, empty+10, paint2); 
  51.  
  52.         canvas.drawLine(empty, empty, empty*2, empty, paint); 
  53.         canvas.drawLine(empty*2+length, empty,  width - empty, empty, paint); 
  54. //      canvas.drawLine(empty, empty, width - empty, empty, paint); 
  55.  
  56.         canvas.drawLine(width - empty, empty, width - empty, height - empty, 
  57.                 paint); 
  58.  
  59.         canvas.drawLine(width - empty, height - empty, empty, height - empty, 
  60.                 paint); 
  61.  
  62.         canvas.drawLine(empty, empty, empty, height - empty, paint); 
  63.         setPadding(empty+10, empty+10, empty+10, empty+10); 
  64.         super.dispatchDraw(canvas); 
  65.          
  66.          
  67.     } 

調用方法:

  1. MyLayout layout = new MyLayout(this,"測試一下"); 
  2.         TextView textView=new TextView(this); 

 

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