简体   繁体   English

如何将动态创建的BufferedImage实例的背景设置为透明?

[英]How do I set the background of a dynamically created BufferedImage instance to transparent?

I am trying to create a BufferedImage instance which contains a rounded rectangle of a certain colour and is transparent everywhere else. 我正在尝试创建一个BufferedImage实例,其中包含一个特定颜色的圆角矩形,并且在其他任何地方都是透明的。

I am using the following code to create the image 我使用以下代码来创建图像

 private BufferedImage createChromImage() {
    BufferedImage I = new BufferedImage(350, 20, ColorSpace.TYPE_RGB);
    Graphics2D g2 = I.createGraphics();

    g2.setPaint(new GradientPaint(0, 0, Color.DARK_GRAY, 100,
              100, Color.BLUE, false));

    g2.fillRoundRect(0, 0, 350, 20, 10, 10);

    return I;
 }

I end up with a rounded rectangle on a black background, is there a way in which I can get it on a transparent background. 我最终在黑色背景上有一个圆角矩形,有一种方法可以让我在透明背景上得到它。 I suspect it will require a different ColorSpace setting, but I not sure which.. any help is much appreciated. 我怀疑它需要一个不同的ColorSpace设置,但我不知道哪个..任何帮助都非常感激。

You can't have a transparent background in an image that does not support transparency. 您不能在不支持透明度的图像中使用透明背景。 RGB is a 24-bit image with no transparency. RGB是24位图像,没有透明度。 Instead, you want to use BufferedImage.TYPE_INT_ARGB as the argument to BufferedImage's constructor: that will give you an alpha channel to play with, which will allow transparency. 相反,您希望使用BufferedImage.TYPE_INT_ARGB作为BufferedImage构造函数的参数:这将为您提供一个可以使用的Alpha通道,这将允许透明度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM