自定義組件基礎
本案例主要簡述如何通過view繪製文字、圖形和圖片。
public class MyView2 extends View {
private Bitmap bitmap;
//自定義組件在佈局中調用時執行以下方法
public MyView2(Context context, AttributeSet attrs) {
super(context, attrs);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
//自定義組件在代碼中調用時執行以下方法
public MyView2(Context context) {
super(context);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
/**
* 各條邊距離左上右下的距離(left,top,right,bottom)
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setAntiAlias(true);//抗鋸齒
paint.setTextSize(30);
canvas.drawText("my is onDraw", 0, 30, paint);
canvas.drawLine(0, 50, 600, 50, paint);//畫直線
canvas.drawRect(0, 90, 100, 190, paint);//畫矩形
paint.setColor(Color.BLUE);//普通方法設置顏色
//paint.setStyle(android.graphics.Paint.Style.STROKE);//空心矩形
Rect r = new Rect(220, 150, 300, 240);
canvas.drawRect(r, paint);//畫矩形
RectF rectf = new RectF(0, 250, 100, 340);
canvas.drawRoundRect(rectf, 11, 11, paint);//畫圓角矩形
//paint.setColor(0xffffffff);//十六進制設置顏色
canvas.drawCircle(400, 300, 50, paint);//畫圓形
canvas.drawBitmap(bitmap, 100, 400, paint);//畫圖片
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<com.trkj.dept12_customer1.MyView2
android:background="#FF0000"
android:layout_width="400dp"
android:layout_height="match_parent" />
</RelativeLayout>
Activity:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);//調用佈局
setContentView(new MyView2(this));//調用自定義代碼
}
}
各邊距示意圖: