【问题标题】:How to draw images on transparent window?如何在透明窗口上绘制图像?
【发布时间】:2014-03-13 08:00:04
【问题描述】:

我正在尝试在 JFrame 上使用 Graphics2D 绘制图像。
但是这段代码只显示空白背景。
怎么做?

Java 版本:SE-1.6
IDE:日食

我的代码如下所示:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferStrategy;
import java.awt.geom.Line2D;
import java.util.TimerTask;

import javax.swing.JFrame;

public class GraphicTest extends JFrame{

    public static void main(String[] args) {
        GraphicTest gt = new GraphicTest();
        gt.start();
    }

    JFrame frame;
    BufferStrategy strategy;

    GraphicTest(){
        int width = 320;
        int height = 240;

        this.frame = new JFrame("test");

        this.frame.setSize(width, height);
        this.frame.setLocationRelativeTo(null);
        this.frame.setLocation(576, 336);
        this.frame.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);

        this.frame.setUndecorated(true);
        this.frame.setBackground(new Color(0, 0, 0, 50));

        this.frame.setVisible(true);

        this.frame.setIgnoreRepaint(true);
        this.frame.createBufferStrategy(2);
        this.strategy = this.frame.getBufferStrategy();
    }

    public void onExit(){
        System.exit(0);
    }

    void start(){
        java.util.Timer timer = new java.util.Timer();
        timer.schedule(new RenderTask(), 0, 16);
    }

    class RenderTask extends TimerTask{
        int count = 0;

        @Override
        public void run() {
            GraphicTest.this.render();
        }
    }

    void render() {
        // Some moving images
        Graphics2D g2 = (Graphics2D)this.strategy.getDrawGraphics();
        g2.setStroke(new BasicStroke(5.0f));
        Line2D line = new Line2D.Double(20, 40, 120, 140);
        g2.draw(line);
        this.strategy.show();
    }
}

感谢您提供的任何帮助。

【问题讨论】:

标签: java swing graphics2d bufferstrategy


【解决方案1】:

另一种方式可以看到here。可以通过

frame.setBackground(new Color(0, 0, 0, 0));
....
setOpaque(false);  //for the JPanel being painted on.

【讨论】:

    【解决方案2】:
    • BufferStrategy 通常与没有任何透明度概念的重量级组件相关联。
    • Java 6 不“官方”支持透明和半透明(每个 Alpha 像素)
    • 使窗口变成半透明效果会影响其他任何东西...这很烦人,无论您使用的是 Java 6 还是 Java 7

    秘诀是一开始就让Window透明,然后叠加一个透明的组件,这个组件具有特殊的“半透明”绘制效果。

    在 Java 6(我认为是更新 10)下,有一个名为 AWTUtilities 的私​​有 API 可用,它提供了使窗口透明或半透明的能力,以下示例基于该 API。

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import java.lang.reflect.Method;
    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 TransparentWindowAnimation {
    
        public static void main(String[] args) {
            new TransparentWindowAnimation();
        }
    
        public TransparentWindowAnimation() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    }
    
                    if (supportsPerAlphaPixel()) {
                        try {
                            JFrame frame = new JFrame("Testing");
                            frame.setUndecorated(true);
                            setOpaque(frame, false);
                            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                            frame.setLayout(new BorderLayout());
                            frame.add(new PaintPane());
                            frame.pack();
                            frame.setLocationRelativeTo(null);
                            frame.setVisible(true);
                        } catch (Exception exp) {
                            exp.printStackTrace();
                        }
                    } else {
                        System.err.println("Per pixel alphering is not supported");
                    }
                }
            });
        }
    
        public static boolean supportsPerAlphaPixel() {
            boolean support = false;
            try {
                Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
                support = true;
            } catch (Exception exp) {
            }
            return support;
        }
    
        public static void setOpaque(Window window, boolean opaque) throws Exception {
            try {
                Class<?> awtUtilsClass = Class.forName("com.sun.awt.AWTUtilities");
                if (awtUtilsClass != null) {
                    Method method = awtUtilsClass.getMethod("setWindowOpaque", Window.class, boolean.class);
                    method.invoke(null, window, opaque);
                }
            } catch (Exception exp) {
                throw new Exception("Window opacity not supported");
            }
        }
    
        public class PaintPane extends JPanel {
    
            private BufferedImage img;
    
            private int xPos, yPos = 100;
            private int xDelta = 0;
            private int yDelta = 0;
    
            public PaintPane() {
                while (xDelta == 0) {
                    xDelta = (int)((Math.random() * 8)) - 4;
                }
                while (yDelta == 0) {
                    yDelta = (int)((Math.random() * 8)) - 4;
                }
                setOpaque(false);
                try {
                    img = ImageIO.read(new File("AngryBird.png"));
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
    
                Timer timer = new Timer(40, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        xPos += xDelta;
                        yPos += yDelta;
                        if (xPos - (img.getWidth() / 2) <= 0) {
                            xPos = img.getWidth() / 2;
                            xDelta *= -1;
                        }
                        if (xPos + (img.getWidth() / 2) >= getWidth()) {
                            xPos = getWidth() - (img.getWidth() / 2);
                            xDelta *= -1;
                        }
                        if (yPos - (img.getHeight() / 2) <= 0) {
                            yPos = img.getHeight() / 2;
                            yDelta *= -1;
                        }
                        if (yPos + (img.getHeight() / 2) >= getHeight()) {
                            yPos = getHeight() - (img.getHeight() / 2);
                            yDelta *= -1;
                        }
                        repaint();
                    }
                });
                timer.start();
            }
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setColor(new Color(128, 128, 128, 128));
                g2d.fillRect(0, 0, getWidth(), getHeight());
                int x = xPos - (img.getWidth() / 2);
                int y = yPos - (img.getHeight()/ 2);
                g2d.drawImage(img, x, y, this);
                g2d.dispose();
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 2021-04-10
      • 2020-08-17
      • 1970-01-01
      相关资源
      最近更新 更多