System Tray icon looks distorted

旧时模样 提交于 2019-12-08 15:48:42

问题


I'm trying to have an icon be added and displayed to the system tray using Java. However the icon is always either too small, or its cut off in areas. Its the second one from left in case you couldn't tell.

What am I doing wrong here? How can I get this icon to be displayed fully? What's the standard icon size to be used for system tray?

Edit: I am using AWT SystemTray and TrayIcon


回答1:


After you've retrieved the actual image resource from disk, you can resize it to the size you need by creating a "fake" one on-the-fly and taking its width.

I found that this was better than using the setImageAutoSize(true) method, as that method does not scale the image smoothly at all.

BufferedImage trayIconImage = ImageIO.read(getClass().getResource("/path/to/icon.png"));
int trayIconWidth = new TrayIcon(trayIconImage).getSize().width;
TrayIcon trayIcon = new TrayIcon(trayIconImage.getScaledInstance(trayIconWidth, -1, Image.SCALE_SMOOTH));



回答2:


To display the icon at an optimal size, you will need to manually resize it to the correct size. This correct size can differ between operating systems and preferences, so Java provides a method to acquire the task bar icon dimensions, which are 16x16 in the case of your example image.

if (SystemTray.isSupported()) {
    SystemTray tray = SystemTray.getSystemTray();
    Dimension trayIconSize = tray.getTrayIconSize();
    // resize icon image to trayIconSize
    // create your tray icon off of the resized image
}



回答3:


According to TrayIcon.setImageAutoSize(boolean).

Sets the auto-size property. Auto-size determines whether the tray image is automatically sized to fit the space allocated for the image on the tray. By default, the auto-size property is set to false.

If auto-size is false, and the image size doesn't match the tray icon space, the image is painted as-is inside that space — if larger than the allocated space, it will be cropped.




回答4:


I've ended up combining some of these answers to make the code I'm using.

This is producing a good looking icon in my system tray from a png that starts at 100x100.

It's worth noting that on a retina MacBook the icon looks worse scaled down. So I do a check elsewhere to see if it's running on a mac and don't apply this if it is.

public Image imageForTray(SystemTray theTray){

    Image trayImage = Toolkit.getDefaultToolkit().getImage("my100x100icon.png");
    Dimension trayIconSize = theTray.getTrayIconSize();
    trayImage = trayImage.getScaledInstance(trayIconSize.width, trayIconSize.height, Image.SCALE_SMOOTH);

    return trayImage;
}


来源:https://stackoverflow.com/questions/12287137/system-tray-icon-looks-distorted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!