Android, Java & 2d Drawing

I tried to draw on the android representation outside the onDraw (Canvas canvas) method.

@Overrides
public void onDraw(Canvas canvas) {
    c = canvas;
    canvas.drawLine(0, 50, 100, 50, paint);
    invalidate();
}

I want the displayed above to be displayed when drawing another character on the screen - depending on xPosition and yPosition.

public void drawPlayer(int x, int y){
        c.drawCircle(x, y, 5, paint);
    }

I am new to 2D graphics in java and android.

Thanks in advance

+3
source share
1 answer

You need to follow the pattern:

private boolean isPlayerVisible = false;
private int playerPosX;
private int playerPosY;

@Overrides
public void onDraw(Canvas canvas) {
    c = canvas;
    canvas.drawLine(0, 50, 100, 50, paint);
    if (isPlayerVisible) {
       Paint paint= new Paint();
       paint.setColor(0xFFFFFFFF);
       paint.setStrokeWidth(1);
       c.drawCircle(playerPosX, playerPosY, 5, paint);
    }
}    

private void setPlayersPos(int x, int y) {
  playerPosX = x;
  playerPosY = y;
  isPlayerVisible= true;
  invalidate();
}

All drawing takes place in the OnDraw method. OnDraw will be called whenever necessary. You can force OnDraw to run by calling invalidate with another method. It is useless to call invalidate in the OnDraw method (perhaps this can also lead to unstable behavior, since OnDraw will need to be started again after it has just finished executing).

+2

Source: https://habr.com/ru/post/1787673/


All Articles