gpt4 book ai didi

java - Android 使 onDraw 无效

转载 作者:行者123 更新时间:2023-12-02 06:00:49 27 4
gpt4 key购买 nike

我刚刚开始学习android,我在网上搜索了如何强制onDraw更新,我发现的唯一方法是无效的。它可以工作一段时间,但之后就不再更新了。

这是我的代码:

package com.andrewxd.test01;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class Game extends View {

private Bitmap enemy;
private Paint dpaint;
private float x,y;

public Game(Context context) {
super(context);
enemy = BitmapFactory.decodeResource(getResources(), R.drawable.enemy);
enemy = Bitmap.createScaledBitmap(enemy, 300 , 300, false);
dpaint = new Paint();
x = 0;
y = 0;
}

@Override
protected void onDraw(Canvas canvas){
canvas.drawBitmap(enemy, x, y, dpaint);
Log.d("GAME", "REDRAWN");
}

@Override
public boolean onTouchEvent(MotionEvent event){
x = event.getX();
y = event.getY();
invalidate();
return true;
}
}

有人可以建议我在 x 和 y 更改后重绘的更好方法吗?

最佳答案

来自API-Docs :

The basic cycle of a view is as follows:

  • An event comes in and is dispatched to the appropriate view. The view handles the event and notifies any listeners.
  • If in the course of processing the event, the view's bounds may need to be changed, the view will call requestLayout().
  • Similarly, if in the course of processing the event the view's appearance may need to be changed, the view will call invalidate().
  • If either requestLayout() or invalidate() were called, the framework will take care of measuring, laying out, and drawing the tree as appropriate.

所以,这可能是做到这一点的方法!

关于java - Android 使 onDraw 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22690113/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com