簡體   English   中英

我可以在Java中從左向右淡入圖像alpha嗎?

[英]Can I have image alpha fade from left to right in java?

我正在做一個游戲,想要從左到右具有單個圖像“淡入淡出”,圖像的左半部分的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(具有alpha漸變)。

基本思想是在已用LinearGradientPaint填充的原始圖像上應用AlphaComposite蒙版

因此,我們首先加載原始圖像...

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

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM