更新画布动画

时间:2017-03-03 18:06:59

标签: android animation canvas refresh invalidation

我不再需要答案了!

我创建了一个应用程序,屏幕周围应该有气泡弹跳。 一切正常,但他们并没有被抽出来。

这里是代码(不是所有代码,而是重要的代码):

泡泡班:

public class Bubble{

    private int ID;

    private float coordX;
    private float coordY;
    private float velX;
    private float velY;
    private float radius;

    private int color;

    private boolean popped;
    private boolean alive;
    private boolean dead;

    public Bubble(int coordX, int coordY, int velocityX, int velocityY, int ID, int color) {
        this.coordX = coordX;
        this.coordY = coordY;
        this.velX = velocityX;
        this.velY = velocityY;
        this.radius = 30;
        this.ID = ID;
        this.color = color;

        this.alive = true;
    }

    public void drawMe(Paint paint, Canvas canvas) {
        int paintStartColor = paint.getColor();
        paint.setColor(this.color);
        canvas.drawCircle(this.coordX, this.coordY, radius, paint);
        paint.setColor(paintStartColor);
        Log.d("Bubble","drawn bubble [" + ID + "] at (" + this.coordX + "|" + this.coordY + ")");
    }

    public void update() {

        //damit die bubble am rand anstößt und zurück prallt
        if(this.coordX - this.radius <= 0) this.velX = - this.velX;
        if(this.coordY - this.radius <= 0) this.velY = - this.velY;
        if(this.coordX + this.radius >= MainActivity.getInstance().getScreenSize().x) this.velX = - this.velX;
        if(this.coordY + this.radius >= MainActivity.getInstance().getScreenSize().y) this.velY = - this.velY;

        coordX += velX;
        coordY += velY;
        updateRadius();
//        Log.d("Bubble", "CoordX: " + coordX + ", velX: " + velX);
    }
}

绘图方法:

public void drawBubbles() {
    Paint paint = new Paint();
    for(Bubble b : bubbles) {
        b.drawMe(paint, MainActivity.getInstance().getCanvas());
    }
}

游戏循环:

while(this.isRunning()) {
      updateBubbles();   //update bubbles just calls the update() function in every bubble (for each loop)
      drawBubbles();
      //...sleep...
}

绘制所有气泡,它可以工作,但我只看到差异,当我离开(不关闭!)应用程序,然后回到它。我在循环中调用该方法,并且每秒调用60次,但为什么它不会出现在屏幕上?此外,我无法使画布无效。

1 个答案:

答案 0 :(得分:0)

我只是误用了invalidate()方法,所以在我修复它之后它工作正常。