public class MyView extends View {
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context,attrs);
init();
}
protected void onDraw(Canvas canvas) { // 画布
super.onDraw();
Paint paint = new Paint(); // 画笔
paint.setColor(Color.BLUE); // 画笔颜色 Color.TRANSPARENT:透明色
paint.setTextSize(20); // 字体大小
paint.setStrokeWidth(30);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE); //空心 FILL:填充
int width = getWidth();
int height = getHeight();
canvas.drawLine(0, 0, width, height, paint);
canvas.drawCircle(width/2, height/2, 50, paint);
canvas.drawRect(0, 0, 200, 100, paint);
Rect rect = new Rect(0, 0, 200, 100);
canvas.drawRect(rect, paint);
RectF rectF = new RectF(100, 100, 200, 100);
canvas.drawArc(rectF, 0, 270, true, paint);
canvas.drawRoundRect(0, 0, 200, 100, 20, 30, paint);
Bitmap bitmap = BitmapFactory.decodeResource(getResource(), R.mimap.xxx);
canvas.drawBitmap(bitmap, width/2, 0, paint);
canvas.drawText("文本", 0, 20, paint);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if(widthMode == MeasureSpec.EXACTLY // match_parent或固定值
&& heightMode == MeasureSpec.AT_MOST) { // wrap_content }
int width = MeasureSpec.getSize(widthMeasureSpec);
if(widthMode == MeasureSpec.AT_MOST) { width = 100; }
if(heightMode == MeasureSpec.AT_MOST) { height = 100; }
setMeasureDimension(width, height);
}
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
if(action == MotionEvent.ACTION_DOWN) {
} else if(action == MotionEvent.ACTION_MOVE) {
} else if(action == MotionEvent.ACTION_UP) {
}
}
}
invalidate(); //更新控件的绘制
postinvalidate(); //子线程调用
只有继承自View,onDraw()才会被调用