[英]How to keep aspect ratio in JPanel
我有點堅持在JPanel
上保持寬高比。
我已經從Netbeans使用邊框布局默認生成了JFrame
。 整個框架充滿了我的JPanel
(來自我的自定義類GraphicsPanel.java,擴展了JPanel
)。
GraphicsPanel類只有一種覆蓋方法,可以使用一些基本構造函數來繪制圖形。 我的JPanel
上有一個矩形和多邊形。 我想要實現的是,當我調整框架的大小時,我希望將JPanel
的縱橫比保持在4:3(或類似的比例)。 當框架對於寬高比而言太大時,它將使用某些默認顏色填充框架背景。
我已經閱讀了一些有關寬高比的主題(例如this )。 但是沒有運氣,我仍然不知道如何去做。
這是我的JPanel
類中的代碼。 我是新手,我想學習如何使用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);
}
}
我認為您想要的是在面板中繪制圖像(看起來很像捷克國旗!),但不填充所有空間。 例如,如果邊框非常寬,則圖像將不會填滿整個寬度。 如果我理解正確,這並不難。
在代碼中,您將獲得面板的寬度和高度。 完成后,請進行一些算術運算。 如果縱橫比“太寬”,則圖像將填充高度,否則將填充寬度。 現在您知道了一個尺寸,因此您可以計算另一個尺寸,並且只繪制足夠大的圖像以適合這些尺寸。
編輯 :示例計算...
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,但可以是任何東西),容器將使用布局管理器來設置面板大小。
我需要維護要繪制的圖像(但是我想維護組件的比例會更容易)。 因為我的圖像不是經典圖像(png,jpg),而是繪制/填充中的一些形狀看起來像圖像。
好了,您可以輕松地以適當的寬高比以合理的大小創建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
類將在標簽可用的空間內按比例縮放Icon:
JLabel label = new JLabel( new StretchIcon(image) );
frame.add(label);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.