3

我即将开始一个项目,该项目将生成一些带有 alpha(渐变)的 PNG,并希望在 java 中以编程方式绘制它们。

对于(一个简单的)示例,我想绘制一个框,添加一个阴影,然后将其保存到一个 PNG 文件中,然后可以覆盖在其他一些图形上。

  1. 使用标准 JRE 系统库可以做到这一点吗?
  2. 哪些库会使这种操作变得简单?

谢谢。

4

1 回答 1

4

Is this possible with the standard JRE system libraries?

Yes, it is possible and is pretty simple aswell. The code below produces this image (transparent png):

screenshot

public static void main(String[] args) throws IOException {

    int x = 50, y = 50, w = 300, h = 200;

    // draw the "shadow"
    BufferedImage img = new BufferedImage(400, 300, BufferedImage.TYPE_INT_ARGB);
    Graphics g = img.getGraphics();
    g.setColor(Color.BLACK);
    g.fillRect(x + 10, y + 10, w, h);

    // blur the shadow
    BufferedImageOp op = getBlurredOp();
    img = op.filter(img, null);

    // draw the box
    g = img.getGraphics();
    g.setColor(Color.RED);
    g.fillRect(x, y, w, h);

    // write it to disk
    ImageIO.write(img, "png", new File("test.png"));
}

private static BufferedImageOp getBlurredOp() {

    float[] matrix = new float[400];
    for (int i = 0; i < 400; i++)
        matrix[i] = 1.0f/400.0f;

    return new ConvolveOp(new Kernel(20, 20, matrix),
                          ConvolveOp.EDGE_NO_OP, null);
}

Which libraries would make this kind of operation simple?

I would say that it depends on your other use cases. For simple shapes like boxes and ovals I would go for the solution above, no library is needed.

于 2012-04-08T09:05:29.867 回答