自定义背景android,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);

}

}

}

该测试示例的运行效果:

fe1866176678

plane

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值