Java - 从图像边框创建一个形状

时间:2012-05-31 12:58:20

标签: java image border awt shape

我有一个从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,并且按钮的渲染只需要很短的时间。在这个领域有经验的人可以教我如何生成一个BufferedImage边界的形状?我使用上面的类从PNG图像创建具有透明背景的形状。

1 个答案:

答案 0 :(得分:5)

有关提示,请查看Smoothing a jagged路径。在最终版本中获得(粗略)轮廓的算法相对较快。创建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);
}