This article focuses on how to make custom views move.
As shown in the following figure, we can customize three views.
One is the unit Tileview, used to draw Blocks
The first is that the snake, the snake, and the snake, inherit to the TileView.
One is the background BackgroundView.
This article focuses on the introduction of the snake view because only the snake is dynamic.
As mentioned above, there are two ways to refresh the View: one in the UI thread and the other in the non-UI thread (SurfaceView is generally used ).
Simple, not very frequent Refresh can be done in the UI thread. This method is used for the snakview. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + usvqxmq1z9ajuw.vcd4kpha + encrypt/decrypt/L2bbI1L3C/decrypt = "brush: java;"> class RefreshHandler extends Handler {@ Override public void handleMessage (Message msg) {// update the status of the snake. this. update (); // refresh the view of the snake. this. invalidate ();} public void sleep (long delayMillis) {this. removeMessages (0); sendMessageDelayed (obtainMessage (0), delayMillis );}};
2. Rewrite the ondraw method to construct a square consisting of a snake body.
@Override public void onDraw(Canvas canvas) { super.onDraw(canvas); for (int x = 0; x < mXTileCount; x += 1) { for (int y = 0; y < mYTileCount; y += 1) { if (mTileGrid[x][y] > 0) { canvas.drawBitmap(mTileArray[mTileGrid[x][y]], mXOffset + x * mTileSize, mYOffset + y * mTileSize, mPaint); } } } }
Convert the screen into a matrix. The number of rows in the matrix is mXTileCount, and the number of columns is mYTileCount. the corresponding element is a square. Whether to draw a square is determined by the value stored in the mTileGrid [] [] Two-dimensional array.
The actions of the snake are to modify the values in the two-dimensional mTileGrid array. Every time a View is updated, the two-dimensional array is traversed once to reconstruct the View. Therefore, the efficiency is very poor.
MXTileCount: currently, the screen X can draw blocks at most.
MYTileCount: You can draw blocks at most in the Y direction of the current screen.
Conclusion: directly refresh the View in the thread UI
Advantages: easy to implement.
Disadvantages: low efficiency, not smooth, and the view position change is very stiff, from here to there. There is no animation in the middle for coherence.