如何在 JPanel 中保持纵横比

How to keep aspect ratio in JPanel

我有点难以在 JPanel.

上保持宽高比

我默认从带有边框布局的 Netbeans 生成 JFrame。整个框架充满了我的 JPanel(来自我的自定义 class GraphicsPanel.java 扩展 JPanel)。

GraphicsPanel class 只有一种使用一些基本构造函数来绘制图形的方法。我的 JPanel 上有一个矩形和一个多边形。 我想要实现的是,当我调整框架大小时,我想保持 JPanel 的纵横比 4:3(或类似的东西)。当框架对于宽高比来说太大时,它会用一些默认颜色填充框架背景。

我已经阅读了一些关于宽高比的主题(例如 this)。但是运气不好,我仍然不知道该怎么做。

这是我的 JPanel class 的代码。我是初学者,正在尝试学习如何使用 Java 图形(绘制、填充、调整大小等),所以请放轻松。

import java.awt.Color;
import java.awt.Graphics;
public class GraphicsPanel extends javax.swing.JPanel {

private int x;
private int z;
private int y;

public GraphicsPanel() { //constructor
    initComponents();
    x = getHeight() / 2;
    z = getWidth() / 2;
    y = getHeight() - 1;
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);

        x = getHeight() / 2;
        z = getWidth() / 2;
        y = getHeight() - 1;

    setBackground(new Color(255, 255, 255));

    g.setColor(Color.red);
    g.fillRect(0, x, getWidth() - 1, y);

    g.setColor(Color.blue);
    int[] poleX = {0, 0, z};
    int[] poleY = {0, y, x};
    g.fillPolygon(poleX, poleY, 3);
  }
}

我认为你想要的是在你的面板中绘制你的图像(看起来很像捷克国旗!),而不是填充所有 space。例如,如果框架很宽,图像将不会填满整个宽度。如果我没理解错的话,这并不难。

在您的代码中,您获得了面板的宽度和高度。完成后,做一些算术。如果宽高比为 "too wide",那么您的图片将填充高度,否则它将填充宽度。现在你知道了一个维度,所以你可以计算另一个维度,你只绘制足够大的图像以适应这些维度。

编辑:示例计算...

if panel width / panel height > 4 / 3
    // too wide
    // use panel height as image height
    // calculate image width from image height
else
    // use panel width as image width
    // calculate image height from image width

面板的大小和形状很难(不可能?)固定。您必须将面板添加到容器(在您的示例中为 JFrame,但可以是任何内容),并且容器将使用布局管理器来设置面板大小。

I need to maintain image that I'm drawing (but I guess it will be easier to maintain component's ratio). Because my image is not classic image (png, jpg) but a few shapes from draw/fill that looks like an image.

好吧,您可以轻松地创建一个 BufferedImage 尺寸合理、宽高比合适的图像,然后将您的形状绘制到 BufferedImage

BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();

//  paint image background

g2d.setColor( ... );
g2d.fillRect(0, 0, width, height);

//  draw shapes

g2d.fillOval(....);

您可以使用 Darryls Stretch Icon 在 JLabel 中显示图像。 StretchIcon class 将在标签可用的 space 范围内按比例缩放图标:

JLabel label = new JLabel( new StretchIcon(image) );
frame.add(label);