下面我有一个简单的方法来绘制一组对象到java.awt.applet.Applet
。我认为这是非常简单的,但它最终只是在applet的左上角将对象绘制为单个像素。其思想是Display类接受一组相当轻量级的对象,这些对象扩展GameObject
并包含有关它们在屏幕上的位置、大小和外观的信息,然后将它们逐像素地绘制到applet上,根据指定的显示高度和宽度按比例拉伸和定位它们。在测试中,我将Display
的宽度和高度设置为128,并将两个对象传递给Display
,它们都是32像素的正方形(对于getWidth()
和getHeight()
都返回32
),一个是红色的,对于getX()
和getY()
返回24
,另一个是蓝色的,对于getX()
和getY()
返回16
。我把Display
放在javax.swing.JFrame
中,并使用java.awt.BorderLayout
来确保它填充帧(我在前面提到的javax.swing.JFrame
中使用add(display, java.awt.BorderLayout.CENTER);
)。
据我所知,这应该绘制一个蓝色的32像素正方形,距离顶部和左侧边缘16像素,以及一个红色的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 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)
只绘制applet的左上角?
解决方案在
这一行 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));
问题出在
(x / this.w) * W
如果x和this。W既是整数又是x
将x和w中的一个或多个转换为float以强制进行浮点除法。
(int)(((float)x/(float)this.w) *W)