public class HelloView extends View {
private final String TAG = "MyLog";
public HelloView(Context context) {
super(context);
Log.d(TAG, "HelloView构造方法1");
Log.d(TAG, "w:" +this.getWidth() +" h:" +this.getHeight());
}
public HelloView(Context context, AttributeSet attrs) {
super(context, attrs);
Log.d(TAG, "HelloView构造方法2");
Log.d(TAG, "w:" +this.getWidth() +" h:" +this.getHeight());
}
public HelloView(Context context, AttributeSet attrs, int i) {
super(context, attrs, i);
Log.d(TAG, "HelloView构造方法3");
Log.d(TAG, "w:" +this.getWidth() +" h:" +this.getHeight());
}
protected void onDraw(Canvas canvas) {
Log.d(TAG, "HelloView onDraw方法");
Log.d(TAG, "w:" +this.getWidth() +" h:" +this.getHeight());
canvas.drawColor(Color.BLUE);
myUseBitmapDrawable(canvas);
myUseBitmapFactory(canvas);
myUseInputStreamandBitmapDrawable(canvas);
initPaint();
canvas.drawText("这段文字使用了画笔", 20, 20, paint);
myEvent();
}
Paint paint;
public void initPaint() {
Log.d(TAG, "HelloView paint初始化方法");
paint = new Paint();
paint.setColor(Color.GREEN);
paint.setAntiAlias(true);
paint.setTextSize(18);
}
/**
* 定义手势识别
*/
GestureDetector mGestureDetector;
public void myEvent() {
mGestureDetector = new GestureDetector(
new GestureDetector.SimpleOnGestureListener(){
public boolean onSingleTapUp(MotionEvent e) {
Log.d(TAG, "g.getX():" +e.getX()+ " e.getY():" +e.getY());
return true;
}
});
}
public boolean onTouchEvent(MotionEvent event) {
mGestureDetector.onTouchEvent(event);
return true;
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Log.d(TAG, "HelloView onMeasure方法");
Log.d(TAG, "w:" +this.getWidth() +" h:" +this.getHeight());
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public void myUseBitmapFactory(Canvas canvas) {
Paint paint = new Paint();
Resources rec = getResources();
InputStream is = rec.openRawResource(R.drawable.promo_ipad);
Bitmap bitmap = BitmapFactory.decodeStream(is);
// BitmapFactory.decodeResource(getResources(), R.drawable.promo_ipad);
canvas.drawBitmap(bitmap, 0, 150, paint);
}
public void myUseBitmapDrawable(Canvas canvas) {
Paint paint = new Paint();
Resources rec = getResources();
BitmapDrawable bitmapDrawable = (BitmapDrawable) rec.getDrawable(R.drawable.promo_ipad);
Bitmap bitmap = bitmapDrawable.getBitmap();
canvas.drawBitmap(bitmap, 100, 20, paint);
}
public void myUseInputStreamandBitmapDrawable(Canvas canvas) {
Paint paint = new Paint();
Resources rec = getResources();
InputStream is = rec.openRawResource(R.drawable.promo_ipad);
BitmapDrawable bitmapDrawable = new BitmapDrawable(is);
Bitmap bitmap = bitmapDrawable.getBitmap();
canvas.drawBitmap(bitmap, 100, 300, paint);
}
}