如何在运行JavaSwing项目时修复模糊图像
我目前正在学习java swing builder作为一项新的技术技能。我需要研究如何在画布上导入图像。是的,它成功导入,图像清晰且不模糊。 但是,当我运行项目时,导入到项目中的图像会变得模糊。我不知道为什么会这样。我研究了一些功能,比如缩放,但什么都没发生,输出结果都一样,变得模糊 图像尺寸:250x250 以下是我在项目中实现的代码:如何在运行JavaSwing项目时修复模糊图像,java,swing,Java,Swing,我目前正在学习java swing builder作为一项新的技术技能。我需要研究如何在画布上导入图像。是的,它成功导入,图像清晰且不模糊。 但是,当我运行项目时,导入到项目中的图像会变得模糊。我不知道为什么会这样。我研究了一些功能,比如缩放,但什么都没发生,输出结果都一样,变得模糊 图像尺寸:250x250 以下是我在项目中实现的代码: private Image doctor_ppe = new ImageIcon(LoginScreen.class.getResource("/a
private Image doctor_ppe = new ImageIcon(LoginScreen.class.getResource("/assets/large.png")).getImage().getScaledInstance(250, 250, Image.SCALE_SMOOTH);
JLabel lblDds = new JLabel("");
lblDds.setVerticalAlignment(SwingConstants.BOTTOM);
lblDds.setHorizontalAlignment(SwingConstants.CENTER);
lblDds.setIcon(new ImageIcon(doctor_ppe));
lblDds.setBounds(59, 305, 236, 251);
panel.add(lblDds);
不可运行项目和可运行项目的区别:
图像不模糊:
运行项目后图像模糊:
希望有人经历过,希望能对我的问题有所帮助
多谢各位
但是,当我运行项目时,导入到项目中的图像会变得模糊
可能是因为您的桌面使用的缩放因子大于1.0,所以在绘制图像时,图像会放大
如果要更改整个应用程序的缩放比例,可以尝试:
-Dsun.java2d.uiScale=1.0
,或System.setProperty(“sun.java2d.uiScale”,“1.0”)
图标
缩放:
import java.awt.*;
import java.awt.geom.AffineTransform;
import javax.swing.*;
public class NoScalingIcon implements Icon
{
private Icon icon;
public NoScalingIcon(Icon icon)
{
this.icon = icon;
}
public int getIconWidth()
{
return icon.getIconWidth();
}
public int getIconHeight()
{
return icon.getIconHeight();
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
Graphics2D g2d = (Graphics2D)g.create();
AffineTransform at = g2d.getTransform();
int scaleX = (int)(x * at.getScaleX());
int scaleY = (int)(y * at.getScaleY());
int offsetX = (int)(icon.getIconWidth() * (at.getScaleX() - 1) / 2);
int offsetY = (int)(icon.getIconHeight() * (at.getScaleY() - 1) / 2);
int locationX = scaleX + offsetX;
int locationY = scaleY + offsetY;
// Reset scaling to 1.0 by concatenating an inverse scale transfom
AffineTransform scaled = AffineTransform.getScaleInstance(1.0 / at.getScaleX(), 1.0 / at.getScaleY());
at.concatenate( scaled );
g2d.setTransform( at );
icon.paintIcon(c, g2d, locationX, locationY);
g2d.dispose();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI()
{
JButton button = new JButton( "Button" );
NoScalingIcon icon = new NoScalingIcon( new ImageIcon("box.jpg") );
button.setIcon( icon );
JPanel panel = new JPanel( );
panel.add( button );
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(panel);
f.setSize(200, 200);
f.setLocationRelativeTo( null );
f.setVisible(true);
}
}
这个属性:System.setProperty(“sun.java2d.uiScale”,“1.0”)解决了我的问题,但是表单变小了。?正确。如果缩放到1.0,则整个窗体将变小。如果使用NoCallingIcon,则只有图标会更小。