标签:pcr pack getwidth setflag void his str tco factor
新建一个类,继承View
package com.topcrab.mygame; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; import android.view.WindowManager; /** * Created by Administrator on 2017-07-24. */ public class GameView extends View { Bitmap bitmap; int mapwidth; int mapheight; public int getRunleft() { return runleft; } public void setRunleft(int runleft) { this.runleft = runleft; } private int runleft; public int getRuntop() { return runtop; } public void setRuntop(int runtop) { this.runtop = runtop; } private int runtop; public GameView(Context context, AttributeSet set) { super(context, set); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.fly); mapheight = bitmap.getHeight(); mapwidth = bitmap.getWidth(); } @Override protected void onDraw(Canvas canvas) { canvas.drawBitmap(bitmap, runleft-mapwidth/2, runtop-mapheight/2, null); super.onDraw(canvas); } }
默认加载页面
package com.topcrab.mygame; import android.app.Activity; import android.content.Context; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.MotionEvent; import android.view.Window; import android.view.WindowManager; public class MainActivity extends Activity { GameView gameView=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //屏幕无标题 requestWindowFeature(Window.FEATURE_NO_TITLE); //全屏显示 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); gameView=(GameView) findViewById(R.id.GameId); //获取屏幕宽度和高度 WindowManager manager = this.getWindowManager(); DisplayMetrics outMetrics = new DisplayMetrics(); manager.getDefaultDisplay().getMetrics(outMetrics); int width = outMetrics.widthPixels; int height = outMetrics.heightPixels; //设置飞机初始状态时的位置 gameView.setRuntop(height-100); gameView.setRunleft(width/2); } //屏幕触碰事件 @Override public boolean onTouchEvent(MotionEvent event) { float left=event.getX(); float top=event.getY(); gameView.setRunleft((int)left); gameView.setRuntop((int)top); gameView.invalidate(); return super.onTouchEvent(event); } }
xml文件
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.topcrab.mygame.MainActivity"> <com.topcrab.mygame.GameView android:id="@+id/GameId" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </android.support.constraint.ConstraintLayout>
标签:pcr pack getwidth setflag void his str tco factor
原文地址:http://www.cnblogs.com/imluzhi/p/7228107.html