Android、Java 和二维绘图

发布于 2024-10-14 04:01:33 字数 422 浏览 1 评论 0原文

一直试图在 onDraw(Canvas canvas) 方法之外绘制到 android 视图上。

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

我想保持上面的显示,同时在屏幕上绘制另一个字符 - 取决于 xPosition 和 yPosition。

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

我对 java 和 2d 图形还很陌生。安卓。

提前致谢

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 in java & android.

Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

古镇旧梦 2024-10-21 04:01:33

您需要遵循这样的模式:

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();
}

所有绘图都发生在 OnDraw 方法中。 OnDraw 将在需要时被调用。您可以通过在另一个方法中调用 invalidate 来强制 OnDraw 运行。在OnDraw方法中调用invalidate是没有意义的(也许它还会导致不稳定的行为,因为OnDraw刚执行完后需要再次运行)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文