0

下面我有一个简单的方法来将一组对象绘制到java.awt.applet.Applet. 我认为这非常简单,但最终只是将对象绘制为小程序左上角的单个像素。这个想法是 Display 类接受一组相当轻量级的对象,这些对象扩展GameObject并包含有关它们在屏幕上的位置、大小和外观的信息,然后将它们逐个像素地绘制到小程序上,按比例拉伸和定位它们取决于指定的显示高度和宽度。在测试这个时,我将 的宽度和高度设置Display为 128,并将两个对象传递给Display,它们都是 32 像素的正方形(都返回32getWidth()getHeight(),一个是红色的,24返回getX()getY(), 另一个是蓝色并16返回getX()getY()。我将Displaya放入javax.swing.JFrame并使用 ajava.awt.BorderLayout以确保它填充框架(我add(display, java.awt.BorderLayout.CENTER);在上述 中使用javax.swing.JFrame)。

据我所知,这应该是绘制一个距离顶部和左侧边缘 16 像素的蓝色 32 像素正方形和一个被另一个遮挡或遮挡一部分的红色 32 像素正方形。但是,我得到的只是Display. 无论窗口有多大或多小,这都是一致的。

代码


public class Display extends java.awt.applet.Applet
{
  private int w,h;
  private ArrayPP<GameObject> gameObjects;//ArrayPP is my way of making a dynamically expanding array. It is similar to Vector, but has many more useful methods I use elsewhere.

  public Display(int width, int height)
  {
    w = width;
    h = height;
  }

  public void addGameObject(GameObject go)
  {
    gameObjects.add(go);
  }

  public void refresh(java.awt.Graphics g)
  {
    int x, y, w, h;
    final int W = getWidth(), H = getHeight();
    for (GameObject go : gameObjects)//Draw all objects
      for (x = go.getX(), y = go.getY(), w = go.getWidth() + x, h = go.getHeight() + y; y < h; y++)//Draw all lines of the object
        for (x = go.getX(); x < w; x++)//Draw all the pixels on this line of the object
        {
          g.setColor(go.getColorForPixel(x, y));
          g.fillRect((x / this.w) * W, (y / this.h) * H, w/W, h/H);
        }
  }
}

 

public interface GameObject
{
  public int getX();
  public int getY();
  public int getWidth();
  public int hetHeight();
  public java.awt.Color getColorForPixel(int x, int y);
}

问题


为什么java.awt.Graphics.fillRect(int x, int y, int width, int height)只画小程序的左上角?

解决方案


解决方案在于读取的行

          g.fillRect((x / this.w) * W, (y / this.h) * H, w/W, h/H);

其中整数计算导致所有值都为0。解决方案如下:

          g.fillRect((int)(((float)x/(float)this.w) *W),
                     (int)(((float)y/(float)this.h) *H),
                     (int)((float)W/(float)w),
                     (int)((float)H/(float)h));
4

1 回答 1

4

问题在于

(x / this.w) * W

如果 x 和 this.w 都是整数并且 x

将 x 和 w 中的一个或多个转换为 float 以强制进行浮点除法。

(int)(((float)x/(float)this.w) *W)
于 2011-11-30T20:40:03.710 回答