在JPanel上绘制部分透明的PNG [英] Drawing partially transparent PNG onto JPanel
问题描述
我将如何通过覆盖其void paint (Graphics g)
方法在JPanel上绘制部分透明的图像?我尝试了一种显而易见的方法,即加载图像,然后使用((Graphics2D)g).drawImage(...)
,但这没有用,并且互联网并不能告诉我太多信息.
How would i go about drawing a partially transparent image onto a JPanel by overriding its void paint (Graphics g)
method? I've tried the obvious way, which is to load the image and then use ((Graphics2D)g).drawImage(...)
but that didn't work, and the internet isn't telling me much.
推荐答案
JLabel
可以做到这一点,但是如果您要对面板/图像进行其他操作,可以使用paintComponent
和Graphics#drawImage
也是一个选择.
JLabel
is capable of doing this, but if you want to do something else with the panel/image, the using paintComponent
and Graphics#drawImage
is also an option.
以此为基础...
我能够渲染这个...
I was able to render this...
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.LinearGradientPaint;
import java.awt.Point;
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.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TransparentPNG {
public static void main(String[] args) {
new TransparentPNG();
}
public TransparentPNG() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage img;
public TestPane() {
try {
img = ImageIO.read(new File("Pony.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
@Override
public Dimension getPreferredSize() {
return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(), img.getHeight());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
LinearGradientPaint lgp = new LinearGradientPaint(
new Point(0, 0),
new Point(0, getHeight()),
new float[]{0f, 1f},
new Color[]{Color.GREEN, Color.YELLOW});
g2d.setPaint(lgp);
g2d.fillRect(0, 0, getWidth(), getHeight());
if (img != null) {
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight() - img.getHeight()) / 2;
g2d.drawImage(img, x, y, this);
}
g2d.dispose();
}
}
}
这篇关于在JPanel上绘制部分透明的PNG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!