是否可以使用 Path2D.Double() 创建一个 ImageIcon?

Is it possible to create an ImageIcon with Path2D.Double()?

带有按钮的新 Toolbar 应初始化具有 Shape 的对象 (Path2D path=new Path2D.Double()).

这些 Object 中的 Shape 应该作为 ImageIcon 添加到按钮中。 我可以避免使用 gimp 之类的东西自己制作图标吗?

应该怎么走?任何帮助将不胜感激。

这里有两种将形状转换为图标的可能性。您可以创建 BufferedImage 对象并将 Shape 绘制到此图像中,或者您可以围绕 Shape.

创建接口 Icon 的实现

这是例子

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.awt.image.BufferedImage;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JToolBar;
import javax.swing.WindowConstants;

public class IconTest {

    public static void main(String[] args) {
        Path2D path = new Path2D.Double();
        path.moveTo(0, 0);
        path.lineTo(15, 0);
        path.lineTo(8, 15);
        path.lineTo(0, 0);
        JToolBar toolbar = new JToolBar();
        // use Icon wrapper around the shape
        JButton btn = new JButton(new ShapeIcon(path, Color.CYAN));
        btn.setFocusable(false);
        toolbar.add(btn);
        // use conversion of shape into the icon
        btn = new JButton(toIcon(path, Color.GREEN));
        btn.setFocusable(false);
        toolbar.add(btn);
        JFrame frm = new JFrame("Test");
        frm.add(toolbar, BorderLayout.NORTH);
        frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frm.setSize(400, 300);
        frm.setLocationRelativeTo(null);
        frm.setVisible(true);
    }

    private static Icon toIcon(Shape shape, Color color) {
        BufferedImage img = new BufferedImage(shape.getBounds().width, shape.getBounds().height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = img.createGraphics();
        g2.setColor(color);
        g2.fill(shape);
        // g2.draw(shape);
        g2.dispose();
        return new ImageIcon(img);
    }

    private static class ShapeIcon implements Icon {

        private final Shape shape;

        private final Color color;

        /**
         * @param shape
         */
        public ShapeIcon(Shape shape, Color color) {
            this.shape = shape;
            this.color = color;
        }

        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
            Graphics2D g2 = (Graphics2D) g;
            g2.setColor(color);
            AffineTransform transform = new AffineTransform();
            transform.translate(x, y);
            g2.fill(transform.createTransformedShape(shape));
            // g2.draw(transform.createTransformedShape(shape));
        }

        @Override
        public int getIconWidth() {
            return shape.getBounds().width;
        }

        @Override
        public int getIconHeight() {
            return shape.getBounds().height;
        }

    }
}