Android createBitmap截取实现移动的游戏背景

createBitmap方法能够截取源位图不同位置的块,实现游戏背景的移动

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(MainActivity.this));
    }
    class MyView extends View{
        //背景图实际高度
        final int BACK_HEIGHT=1700;
        //背景图和飞机
        private Bitmap back;
        private Bitmap plane;
        final int WIDTH=640,HEIGHT=880;
        //Matrix实例用于控制缩放
        private Matrix matrix=new Matrix();
        //图片开始的Y坐标
        private int StartY=BACK_HEIGHT-HEIGHT;
        public MyView(Context context) {
            super(context);
            back=BitmapFactory.decodeResource(context.getResources(), R.drawable.back_img);
            //获取窗口管理器
            WindowManager windowManager=getWindowManager();
            Display display=windowManager.getDefaultDisplay();
            DisplayMetrics metrics=new DisplayMetrics();
            display.getMetrics(metrics);
            //获得屏幕宽度
            float screenWidth=metrics.widthPixels;
            //确定缩放比例
            float scale=screenWidth/WIDTH;
            matrix.setScale(scale, scale);
            plane=BitmapFactory.decodeResource(context.getResources(), R.drawable.plane);
            final Handler handler=new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    if(msg.what==0x123){
                        //图片向上移动/回到初始状态
                        if(StartY<3){
                            StartY=BACK_HEIGHT-HEIGHT;
                        }else{
                            StartY-=3;
                        }
                    }
                    //通知VIew重绘(调用OnDraw方法)
                    invalidate();
                }
            };
            //每100ms移动一次
            new Timer().schedule(new TimerTask() {
                
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    handler.sendEmptyMessage(0x123);
                }
            }, 0,100);
        }
        @Override
        protected void onDraw(Canvas canvas) {
            //截取背景图的一段作为实际绘制的背景图
            Bitmap bitmap2=Bitmap.createBitmap(back,0,StartY,WIDTH,HEIGHT,matrix,false);
            canvas.drawBitmap(bitmap2, 0, 0,null);
            canvas.drawBitmap(plane, 320,700, null);
        }
    }

你可能感兴趣的:(Android createBitmap截取实现移动的游戏背景)