mainActivity如下:
package com.cn; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class MainActivity extends Activity { private SurfaceViewTest mSurfaceViewTest; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mSurfaceViewTest=new SurfaceViewTest(MainActivity.this); setContentView(mSurfaceViewTest); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } }
SurfaceViewTest如下:
package com.cn; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.RectF; import android.view.SurfaceHolder; import android.view.SurfaceView; //注意 //1 矩形构造方法 //RectF rectF=new RectF(10, 10, 100, 100); //RectF(float left, float top, float right, float bottom) //must ensure that left <= right and top <= bottom //第一个,第二个参数float left, float top //表示矩形的起始点(即左上角的点) //第一个,第二个参数float right, float bottom //表示矩形的终止点(即右下角的点) //2 绘制椭圆 //并没有想象中的"直接"绘制椭圆的方法 //而是在一个矩形中绘制了椭圆 //因为一个矩形就定位了椭圆 public class SurfaceViewTest extends SurfaceView implements SurfaceHolder.Callback{ private Context mContext; private Paint mPaint; public SurfaceViewTest(Context context) { super(context); this.mContext=context; //设置生命周期回调接口的实现 this.getHolder().addCallback(this); mPaint=new Paint(); //抗锯齿 mPaint.setAntiAlias(true); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //-------->绘制白色矩形背景 //设置画笔颜色 mPaint.setColor(Color.WHITE); //绘制白色矩形背景 canvas.drawRect(0, 0, 350, 450, mPaint); mPaint.reset(); //-------->绘制直线 mPaint.setColor(Color.RED); //设置线条宽度 mPaint.setStrokeWidth(10); canvas.drawLine(30, 10, 200, 70, mPaint); mPaint.reset(); //-------->绘制带边框的空心矩形(实心矩形) mPaint.setStrokeWidth(5); mPaint.setARGB(50, 0, 255, 0); //注释掉下一句即为实心矩形 mPaint.setStyle(Style.STROKE); RectF rectF1=new RectF(10, 10, 150, 150); canvas.drawRect(rectF1, mPaint); mPaint.reset(); //-------->绘制空心圆(实心圆) mPaint.setColor(Color.GREEN); mPaint.setAntiAlias(true); //注释掉下一句即为实心圆 mPaint.setStyle(Style.STROKE); canvas.drawCircle(150, 200, 30, mPaint); mPaint.reset(); //-------->绘制椭圆充满矩形 mPaint.setColor(Color.YELLOW); RectF rectF2=new RectF(10, 230, 200, 300); canvas.drawOval(rectF2, mPaint); mPaint.reset(); //-------->绘制文字 mPaint.setColor(Color.BLACK); mPaint.setTextSize(25); //设置文字下划线 mPaint.setUnderlineText(true); canvas.drawText("大家好,Hello world", 50, 340, mPaint); mPaint.reset(); } //实现SurfaceHolder.Callback中的方法 public void surfaceCreated(SurfaceHolder holder) { Canvas canvas=holder.lockCanvas(); try { synchronized (holder) { onDraw(canvas); } } catch (Exception e) { }finally{ if (canvas!=null) { holder.unlockCanvasAndPost(canvas); } } } //实现SurfaceHolder.Callback中的方法 public void surfaceChanged(SurfaceHolder holder, int format, int width,int height) { } //实现SurfaceHolder.Callback中的方法 public void surfaceDestroyed(SurfaceHolder holder) { } }