Java - 图形透明度与图形g

时间:2015-09-08 02:46:59

标签: java transparency

我想为我的视频游戏中的一个角色创建一个淡入和淡出效果。要做到这一点,我希望他们的图像淡出并淡入。我想改变图像的不透明度,但不知道如何。我正在使用java Graphics。这是一些代码。

g.drawImage(joople, jx, jy, sx, sy, this);

我在这个方法中运行此代码:

public void paint(Graphics g) {

非常感谢, 橡木

2 个答案:

答案 0 :(得分:2)

您需要查看Compositing Graphics

enter image description here

import java.awt.AlphaComposite;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class FadeMe {

    public static void main(String[] args) {
        new FadeMe();
    }

    public FadeMe() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private BufferedImage img;
        private float alpha = 0;
        private float delta = 0.01f;

        public TestPane() {
            try {
                img = ImageIO.read(...);
                Timer timer = new Timer(40, new ActionListener(){ 
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        alpha += delta;
                        if (alpha > 1.0) {
                            alpha = 1.0f;
                            delta *= -1.0f;
                        } else if (alpha < 0.0) {
                            alpha = 0.0f;
                            delta *= -1.0f;
                        }
                        repaint();
                    }
                });
                timer.start();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return img != null ? new Dimension(img.getWidth(), img.getHeight()) : new Dimension(200, 200);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setComposite(AlphaComposite.SrcOver.derive(alpha));
            int x = (getWidth() - img.getWidth()) / 2;
            int y = (getHeight() - img.getHeight()) / 2;
            g2d.drawImage(img, x, y, this);
            g2d.dispose();
        }

    }

}

答案 1 :(得分:0)

对于大多数使用Java代码进行图像淡入淡出的开发人员来说,这是一个简单快捷的方法。

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 *
 * @author ADMIN
 */
public class ImageFade extends JFrame {

    ImageFade() {
        setLayout(null);

        JLabel l = new JLabel();
        l.setBounds(0, 0, 100, 96);
        add(l);

        Thread tp = new Thread() {
            @Override
            public void run() {
                for (int amp = 0; amp <= 500; amp++) {
                    try {
                        sleep(1);
                        try {
                            BufferedImage bim = ImageIO.read(new File("src/image/fade/image.png"));
                            BufferedImage nbim = new BufferedImage(bim.getWidth(), bim.getHeight(), BufferedImage.TYPE_INT_ARGB);
                            Graphics2D createGraphics = nbim.createGraphics();
                            createGraphics.drawImage(bim, null, 0, 0);
                            RescaleOp r = new RescaleOp(new float[]{1f, 1f, 1f, (float) amp / 500}, new float[]{0, 0, 0, 0}, null);
                            BufferedImage filter = r.filter(nbim, null);
                            l.setIcon(new ImageIcon(filter));
                        } catch (Exception ex) {
                            System.err.println(ex);
                        }
                    } catch (InterruptedException ex) {
                    }
                }
            }
        };
        tp.start();

        setUndecorated(true);
        setBackground(new Color(0, 0, 0, 0));
        setSize(100, 96);
        setVisible(true);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        setAlwaysOnTop(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        ImageFade fr = new ImageFade();
    }
}

在此代码中,您可以看到线程代码。在线程中此图像将淡入。

使用的图像是堆栈溢出网页的徽标图像。

只有通过显示的代码,图像才会淡入。

Thread tp = new Thread() {
    @Override
    public void run() {
        for (int amp = 0; amp <= 500; amp++) {
            try {
                sleep(1);
                try {
                    BufferedImage bim = ImageIO.read(new File("src/image/fade/image.png"));
                    BufferedImage nbim = new BufferedImage(bim.getWidth(), bim.getHeight(), BufferedImage.TYPE_INT_ARGB);
                    Graphics2D createGraphics = nbim.createGraphics();
                    createGraphics.drawImage(bim, null, 0, 0);
                    RescaleOp r = new RescaleOp(new float[]{1f, 1f, 1f, (float) amp / 500}, new float[]{0, 0, 0, 0}, null);
                    BufferedImage filter = r.filter(nbim, null);
                    l.setIcon(new ImageIcon(filter));
                } catch (Exception ex) {
                      System.err.println(ex);
                  }
            } catch (InterruptedException ex) {
            }
        }
    }
};
tp.start();

此代码非常易于使用。

这不是来自任何书本,互联网等,而是我开发的。

正常图像无法更改Alpha。通过代码BufferedImage nbim = new BufferedImage(bim.getWidth(), bim.getHeight(), BufferedImage.TYPE_INT_ARGB);,图像将转换为ARGB-Alpha,Red,Green,Blue(R,G,B,A)图像。

因此您可以更改图像的Alpha。

通过此代码,您的图像将比回答1的代码用户更流畅地显示图像。