01 | package com.sarnath.activity; |
02 |
03 | import java.util.Timer; |
04 | import java.util.TimerTask; |
05 |
06 | import android.app.Activity; |
07 | import android.content.Context; |
08 | import android.graphics.Bitmap; |
09 | import android.graphics.BitmapFactory; |
10 | import android.graphics.Canvas; |
11 | import android.graphics.Matrix; |
12 | import android.os.Bundle; |
13 | import android.os.Handler; |
14 | import android.os.Message; |
15 | import android.view.Display; |
16 | import android.view.View; |
17 |
18 | public class GbdemoActivity extends Activity { |
19 | public void onCreate(Bundle savedInstanceState) { |
20 | super .onCreate(savedInstanceState); |
21 |
22 | setContentView( new MyView( this )); |
23 | |
24 | } |
25 |
26 | class MyView extends View { |
27 | |
28 | // 得到容器分辨率 高,宽 |
29 | Display display = getWindowManager().getDefaultDisplay(); |
30 | |
31 | // 记录背景图片实际的高度 |
32 | final int BACK_HEIGHT = 960 ; |
33 | // 背景图片 |
34 | private Bitmap back; |
35 | private Bitmap plane; |
36 | private Bitmap map_01; |
37 | // 背景图片的开始位置 320 480 |
38 | final int WIDTH = display.getWidth(); |
39 | final int HEIGHT = display.getHeight(); |
40 | private int startY = BACK_HEIGHT - HEIGHT; |
41 |
42 | public MyView(Context context) { |
43 | super (context); |
44 | // 获取背景图片 |
45 | back = BitmapFactory.decodeResource(context.getResources(), |
46 | R.drawable.map_02); |
47 | plane = BitmapFactory.decodeResource(context.getResources(), |
48 | R.drawable.plan_1); |
49 | final Handler handler = new Handler() { |
50 |
51 | public void handleMessage(Message msg) { |
52 | if (msg.what == 0x123 ) { |
53 | // 重新开始移动 |
54 | if (startY <= 0 ) { |
55 | startY = BACK_HEIGHT - HEIGHT; |
56 | } else { |
57 | startY -= 10 ; |
58 | } |
59 | } |
60 | //该函数的作用是使整个窗口客户区无效。窗口的客户区无效意味着需要重绘 |
61 | invalidate(); |
62 | } |
63 | }; |
64 | new Timer().schedule( new TimerTask(){ |
65 |
66 | @Override |
67 | public void run() { |
68 | handler.sendEmptyMessage( 0x123 ); |
69 | } |
70 | |
71 | |
72 | }, 0 , 100 ); |
73 | } |
74 | |
75 | |
76 | @Override |
77 | protected void onDraw(Canvas canvas) { |
78 | // 根据原始位图和Matrix创建新图片 |
79 | Bitmap bitmap2 = Bitmap.createBitmap(back, 0 , startY, WIDTH,HEIGHT); |
80 | //设置拉伸的比例 实现 等腰梯形 |
81 | float [] src= new float [] { 0 , 0 , WIDTH, 0 , WIDTH, HEIGHT, 0 , HEIGHT }; |
82 | float [] dst= new float [] { 100 , 0 , 200 , 0 , 500 , 450 , - 150 , 450 }; |
83 | //获取Matrix对象 实现 图片拉伸 |
84 | Matrix mMatrix= new Matrix(); |
85 | mMatrix.setPolyToPoly(src, 0 , dst, 0 , src.length >> 1 ); |
86 | // 绘制新位图 |
87 | canvas.drawBitmap(bitmap2, mMatrix, null ); |
88 | |
89 | //绘制小飞机 |
90 | canvas.drawBitmap(plane, 160 , 380 , null ); |
91 | } |
92 | } |
93 | } |