我使用Slick2DLWJGL,我想问一个问题,当我运行它时,如何更改taskbar中的游戏图标。

最佳答案

实际上,取决于您要精确执行的操作可能非常困难。

最简单的方法是使用Slick2d方法:在GameContainer中,您可以使用setIcon(String)方法。

但是在我的个人项目之一中,我在开始时使用Slick加载图像时遇到了一些困难。所以我用LWJGL寻找另一个解决方案:

public static void main(String[] args) {
    AppGameContainer app;
    try {

        app = new AppGameContainer(new Main("Anode"));
        org.lwjgl.opengl.Display.setIcon(loadIcon("resources/images/logo.png", app));
}

public static ByteBuffer[] loadIcon(String filepath,AppGameContainer app)
{
    BufferedImage image = null;
    try
    {
        image = ImageIO.read(app.getClass().getClassLoader().getResource(filepath));
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    ByteBuffer[] buffers = new ByteBuffer[3];
    buffers[0] = loadIconInstance(image, 128);
    buffers[1] = loadIconInstance(image, 32);
    buffers[2] = loadIconInstance(image, 16);
    return buffers;
}

private static ByteBuffer loadIconInstance(BufferedImage image, int dimension)
{
    BufferedImage scaledIcon = new BufferedImage(dimension, dimension, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = scaledIcon.createGraphics();
    double ratio = 1;
    if(image.getWidth() > scaledIcon.getWidth())
    {
        ratio = (double) (scaledIcon.getWidth()) / image.getWidth();
    }
    else
    {
        ratio = (int) (scaledIcon.getWidth() / image.getWidth());
    }
    if(image.getHeight() > scaledIcon.getHeight())
    {
        double r2 = (double) (scaledIcon.getHeight()) / image.getHeight();
        if(r2 < ratio)
        {
            ratio = r2;
        }
    }
    else
    {
        double r2 =  (int) (scaledIcon.getHeight() / image.getHeight());
        if(r2 < ratio)
        {
            ratio = r2;
        }
    }
    double width = image.getWidth() * ratio;
    double height = image.getHeight() * ratio;
    g.drawImage(image, (int) ((scaledIcon.getWidth() - width) / 2), (int) ((scaledIcon.getHeight() - height) / 2),
            (int) (width), (int) (height), null);
    g.dispose();

    byte[] imageBuffer = new byte[dimension*dimension*4];
    int counter = 0;
    for(int i = 0; i < dimension; i++)
    {
        for(int j = 0; j < dimension; j++)
        {
            int colorSpace = scaledIcon.getRGB(j, i);
            imageBuffer[counter + 0] =(byte)((colorSpace << 8) >> 24 );
            imageBuffer[counter + 1] =(byte)((colorSpace << 16) >> 24 );
            imageBuffer[counter + 2] =(byte)((colorSpace << 24) >> 24 );
            imageBuffer[counter + 3] =(byte)(colorSpace >> 24 );
            counter += 4;
        }
    }
    return ByteBuffer.wrap(imageBuffer);
}


我真的建议您使用Slick2d解决方案,如果您达不到目标,则可以切换到更复杂的解决方案

10-07 13:05