Andorid學習之遊戲背景移動

來源:互聯網
上載者:User

藉助Bitmap和createBitmap方法可以挖取源位元影像的一塊,這樣可以在程式中通過定時器不斷的挖取源位元影像中的不同塊,給遊戲者一種背景在移動,即對象在向前移動的假象。


import java.util.Timer;import java.util.TimerTask;import android.app.Activity;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;public class MoveBack extends Activity{@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(new MyView(this));}class MyView extends View{// 記錄背景位元影像的實際高度final int BACK_HEIGHT = 1700;// 背景圖片private Bitmap back;private Bitmap plane;// 背景圖片的開始位置final int WIDTH = 480;final int HEIGHT = 800;private int startY = BACK_HEIGHT - HEIGHT;public MyView(Context context){super(context);back = BitmapFactory.decodeResource(context.getResources(),R.drawable.back_img);plane = BitmapFactory.decodeResource(context.getResources(),R.drawable.plane);final Handler handler = new Handler(){public void handleMessage(Message msg){if (msg.what == 0x123){// 重新開始移動if (startY <= 0){startY = BACK_HEIGHT - HEIGHT;}else{startY -= 3;}}invalidate();}};new Timer().schedule(new TimerTask(){public void run(){handler.sendEmptyMessage(0x123);}}, 0, 100);}public void onDraw(Canvas canvas){// 根據原始位元影像和Matrix建立新圖片Bitmap bitmap2 = Bitmap.createBitmap(back, 0, startY, WIDTH, HEIGHT);  // 繪製新位元影像canvas.drawBitmap(bitmap2, 0, 0, null);// 繪製飛機canvas.drawBitmap(plane, 160, 360, null);}}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.