java - 将图像拆分为可点击区域

标签 java image swing jlabel java-2d

有什么方法可以将图像分割成区域(现在是 JLabel,但如果需要我可以更改它)?
我在我的程序中使用了 swing,并且我有一个图像(在这个例子中是正方形),里面有一些三角形、星星和梯形(它可以是 JPG、PNG 等)。
这个想法是用户将在其中一个形状内单击,然后我将在用户单击的区域顶部放置另一个小图标。用户可以点击多个区域,但最终,我需要知道点击了哪些形状。

似乎有人可以吗?

最佳答案

看看我做了什么:

这是我用来测试的图片:

Original Image

图片分割后:

After Image splitting

这是来源:

import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class Test {

    private JFrame frame;
    private JLabel[] labels;
    private static String imagePath = "c:/test.jpg";
    private final int rows = 3; //You should decide the values for rows and cols variables
    private final int cols = 3;
    private final int chunks = rows * cols;
    private final int SPACING = 10;//spacing between split images

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Test().createAndShowUI();
            }
        });
    }

    private void createAndShowUI() {
        frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initComponents();
        frame.setResizable(false);
        frame.pack();
        frame.setVisible(true);
    }

    private void initComponents() {

        BufferedImage[] imgs = getImages();

        //set contentpane layout for grid
        frame.getContentPane().setLayout(new GridLayout(rows, cols, SPACING, SPACING));

        labels = new JLabel[imgs.length];

        //create JLabels with split images and add to frame contentPane
        for (int i = 0; i < imgs.length; i++) {
            labels[i] = new JLabel(new ImageIcon(Toolkit.getDefaultToolkit().createImage(imgs[i].getSource())));
            frame.getContentPane().add(labels[i]);
        }
    }

    private BufferedImage[] getImages() {
        File file = new File(imagePath); // I have bear.jpg in my working directory
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
        BufferedImage image = null;
        try {
            image = ImageIO.read(fis); //reading the image file
        } catch (IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
        int chunkWidth = image.getWidth() / cols; // determines the chunk width and height
        int chunkHeight = image.getHeight() / rows;
        int count = 0;
        BufferedImage imgs[] = new BufferedImage[chunks]; //Image array to hold image chunks
        for (int x = 0; x < rows; x++) {
            for (int y = 0; y < cols; y++) {
                //Initialize the image array with image chunks
                imgs[count] = new BufferedImage(chunkWidth, chunkHeight, image.getType());

                // draws the image chunk
                Graphics2D gr = imgs[count++].createGraphics();
                gr.drawImage(image, 0, 0, chunkWidth, chunkHeight, chunkWidth * y, chunkHeight * x, chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight, null);
                gr.dispose();
            }
        }
        return imgs;
    }
}

唯一的缺陷是我没有检查图像是否大于屏幕可能会导致问题,这将通过使用 getScaledInstance(int x,int y, int width, in height) 在图像上并将其分成 block 。

更新

抱歉,我错过了形状中的问题,请查看 draw(Shape s) Graphics2D/Graphics 的方法。

我读过这个:

Any Shape object can be used as a clipping path that restricts the portion of the drawing area that will be rendered. The clipping path is part of the Graphics2D context; to set the clip attribute, you call Graphics2D.setClip and pass in the Shape that defines the clipping path you want to use.

有关将 u] 图像裁剪为形状的信息,请参见此处:Clipping the Drawing Region

引用资料:

关于java - 将图像拆分为可点击区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12418618/

相关文章:

JAVA通过 Swing 定时器使时间减少到零

java - JCombobox Listener如何在选择项目时启用它?

java - 在java中我们可以在没有真正的数据库连接的情况下执行SQL吗?

java - 使方法同步或在方法中添加同步块(synchronized block)之间有区别吗?

html - 找不到 Angular 4 img src

c++ - 沿非连续维度对图像进行装箱的最快方法

java - JTextPane 中的复制粘贴图标

java - 不偶尔发送证书

java - 确定用户两次单击的顺序

html - 防止人们打开原始图像