我可以在java中从左到右进行图像alpha淡化吗?

我正在制作一个游戏,并希望从左到右让单个图像“淡入淡出”,图像的左侧部分的alpha值为1.0,右侧的alpha值为0.0。 (注意:我不希望它随着时间的推移改变它的样子,如淡入或淡出,但只是从左到右渐渐变化并保持不变)。 尝试绘制我想要的最终结果如下所示:

lll lll ll ll lllll lll lll ll ll lllll lll lll ll ll lllll lll lll ll ll lllll lll lll ll ll lllll lll lll ll ll lllll 

‘l’的密度代表alpha

我目前正在使用TYPE_INT_RGB的缓冲图像,并希望尽可能保持相同。

是否有任何内置的java类可以帮助我做到这一点,或者至少有一种(相对容易的)方法来做我自己无法解决的问题?


编辑:我不希望有任何forms的不透明框架。 我想在另一个BufferedImage上绘制一个BufferedImage(带有alpha渐变)。

基本思想是在原始图像上应用AlphaComposite蒙版,该图像已填充LinearGradientPaint

所以,我们首先加载原始图像……

 BufferedImage original = ImageIO.read(new File("/an/image/somewhere")); 

然后我们创建一个相同大小的掩蔽图像……

 BufferedImage alphaMask = new BufferedImage(original.getWidth(), original.getHeight(), BufferedImage.TYPE_INT_ARGB); 

然后我们用LinearGradientPaint填充蒙版图像……

 Graphics2D g2d = alphaMask.createGraphics(); LinearGradientPaint lgp = new LinearGradientPaint( new Point(0, 0), new Point(alphaMask.getWidth(), 0), new float[]{0, 1}, new Color[]{new Color(0, 0, 0, 255), new Color(0, 0, 0 , 0)}); g2d.setPaint(lgp); g2d.fillRect(0, 0, alphaMask.getWidth(), alphaMask.getHeight()); g2d.dispose(); 

这里重要的是,我们实际上并不关心物理颜色,只关心它的alpha属性,因为这将决定两个图像如何被掩盖在一起……

然后,我们应用面具……

 BufferedImage faded = applyMask(original, alphaMask, AlphaComposite.DST_IN); 

实际上这称为实用方法……

 public static BufferedImage applyMask(BufferedImage sourceImage, BufferedImage maskImage, int method) { BufferedImage maskedImage = null; if (sourceImage != null) { int width = maskImage.getWidth(); int height = maskImage.getHeight(); maskedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D mg = maskedImage.createGraphics(); int x = (width - sourceImage.getWidth()) / 2; int y = (height - sourceImage.getHeight()) / 2; mg.drawImage(sourceImage, x, y, null); mg.setComposite(AlphaComposite.getInstance(method)); mg.drawImage(maskImage, 0, 0, null); mg.dispose(); } return maskedImage; } 

这基本上使用“目的地” AlphaComposite将蒙版应用到原始图像上,这导致……

(原件在左边,alpha在右边)

Α

为了certificate这一点,我将框架内容窗格的背景颜色更改为RED

在此处输入图像描述