D
D
Dmitry Smerks2018-11-11 10:15:11
Android
Dmitry Smerks, 2018-11-11 10:15:11

Newbie question on Android Studio graphics. How does canvas work?

Guys, help, please, a newbie in Android
Ufff, I don’t know where to start, the very first question, I hope you
can help there is a protected void onDraw(Canvas canvas) method that starts the level display on the canvas and fires the Timer call.

Timer t = new Timer(player,canvas); //player объект моего игрока где координаты и свой paint
t.start();//Запускаем таймер

Then the timer calls the update(player,canvas) method at intervals of a second, it gives the same Canvas object and the same player object there. But then an error appears in it, or rather, just a crash of the application
Here is update (c, p);
The code
protected void update (Player player,Canvas canvas){
       player.setX1(player.getX1() + Vx);
       player.setY1(player.getY1() + Vy);
       Log.d("MyTag",String.valueOf(player.getX1()));
      Log.d("MyTag",String.valueOf(player.getY1()));
      try {if (canvas != null){
          canvas.drawCircle(player.getX1(), player.getY1(), player.getRadius(), player.getPaint());} //на этой строке происходит вылет. Canvas не NULL. По идее можно рисовать
      }
    catch (Exception e){Log.d("MyTag","NULL");}
    }

Here is the Timer
Code
public class Timer extends CountDownTimer {
        int i;
        public Player player;
        public Canvas  canvas;


        public Timer(Player player, Canvas canvas) {
            super(Integer.MAX_VALUE, 1000);
            this.player=player;
            this.canvas=canvas;

        }


        @Override
        public void onTick(long millisUntilFinished) {
            update(this.player,this.canvas);
            i+=1;
            Log.d("MyLog",Integer.toString(i));
        }

        @Override
        public void onFinish() {

        }

Guys, please help. All were newbies

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Chvarkov, 2018-11-12
@SmerxDimas

To begin with, it is better to use SurfaceView for this.
But if we talk about the current implementation, then do not draw on canvas in a timer. Change the player's coordinates and call the view's invalidate() method. And in the onDraw method, take the coordinates and redraw the canvas

G
GavriKos, 2018-11-11
@GavriKos

1) Code - in the "code" tag. it's unreadable.
2) Logs, errors - where? There are line numbers, and wording, and that's it. You should ALWAYS start with logs.
3) Using a blank canvas for the game is not a good idea. Unless it's a tic-tac-toe game. At least for a while the canvas will not pull a dynamic picture.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question