java图像透明度(图像丢失)

时间:2017-11-30 09:12:24

标签: java swing graphics

我认为绘画方法有问题,但我无法弄明白。

public void paint(Graphics g) {
        screenImage = createImage(1280, 720);
        screenGraphic = screenImage.getGraphics();
        screenDraw(screenGraphic);
        g.drawImage(screenImage, 0, 0, null);
    }

    public void screenDraw(Graphics g) {
        g.drawImage(BG, 0, 0, null);
        if(isMainScreen) {
            g.drawImage(changedImageAlpha(selectedImage, 120), 130, 360, null);
        }
        paintComponents(g);
        this.repaint();
    }

    public Image changedImageAlpha(Image image, int trans) {
        BufferedImage img = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics(); 
        Composite c = AlphaComposite.getInstance( AlphaComposite.SRC_ATOP, .5f); 
        g.setComposite(c); 
        g.drawImage(image, 0, 0, null);
        g.dispose();

        int colorMask = 0x00FFFFFF;
        int alphaShift = 24;
        for(int y=0; y<img.getHeight(); y++){
            for(int x=0; x<img.getWidth(); x++) {
                img.setRGB(x, y, (img.getRGB(x, y) & colorMask) | (trans << alphaShift));
            }
        }
        return img;
    }

BG是一个Image对象,也是一个screenImage。 我希望图像是一个透明的图像,是的。 我看到一些透明的图像,但没有任何内容。它只是一个清晰的透明图像,没有颜色,没有。 可能是什么问题?

1 个答案:

答案 0 :(得分:1)

作为对the answer对前一个问题的评论,我提到答案中提到的比操作更容易。

但我的意思是而不是而不是

所以这个:

public Image changedImageAlpha(Image image, int trans) {
    BufferedImage img = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = img.createGraphics(); 
    Composite c = AlphaComposite.getInstance( AlphaComposite.SRC_ATOP, .5f); 
    g.setComposite(c); 
    g.drawImage(image, 0, 0, null);
    g.dispose();

    int colorMask = 0x00FFFFFF;
    int alphaShift = 24;
    for(int y=0; y<img.getHeight(); y++){
        for(int x=0; x<img.getWidth(); x++) {
            img.setRGB(x, y, (img.getRGB(x, y) & colorMask) | (trans << alphaShift));
        }
    }
    return img;
}

应该是这样的:

public Image changedImageAlpha(Image image, int trans) {
    BufferedImage img = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = img.createGraphics(); 
    Composite c = AlphaComposite.getInstance( AlphaComposite.SRC_ATOP, .5f); 
    g.setComposite(c); 
    g.drawImage(image, 0, 0, null);
    g.dispose();

    return img;
}

作为提示:尝试理解其他人提供的代码。 &#39; Cut&amp;粘贴&#39;编程通常以失败告终。

相关问题