我有一个从 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 图像创建形状。
最佳答案
有关提示,请查看 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);
}
关于Java - 从图像周围的边框创建一个形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10834109/