public class Test extends Activity { //SurfaceView private SurfaceView surfaceViewRect; //Holder private SurfaceHolder surfaceHolderRect; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test); //初始化 surfaceViewRect = (SurfaceView) findViewById(R.id.surfaceViewRect); surfaceHolderRect = surfaceViewRect.getHolder(); surfaceHolderRect.addCallback(callbackRectangle); surfaceHolderRect.setFormat(PixelFormat.TRANSPARENT); surfaceHolderRect.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } private SurfaceHolder.Callback callbackRectangle = new Callback() { @Override public void surfaceDestroyed(SurfaceHolder holder) { } @Override public void surfaceCreated(SurfaceHolder holder) { //Canvas Canvas canvas = holder.lockCanvas(); //背景為透明 canvas.drawColor(Color.TRANSPARENT); //畫筆 Paint paint = new Paint(); //實心=Paint.Style.FILL //空心 paint.setStyle(Paint.Style.STROKE); //畫筆顏色 paint.setColor(Color.BLUE); //繪製矩形 //left=開始x //top=開始y //right=結束x //bottom=結束y //以下方例子來說開始的位置在於(20,20) 結束地方在於(100-20,100-20) //也就是說這個矩形長寬為80 canvas.drawRect(20, 20, 100, 100, paint); holder.unlockCanvasAndPost(canvas); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } }; }
2015/10/31
Android SurfaceView透過Canvas繪製 實心/空心矩形
Code: