Use of SurfaceView in Android game development-android learning journey (5)
SurfaceView and View
In the main ui thread, View directly responds to user operations and distributes tasks. However, complicated tasks may cause blocking.
SurfaceView does not have this problem, so that it directly retrieves images from memory and so on. More importantly, SurfaceView can change the Ui through threads outside the main thread.
Use
Ui updates are divided into active updates and passive updates. For passive updates, the update of the control is based on time, and the frequency is generally relatively low. Therefore, you are inclined to select View to complete the update.
For active updates, the update frequency is faster. For example, if the timer updates the screen, the first version uses SurfaceView.
Instance code:
Public class MyView extends SurfaceView implements SurfaceHolder. callback {public MyView (Context context) {super (context); getHolder (). addCallback (this);} public void draw () {// lock the Canvas canvas = getHolder (). lockCanvas (); // remember to unlock the canvas getHolder (). unlockCanvasAndPost (canvas);} @ Override public void surfaceCreated (SurfaceHolder holder) {// TODO Auto-generated method stub} @ Override public void surfaceChanged (SurfaceHolder holder, int format, int width, int height) {// TODO Auto-generated method stub} @ Override public void surfaceDestroyed (SurfaceHolder holder) {// TODO Auto-generated method stub }}
Use SuifaceView to draw a simple image
Draw a Red Square:
public class MyView extends SurfaceView implements SurfaceHolder.Callback{ private Paint paint = null; public MyView(Context context) { super(context); paint = new Paint(); paint.setColor(Color.RED); getHolder().addCallback(this); } public void draw(){ Canvas canvas = getHolder().lockCanvas(); canvas.drawColor(Color.WHITE); canvas.drawRect(0, 0, 100, 100, paint); getHolder().unlockCanvasAndPost(canvas); } @Override public void surfaceCreated(SurfaceHolder holder) { // TODO Auto-generated method stub draw(); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } @Override public void surfaceDestroyed(SurfaceHolder holder) { // TODO Auto-generated method stub }}
Note that you must start painting after the surfaceCreated method and finish painting before the surfaceDestroyed method.