我创建了一个扩展 Jbutton 的按钮,我添加到按钮图像中,但这不会使图像呈现平滑。
我尝试 getScaledInstance
但它不起作用
这是原始图像:
这就是它真正呈现的图片:
public class Button extends JButton {
private Image image;
public Button(Image image) {
this.image = image;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}
编辑:
我明白为什么它不能使图像变得平滑。
我必须将 drawImage
更改为 g.drawImage(image, 0, 0, null);
我运行代码,有时它会向我显示图片,有时会向我显示空方 block ,这会在控制台中向我显示错误。
只有我用鼠标移动它们,图片才会出现
最佳答案
尝试以下操作。这是非常不言自明的。
public class CircleDisplay extends JPanel {
final static int height = 500;
final static int width = 500;
Image img = null;
JFrame frame = new JFrame();
public static void main(String[] args) {
new CircleDisplay();
}
public CircleDisplay() {
Image img = null;
try {
img = ImageIO
.read(new File("f:yellowCircle.png"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
frame.add(this);
img =
img.getScaledInstance(50, 50,
Image.SCALE_SMOOTH);
Button b = new Button(img);
b.setPreferredSize(new Dimension(50,50));
add(b);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class Button extends JButton {
Image img;
public Button(Image img) {
this.img = img;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img,0,0,null);
}
}
关于java - java中图像的平滑缩放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59935952/