一、创建自定义View
package com.test.androidtest; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class CrossView extends View { private Paint mPaint; private float[] mPoints = {0.5f, 0f, 0.5f, 1f, 0f, 0.5f, 1f, 0.5f}; public CrossView(Context context) { super(context); mPaint = new Paint(); mPaint.setAntiAlias(true); //设置抗锯齿 mPaint.setColor(0xFFFFFFFF);//设置画笔颜色 } public CrossView(Context context, AttributeSet attrs) { super(context, attrs); } public CrossView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * 所有的在画布上绘图的调用都应当受对应的save()和restore()的约束 */ @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.save(); //自定义代码 int scale = getWidth(); canvas.scale(scale, scale); canvas.drawLines(mPoints, mPaint); //end canvas.restore(); } }
提示:
视图同样有被其父视图调用的draw方法。这个方法处理基础的绘制步骤,像设置画布以及绘制背景等。你应当避免重写这个方法,而要重写onDraw方法。
二、创建主活动
package com.test.androidtest; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { private static String TAG = "sgzs"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new CrossView(this)); } }
运行效果