如何在Java中制作圆形图像标签?

时间:2015-07-15 06:38:19

标签: java swing jlabel

如何用Java制作圆形图像标签?

我想制作圆圈图片标签但是我不能这样做..嘿伙计们帮助我... T.T

我尝试制作圆形面板以添加图像图标,但这不起作用。

请帮助我......

2 个答案:

答案 0 :(得分:8)

我认为你应该改变你的方向,而不是试图修改组件的输出,而是修改输入......

enter image description here

所有这一切,都是将圆形(基于alpha的)蒙版应用于另一个图像

    BufferedImage master = ImageIO.read(new File("/Volumes/Disk02/Dropbox/MegaTokyo/thumnails/megatokyo_omnibus_1_3_cover_by_fredrin-d4oupef.jpg"));

    int diameter = Math.min(master.getWidth(), master.getHeight());
    BufferedImage mask = new BufferedImage(master.getWidth(), master.getHeight(), BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2d = mask.createGraphics();
    applyQualityRenderingHints(g2d);
    g2d.fillOval(0, 0, diameter - 1, diameter - 1);
    g2d.dispose();

    BufferedImage masked = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);
    g2d = masked.createGraphics();
    applyQualityRenderingHints(g2d);
    int x = (diameter - master.getWidth()) / 2;
    int y = (diameter - master.getHeight()) / 2;
    g2d.drawImage(master, x, y, null);
    g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.DST_IN));
    g2d.drawImage(mask, 0, 0, null);
    g2d.dispose();

    JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(masked)));

这样做的好处是你可以得到软剪辑(setClip没有提供)以及不弄乱组件的现有剪裁形状

applyQualityRenderingHints ...

public static void applyQualityRenderingHints(Graphics2D g2d) {

    g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
    g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

}

答案 1 :(得分:-1)

您可以使用Area类创建剪辑区域:

BufferedImage image = ImageIO.read(new File("..."));
Area clip = new Area( new Rectangle(0, 0, image.getWidth(), image.getHeight()) );
Area oval = new Area( new Ellipse2D.Double(0, 0, image.getWidth() - 1, image.getHeight() - 1) );
clip.subtract( oval );
Graphics g2d = image.createGraphics();
g2d.setClip( clip );
g2d.setColor( Color.BLACK );
g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(image)));