1

I'm fairly new to programming in java. Right now I'm writing a little platformer game for class. The problem im facing is the following: I drew a little bitmap of a man to my canvas. if you touch the right half of the screen he should move right. same thing for the left side of the screen. im trying to recall the onDraw method in my seperate "CanvasClass" which extends the View Class and change the variables of the drawn bitmap everytime. Help me with the invalidate/postInvalidate method, i cant seem to understand it! thanks :) GameActivity:

public class GameActivity extends Activity implements OnTouchListener{

CanvasClass ourView;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);            
    ourView = new CanvasClass(this);
    setContentView(ourView);     
}   

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onTouch(View v, MotionEvent me) {
    return false;
}

}

CanvasClass:

public class CanvasClass extends View implements OnTouchListener {

Bitmap mBackground, BackScaled,bobOri, bobScale;
int width, height,bobWidth = 33, bobHeight = 93;
float meX = 20,meY = 400;
Canvas canvas;

public CanvasClass(Context context) {
    super(context);
    ((Activity) getContext()).requestWindowFeature(Window.FEATURE_NO_TITLE);
    ((Activity) getContext()).getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

    DisplayMetrics displaymetrics = getResources().getDisplayMetrics();
    height =displaymetrics.heightPixels;
    width = displaymetrics.widthPixels;
    mBackground = BitmapFactory.decodeResource(getResources(), R.drawable.background); 
    ((Activity) getContext()).getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    BackScaled = Bitmap.createScaledBitmap(mBackground, width, height,true);

    bobOri = BitmapFactory.decodeResource(getResources(),R.drawable.bobertfront);
    bobScale = Bitmap.createScaledBitmap(bobOri, bobWidth,bobHeight, true);

}
@Override
protected void onDraw(Canvas canvas){
    super.onDraw(canvas);
    canvas.drawBitmap(BackScaled,0,0,null);
    canvas.drawBitmap(bobScale,20,410,null);

}

@Override
public boolean onTouch(View v, MotionEvent me) {

    return true;
}

}

If you need anything else, please ask! I will be checking every 5-10 minutes for replies, thanks :)

4

2 回答 2

0

在我看来你需要刷新 onDraw 实现 onPause 方法

于 2013-10-21T13:36:35.547 回答
0

你的问题是什么?

要再次调用 onDraw(),您需要调用 invalidate()。invalidate 和 postInvalidate 的区别在于 invalidate 需要从 UI 线程调用,而 postInvalidate 可以从其他线程调用...

在您的情况下,无效应该可以解决问题。

参考

http://developer.android.com/reference/android/view/View.html#invalidate()http://developer.android.com/reference/android/view/View.html#postInvalidate()

于 2013-10-21T13:12:01.150 回答