所以,我一直在修改 Minecraft 一段时间,我看到了它是如何生成按钮的。它需要一个非常宽的按钮图像,占据左侧的一部分,占据右侧的一部分,然后将两者重新组合在一起形成一个较小的图像。
很抱歉,我无法用语言很好地解释这一点,所以让我向您展示一下糟糕的 Paint.Net 技能:
但是,我无法让它工作,结果是这样的:
这是我的代码的一部分:
public class ComponentToolbarButton extends JComponent implements MouseListener {
private static final int HEIGHT = 40;
// ... other methods here
private BufferedImage getImageBasedOnWidth(Graphics g) {
BufferedImage finalImage = null;
BufferedImage rawImage = null;
// Try/catch block to initialize rawImage
// Setting font and things here
int compWidth = determineComponentWidth(g); // Returns the (should-be) width of the component
if (compWidth != getWidth()) {
setPreferredSize(new Dimension(compWidth, HEIGHT)); // Just making sure :)
}
finalImage = new BufferedImage(compWidth, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics finalImageGraphics = finalImage.getGraphics();
// Draw left side:
finalImageGraphics.drawImage(rawImage, 0, 0, 0, compWidth / 2, 0, 0, compWidth, HEIGHT, null);
// Draw right side:
finalImageGraphics.drawImage(rawImage, compWidth / 2, 0, compWidth, HEIGHT, rawImage.getWidth() / 2 - compWidth,
0, rawImage.getWidth(), rawImage.getHeight(), null);
return finalImage;
}
}
提前致谢!(顺便说一句,我试图尽可能地缩短代码)