1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
/**
* Create a cursor than can be used with any component from an icon.
* The icon can be any kind of image that can be read with ImageIO (jpg, png, gif, bmp)
* and is specified by its path.
* @param imagePath Name of the image file to read
* @param cursorName name of the cursor for later use
* @return the Cursor that can be applied to a component.
*/
public static Cursor createCursorFromIcon(String imagePath, String cursorName) {
// Open the file specified by the path
File iconFile = new File(imagePath);
// create a buffered image from the file
BufferedImage icon = null;
try {
icon = ImageIO.read(iconFile);
} catch (IOException e) {
e.printStackTrace();
return null;
}
// The window system may not be able to use the specified image.
// Some window system are not able to display cursors with certain size.
// We then need to resize the image to the compatible dims.
Dimension compatibleDims = Toolkit.getDefaultToolkit().getBestCursorSize(icon.getWidth(), icon.getHeight());
// create a new image with a compatible dimentions
Image compatibleIcon = null;
if (compatibleDims.width == icon.getWidth() || compatibleDims.height == icon.getHeight()) {
// no need for resize just use the icon
compatibleIcon = icon;
} else if (icon.getWidth() < compatibleDims.width && icon.getHeight() < compatibleDims.height) {
// the icon is smaller than the compatible size
// We create a new image with a compatible size and copy the icon on the top left corner.
// The remaining part of the icon is kept transparent, so the cursor rendering
// is actually unchanged
BufferedImage compatibleIconB = new BufferedImage(compatibleDims.width, compatibleDims.height, BufferedImage.TYPE_INT_ARGB);
// by default set the image to transparent
for (int i = 0; i < compatibleIconB.getWidth(); i++) {
for (int j = 0; j < compatibleIconB.getHeight(); j++) {
compatibleIconB.setRGB(i, j, 0);
}
}
// then copy the icon in the top left part
for (int i = 0; i < icon.getWidth(); i++) {
for (int j = 0; j < icon.getHeight(); j++) {
// we're lucky since getRGB return the value as ARGB
compatibleIconB.setRGB(i, j, icon.getRGB(i, j));
}
}
compatibleIcon = compatibleIconB;
} else {
// the icon is larger than the compatible size
// we then need to reduce it
compatibleIcon = icon.getScaledInstance(compatibleDims.width, compatibleDims.height, Image.SCALE_SMOOTH);
}
// finally create the Cursor
// the second parameter is quite obscure, the java doc does not help very much. But using
// (0, 0) as value works fine so let's use this.
return Toolkit.getDefaultToolkit().createCustomCursor(compatibleIcon, new Point(0, 0), cursorName);
} |
Partager