gpt4 book ai didi

java - 缩放和绘制 BufferedImage

转载 作者:行者123 更新时间:2023-12-02 02:03:54 29 4
gpt4 key购买 nike

我有一个自定义的JPanel,在paintComponent方法上有一个@Override,它从一个BufferedImage获取成员变量并绘制它。在我尝试缩放图像之前它工作得很好。我从阅读中了解到有两种不同的方法。一种是使用 Image.getScaledInstance,另一种是使用缩放图像的尺寸创建一个 Graphics2D。然而,当我尝试使用这些方法中的任何一种时,我要么得到一个完全白色的矩形,要么什么也得不到。我不确定我做错了什么。重写方法的代码如下。任何意见,将不胜感激。我确信这是微不足道的,但我看不到问题所在。

protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
int imageWidth = img.getWidth();
int imageHeight = img.getHeight();
int panelWidth = getWidth();
int panelHeight = getHeight();

if(imageWidth > panelWidth || imageHeight > panelHeight){
double aspectRatio = (double)imageWidth / (double)imageHeight;
int newWidth, newHeight;

// rescale the height then change the width to pre
if(imageWidth > panelWidth){
double widthScaleFactor = (double)panelWidth / (double)imageWidth;
newWidth = (int)(widthScaleFactor * imageWidth);
newHeight = (int)(widthScaleFactor * imageWidth / aspectRatio);
}else{
double heightScaleFactor = (double)panelHeight / (double)imageHeight;
newHeight = (int)(heightScaleFactor * imageHeight);
newWidth = (int)(heightScaleFactor * imageHeight * aspectRatio);
}

//BufferedImage scaledImage = (BufferedImage)img.getScaledInstance(newWidth, newHeight, BufferedImage.SCALE_DEFAULT);
BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, img.getType());
int x = (panelWidth - newWidth) / 2;
int y = (panelHeight - newHeight) / 2;

//Graphics2D g2d = (Graphics2D) g.create();
Graphics2D g2d = scaledImage.createGraphics();
//g2d.drawImage(scaledImage, x, y, this);
g2d.drawImage(img, 0, 0, newWidth, newHeight, null);
g2d.dispose();
}else{
int x = (getWidth() - img.getWidth()) / 2;
int y = (getHeight() - img.getHeight()) / 2;

Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(img, x, y, this);
g2d.dispose();
}
}

最佳答案

不确定这是否有帮助,因为您还没有发布 SSCCE ,但这可能比您的代码工作得更好。

Image scaledImage = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
int x = (panelWidth - newWidth) / 2;
int y = (panelHeight - newHeight) / 2;
g.drawImage(scaledImage, x, y, this);

关于java - 缩放和绘制 BufferedImage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51133242/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com