简体   繁体   中英

Create an image from part of an image in Java?

I would like to create an ImageIcon from part of an image which I can then set as the icon for a JButton. However, the Image (which I convert to an ImageIcon) should come from part of an image (one tile from my terrain tileset). How can I do this in Java, or is it better to have all my tiles as separate images rather than in a tileset?

First you would create a BufferedImage and then call getSubImage(int x, int y, int w, int h) on the BufferedImage. You could then take the Image returned and make an ImageIcon with it.

If you need to subdivide the image and create a bunch of images, a for loop or even two nested for loops could help you do this. You will have to know of course the widths and heights of the main image and the sub images for this to work, but I assume that you already know this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM