我可以确认您的图像缩放功能适用于 Oracle Java 1.8。我无法让NSImage hack 在 java 1.7 或 1.8 上工作。我认为这只适用于 Mac 的 Java 6...
除非其他人有更好的解决方案,否则我要做的是:
创建两组图标。
如果您有一个48pixel 宽度图标,请创建一个48px @normal DPI 和另一个96px 和2x DPI。将2xDPI 图像重命名为@2x.png 以符合苹果命名标准。
子类ImageIcon 并称它为RetinaIcon 或其他。
您可以按如下方式测试 Retina 显示屏:
public static boolean isRetina() {
boolean isRetina = false;
GraphicsDevice graphicsDevice = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
try {
Field field = graphicsDevice.getClass().getDeclaredField("scale");
if (field != null) {
field.setAccessible(true);
Object scale = field.get(graphicsDevice);
if(scale instanceof Integer && ((Integer) scale).intValue() == 2) {
isRetina = true;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return isRetina;
}
确保@Override新ImageIcon类的宽度和高度如下:
@Override
public int getIconWidth()
{
if(isRetina())
{
return super.getIconWidth()/2;
}
return super.getIconWidth();
}
@Override
public int getIconHeight()
{
if(isRetina())
{
return super.getIconHeight()/2;
}
return super.getIconHeight();
}
一旦您对视网膜屏幕进行了测试并覆盖了您的自定义宽度/高度方法,您就可以自定义 painIcon 方法,如下所示:
@Override
public synchronized void paintIcon(Component c, Graphics g, int x, int y)
{
ImageObserver observer = getImageObserver();
if (observer == null)
{
observer = c;
}
Image image = getImage();
int width = image.getWidth(observer);
int height = image.getHeight(observer);
final Graphics2D g2d = (Graphics2D)g.create(x, y, width, height);
if(isRetina())
{
g2d.scale(0.5, 0.5);
}
else
{
}
g2d.drawImage(image, 0, 0, observer);
g2d.scale(1, 1);
g2d.dispose();
}
我不知道这将如何与多个屏幕一起使用 - 还有其他人可以帮助解决这个问题吗???
希望这段代码能有所帮助!
杰森·巴拉克劳。
以下是使用上述缩放的示例:
RetinaIcon is on the left. ImageIcon is on the right