二、如何创建自己的View
继承View或者它的子类,然后重写构造函数和onDraw函数。看看代码:
package com.wenix;
import Android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class MyView extends View {
private static final String TAG = "MyView";
private Paint mPaint;
Drawable background;
public MyView(Context context) {
// TODO Auto-generated constructor stub
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
mPaint = new Paint();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);//得到属性数组
int textColor = a.getColor(R.styleable.MyView_textColor, Color.BLUE);//得到属性值,可以指定默认值,防止空值,注意引用名。
float textSize = a.getDimension(R.styleable.MyView_textSize, 22);//注意get方法,跟format是一致的。
background = a.getDrawable(R.styleable.MyView_background);
mPaint.setColor(textColor);
mPaint.setTextSize(textSize);
a.recycle();//一定要recycle以下来保证属性值一致。
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
mPaint.setStyle(Style.FILL);
Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.myview_background);
canvas.drawBitmap(bitmap, 0, 0, mPaint);
// Matrix matrix = new Matrix();
// matrix.postScale(0, 0, 480, 800);
// canvas.drawBitmap(bitmap, matrix, mPaint);
mPaint.setColor(Color.RED);
canvas.drawText("hello,world!", 20, 55, mPaint);
}
}