我正在制作一个游戏,希望有一个图像“淡出”从左到右,图像的左边部分有一个alpha值为1.0,右边有一个alpha值为0.0。(注意:我不想让它随着时间的推移而改变它的样子,就像渐入佳境,而只是从左到右逐渐消失,并保持不变)。试图画出我想要的最终结果如下:
lll lll ll ll l l l l l
lll lll ll ll l l l l l
lll lll ll ll l l l l l
lll lll ll ll l l l l l
lll lll ll ll l l l l l
lll lll ll ll l l l l l
其中‘l’的密度代表阿尔法
我目前正在使用缓冲图像的TYPE_INT_RGB,并希望保持不变,如果可能的话。
是否有内置的java类可以帮助我做到这一点,或者至少有一种(相对容易的)方法可以自己解决这个问题?
编辑:我不想有任何不透明的框架。我想把一个BufferedImage (带有α梯度)画到另一个BufferedImage上。
发布于 2014-11-16 21:20:56
其基本思想是将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
将掩码应用到原始图像上,这将导致.
(左边是原件,右边是阿尔法)
为了证明这一点,我将框架内容窗格的背景色更改为RED
https://stackoverflow.com/questions/26961190
复制相似问题