Android 自定义 View 之移动游戏背景

借助于 Bitmap 的 createBitmap 方法可以”挖取“源位图的其中一块,这样可以在程序中通过定时器控制不断地”挖取“源位图不同位置的块,从而给用户看到背景移动的”假象“。

假设要开发经典“雷电”飞机游戏,为了给客户一个飞机在不断飞行的感觉,可以通过在这种方式来控制背景图片不断下移,这时用户就会感觉飞机在不断向上飞行。

下面是一个简单的示例程序:

package com.toby.personal.testlistview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    final private static String TAG = "Toby_Test";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new TestView(this));
    }

    class TestView extends View {

        final int BACK_HEIGHT = 1720;

        private Bitmap back;
        private Bitmap plane;

        final int WIDTH = 320;
        final int HEIGHT = 440;
        private int startY = BACK_HEIGHT - HEIGHT;

        public TestView(Context context) {
            super(context);
            back = BitmapFactory.decodeResource(context.getResources(), R.drawable.bg_long);
            plane = BitmapFactory.decodeResource(context.getResources(), R.drawable.plane);

            final Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    if (msg.what == 170416) {
                        if (startY <= 0) {
                            startY = BACK_HEIGHT - HEIGHT;
                        } else {
                            startY -= 3;
                        }
                    }
                    invalidate();
                }
            };

            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    handler.sendEmptyMessage(170416);
                }
            }, 0, 100);

        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            canvas.drawColor(Color.GRAY);
            Bitmap bitmap = Bitmap.createBitmap(back, 0, startY, WIDTH, HEIGHT);
            canvas.drawBitmap(bitmap, 0, 0, null);
            canvas.drawBitmap(plane, 100, 320, null);
        }
    }

}

该测试示例的运行效果:

《Android 自定义 View 之移动游戏背景》 plane

本文参考文献:《疯狂Android讲义 : 第2版

    原文作者:赵者也
    原文地址: https://www.jianshu.com/p/fe1866176678
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞