使用 Graphics2D 填充透明度

发布于 2024-10-09 23:04:24 字数 519 浏览 9 评论 0原文

我创建了一个 ARGB BufferedImage。现在我想用透明背景重新初始化它。我尝试了以下代码:

(...) 
if( this.offscreen==null  ||
    this.offscreen.getWidth()!= dim.width ||
    this.offscreen.getHeight()!= dim.height )
    {
    this.offscreen=new BufferedImage(
       dim.width,
       dim.height,
      BufferedImage.TYPE_INT_ARGB);
     }
Graphics2D g=this.offscreen.createGraphics();
g.setColor(new Color(255,255,255,0));
g.clearRect(0, 0, dim.width, dim.height);
(...)

但它不起作用。

请问您知道如何执行此操作吗?

谢谢 !

I created an ARGB BufferedImage. Now I'd like to reinitialize it with a transparent background. I tried the following code:

(...) 
if( this.offscreen==null  ||
    this.offscreen.getWidth()!= dim.width ||
    this.offscreen.getHeight()!= dim.height )
    {
    this.offscreen=new BufferedImage(
       dim.width,
       dim.height,
      BufferedImage.TYPE_INT_ARGB);
     }
Graphics2D g=this.offscreen.createGraphics();
g.setColor(new Color(255,255,255,0));
g.clearRect(0, 0, dim.width, dim.height);
(...)

but it didn't work.

Any idea on how to do this please ?

Thanks !

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北斗星光 2024-10-16 23:04:25

g.clearRect(..) 使用 Graphics2D 对象的背景颜色填充选定的矩形。您最好执行 g.fillRect(..) 这将为您的代码提供预期结果,或者预先设置 Graphics2D 对象的背景颜色 (g.setBackground(..))。

另外,您可能必须在填充之前执行 g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC)); ,以便正确设置缓冲区(忽略目标缓冲区数据,仅使用源数据 -在本例中为填充操作)。不确定该值的默认值是什么,但您应该稍后将其设置回该值以确保正常运行。

g.clearRect(..) fills the selected rectangle with the background colour of the Graphics2D object. You're better off doing g.fillRect(..) which would give the intended result with your code, or set the background colour of the Graphics2D object beforehand (g.setBackground(..)).

Also, you may have to do g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC)); before the fill so that it sets the buffer properly (ignore destination buffer data, only use source data -- in this case, the fill operation). Not sure what the default is for this value, but you should set it back to that afterwards to ensure proper operation.

蒲公英的约定 2024-10-16 23:04:25

我以前遇到过这个问题,我用一个非常狭窄的技巧解决了它。
事情是这样的:

在 Paint 类的构造函数中拍摄系统的屏幕截图,但要小心

BufferedImage image = new Robot().createScreenCapture(new Rectangle(0, 23, xScreen, yScreen));

以及要清除屏幕的位置

g2D.drawImage(image, null, /*your Image observer*/);                    

I had this problem before and I solved it with a really narrow trick.
Here is the deal:

In the constructor of the paint Class take a screen shot of the System but be careful

BufferedImage image = new Robot().createScreenCapture(new Rectangle(0, 23, xScreen, yScreen));

And where you want to clear the screen

g2D.drawImage(image, null, /*your Image observer*/);                    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文