调用/更新视图onDraw()

时间:2013-10-21 12:27:41

标签: android eclipse ondraw invalidation

我对java编程很新。现在我正在为课堂写一个小小的平台游戏。我面临的问题如下:我向我的bitmap画了一个canvas个男人。如果你触摸屏幕的右半边,他应该向右移动。屏幕左侧同样的事情。我试图在单独的“onDraw”中回忆CanvasClass方法,该方法扩展View Class并每次更改绘制的bitmap的变量。 帮助我使用invalidate / postInvalidate方法,我似乎无法理解它!谢谢 :) 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;
}

}

如果您还有其他需求,请询问! 我将每隔5-10分钟检查一次回复,谢谢:)

2 个答案:

答案 0 :(得分:0)

你的问题有什么特别之处?

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

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

参考

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

答案 1 :(得分:0)

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