java中图像的平滑缩放
我创建了一个扩展Jbutton的按钮,并将其添加到按钮图像中,但这并不能使图像平滑。 我尝试java中图像的平滑缩放,java,swing,Java,Swing,我创建了一个扩展Jbutton的按钮,并将其添加到按钮图像中,但这并不能使图像平滑。 我尝试getScaledInstance,但它不起作用 这是原始图像: 这就是它真正呈现画面的方式: 编辑: 我理解为什么它不能使图像平滑。 我必须将drawImage更改为g.drawImage(image,0,0,null) 我运行代码,有时它向我显示图片,有时它向我显示空方块,这向我显示控制台中的错误 只有我用鼠标移动它们,图片才会出现 尝试以下方法。这是不言自明的 public class Circ
getScaledInstance
,但它不起作用
这是原始图像:
这就是它真正呈现画面的方式:
编辑:
我理解为什么它不能使图像平滑。
我必须将drawImage
更改为g.drawImage(image,0,0,null)代码>
我运行代码,有时它向我显示图片,有时它向我显示空方块,这向我显示控制台中的错误
只有我用鼠标移动它们,图片才会出现
尝试以下方法。这是不言自明的
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);
}
}
我不明白为什么要这么复杂。
我建议只需创建一个ImageIcon
并设置JButton
图标。
示例代码:
javax.swing.ImageIcon imgIco=newjavax.swing.ImageIcon(“图标文件的路径”);
javax.swing.JButton button2=新的javax.swing.JButton(imgIco);
button2.setPreferredSize(新的java.awt.Dimension(imgIco.getIconWidth(),imgIco.getIconHeight());
上述代码的最后一行确保按钮大小与图标大小相同,因为您暗示这是您在对另一个答案的评论中想要的。这不是问题的原因,但是,g.drawImage
的最后一个参数应该是this
。如果不需要图像观察者,它可以是null
。再看一次@Ok。我编辑了我的答案。我想这样就行了。不起作用,在JLable上它确实起作用,但在Jbutton上你可以写你写的所有代码,也许我遗漏了一些我提供的测试程序。您将需要修改图像的路径。图像看起来不错,但它没有覆盖整个按钮。您的示例已将其修复为看起来不错,但我无法缩小图像。看看我的编辑我已经建议在以前的编辑中使用ImageIcon。
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);
}
}