简体   繁体   English

如何在JLabel中绘制椭圆形图像

[英]How draw oval image in JLabel

I want to draw a oval image in a JLabel , using Graphics . 我想使用GraphicsJLabel中绘制一个椭圆形图像。 This is my code, but a dont know about Graphics. 这是我的代码,但不知道图形。

class imagePanel extends JLabel {
    //private PlanarImage image;

    private BufferedImage buffImage = null;

    private void drawFingerImage(int nWidth, int nHeight, byte[] buff) {
        buffImage = new BufferedImage(nWidth, nHeight, BufferedImage.TYPE_BYTE_GRAY);
        buffImage.getRaster().setDataElements(0, 0, nWidth, nHeight, buff);
        Graphics g = buffImage.createGraphics();
        g.drawImage(buffImage, 0, 0, 140, 150, null);
        g.dispose();
        repaint();
    }

    public void paintComponent(Graphics g) {
        g.drawImage(buffImage, 0, 0, this);
    }
}

I have this 我有这个

you need the help of setClip() method as mentioned here and here . 你需要这里这里提到的setClip()方法的帮助。

when it comes to code it should look like this 当谈到代码时它应该是这样的

public class OvalImageLabel extends JLabel {

    private Image image;

    public OvalImageLabel(URL imageUrl) throws IOException {
        image = ImageIO.read(imageUrl);
    }

    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        g.setClip(new java.awt.geom.Ellipse2D.Float(0f,0f, getWidth(),getHeight()/2));
        g.drawImage(image, 0, 0, this);

    }
}

and a running application that using this class 以及使用此类的正在运行的应用程序

public class UsageExample extends JPanel {

    public UsageExample() {
        super(new BorderLayout());
        OvalImageLabel l;
        try {
            l = new OvalImageLabel(new File("/path/to/image.png").toURI().toURL());
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        add(l, BorderLayout.CENTER);
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setContentPane(new UsageExample());
        frame.setSize(200, 200);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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