开发者

Android, Java & 2d Drawing

开发者 https://www.devze.com 2023-02-06 20:37 出处:网络
Been trying to draw onto an android view outside the onDraw(Canvas canvas) method. @Overrides public void onDraw(Canvas canvas) {

Been trying to draw onto an android view outside the onDraw(Canvas canvas) method.

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

I want to keep the above displayed, while drawing another character onto the screen - depending on xPosition and yPosition.

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

I'm pretty new to 2d graphics i开发者_JAVA百科n java & android.

Thanks in advance


You need to follow a pattern like this:

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 happens in OnDraw method. OnDraw will be called whenever is needed. You can force OnDraw to run by calling invalidate in another method. It is meaningless to call invalidate in OnDraw method (perhaps it could also cause unstable behavior, as OnDraw would need to run again after it had just finished executing).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号