[英]How can I resize a rectangular image to a square image while maintaining aspect ratio in Java?
[英]How do I resize a JFrame while maintaining aspect ratio?
我希望用戶能夠調整JFrame的寬度/高度,同時在其寬度和高度之間保持相同的比率。 換句話說,我想強制高度隨着寬度保持相同的框架形狀而變化。
public void componentResized(ComponentEvent arg0)
{
int setHeight = arg0.getComponent().getHeight();
int setWidth = arg0.getComponent().getWidth();
double newWidth = 0;
double newHeight = 0;
{
if(setHeight != oldHeight)
{
heightChanged = true;
}
if(setWidth != oldWidth)
{
widthChanged = true;
}
}
{
if(widthChanged == true && heightChanged == false)
{
newWidth = setWidth;
newHeight = setWidth*HEIGHT_RATIO;
}
else if(widthChanged == false && heightChanged == true)
{
newWidth = setHeight * WIDTH_RATIO;
newHeight = setHeight;
}
else if(widthChanged == true && heightChanged == true)
{
newWidth = setWidth;
newHeight = setWidth*HEIGHT_RATIO;
}
}
int x1 = (int) newWidth;
int y1 = (int) newHeight;
System.out.println("W: " + x1 + " H: " + y1);
Rectangle r = arg0.getComponent().getBounds();
arg0.getComponent().setBounds(r.x, r.y, x1, y1);
widthChanged = false;
heightChanged = false;
oldWidth = x1;
oldHeight = y1;
}
看看以寬高比調整J幀的大小
我認為這就是您所需要的。
@Override
public void componentResized(ComponentEvent arg0) {
int W = 4;
int H = 3;
Rectangle b = arg0.getComponent().getBounds();
arg0.getComponent().setBounds(b.x, b.y, b.width, b.width*H/W);
}
嘗試使用componentEvent在調整框架大小時發出信號。 調整框架大小時,請跟蹤更改了哪個尺寸(x或y)。 使用getSize()方法獲取框架尺寸,然后獲取.getWidth()或.getHeight()以獲取調整為框架的新尺寸。 使用更改后的尺寸的新尺寸來計算其他尺寸的所需尺寸,並使用.setSize(int width,int height)設置框架的尺寸。
如果您在相同的調整大小中同時更改寬度和高度,則可能會有問題,如果這樣,您始終可以根據寬度確定高度,反之亦然
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.