【问题标题】:Java - Create a shape from border around imageJava - 从图像周围的边框创建形状
【发布时间】:2012-06-05 17:46:04
【问题描述】:

我有一个从 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 图像创建形状。

【问题讨论】:

  • 不好意思,能不能帮我看看,获取大纲用的是哪些部分?我对形状等不是很熟悉:/请指导我。
  • 啊,好的,谢谢!无论如何,与我上面使用的类相比,这种方法真的非常快.. 结果不到一秒就出来了!与上述方法不同,它需要大约 +-13 秒来处理。再次感谢!
  • 很高兴你把它整理好了。 :) 我输入了 cmets 作为答案,有机会请accept 它。

标签: java image border awt shape


【解决方案1】:

有关提示,请查看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);
}

【讨论】:

  • 不客气。很高兴我使用该代码帮助了某人。 :)
  • @AndrewThompson 我知道这是一种死灵,但是当我运行你的代码时,我得到一个初始的moveTo 丢失的错误......我试图实现这样的if(first) { gp.moveTo(xx,yy); first = false; } else { gp.lineTo(xx,yy); } 到代码,但它没有帮助......提前致谢。
  • @AndrewThompson 如果有帮助,我正在使用 jdk 6 arm-7 开发 linux。
  • “我试图实现这样的东西..” 代码已经使用cont 属性正确实现了它。如果你不能让它工作,我建议你 1) 开始一个新问题。 2) 发布您的尝试MCVE
猜你喜欢
  • 1970-01-01
  • 2020-03-03
  • 1970-01-01
  • 1970-01-01
  • 2011-06-08
  • 1970-01-01
  • 2023-03-18
  • 2011-08-22
  • 2015-08-31
相关资源
最近更新 更多