Java - 从图像周围的边框创建形状



我有一个从 PNG 图像绘制形状的类,以便我可以使用该形状绘制项目所需的自定义按钮的边框。 下面是类绘制图像形状的代码:

public class CreateShapeClass {
    public static Area createArea(BufferedImage image, int maxTransparency) {
        Area area = new Area();
        Rectangle rectangle = new Rectangle();
        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                int rgb = image.getRGB(x, y);
                rgb = rgb >>> 24;
                if (rgb >= maxTransparency) {
                    rectangle.setBounds(x, y, 1, 1);
                    area.add(new Area(rectangle));
                }
            }
        }
        return area;
    }
}

但是,这需要很长时间来处理,我认为通过在主应用程序中预先绘制形状,然后将它们存储到数组中并传递给其他类,它将减少渲染时间。 但是,paintBorder() 方法绘制按钮边框所花费的时间也需要相当长的时间(尽管比绘制形状所需的时间短), 因为上面类生成的形状是填充的,而不是空的。我尝试使用 java2d 绘制形状,例如 Ellipse2D,按钮的渲染只需要很短的时间。任何在这个领域有经验的人都可以教我如何生成一个作为缓冲图像边框的形状?我使用上面的类从具有透明背景的 PNG 图像创建形状。

有关提示,请参阅平滑锯齿状路径。在最终版本中,获得(粗略)轮廓的算法相对较快。 创建GeneralPath比追加Area对象要快得多。

重要的部分是这种方法:

public Area getOutline(Color target, BufferedImage bi) {
    // construct the GeneralPath
    GeneralPath gp = new GeneralPath();
    boolean cont = false;
    int targetRGB = target.getRGB();
    for (int xx=0; xx<bi.getWidth(); xx++) {
        for (int yy=0; yy<bi.getHeight(); yy++) {
            if (bi.getRGB(xx,yy)==targetRGB) {
                if (cont) {
                    gp.lineTo(xx,yy);
                    gp.lineTo(xx,yy+1);
                    gp.lineTo(xx+1,yy+1);
                    gp.lineTo(xx+1,yy);
                    gp.lineTo(xx,yy);
                } else {
                    gp.moveTo(xx,yy);
                }
                cont = true;
            } else {
                cont = false;
            }
        }
        cont = false;
    }
    gp.closePath();
    // construct the Area from the GP & return it
    return new Area(gp);
}

最新更新