[英]Java JPanel Scaling
嗨,我成功地用Java制作了一個GUI,該GUI將使用滑塊縮放多邊形和圓形。 一切正常,但我想知道是否有辦法更改原點(從何處縮放)。 現在,它從角落縮放,我希望它從中間縮放,因此我可以從中間開始,然后均勻地縮放。 另外,如果有人能告訴我用某種圖像替換我擁有的Rectangle的簡便方法,以便您可以放大和縮小圖片,那就太好了! 謝謝! 這是我的代碼:
import javax.swing.*;
public class Fred
{
public static void main(String[] args)
{
TheWindow w = new TheWindow();
w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //X wont close the window with out this line
w.setSize(375,375);
w.setVisible(true);
}
}
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
public class TheWindow extends JFrame
{
private JSlider slider; //declare slider
private drawRect myPanel; //declare/ create panel
public TheWindow()
{
super("Slider Example"); //make title
myPanel = new drawRect();
myPanel.setBackground(Color.green); //change background color
slider = new JSlider(SwingConstants.VERTICAL, 0, 315, 10);// restrains the slider from scaling square to 0-300 pixels
slider.setMajorTickSpacing(20); //will set tick marks every 10 pixels
slider.setPaintTicks(true); //this actually paints the ticks on the screen
slider.addChangeListener
(
new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
myPanel.setD(slider.getValue()); //Wherever you set the slider, it will pass that value and that will paint on the screen
}
}
);
add(slider, BorderLayout.WEST); //similar to init method, adds slider and panel to GUI
add(myPanel, BorderLayout.CENTER);
}
}
import java.awt.*;
import javax.swing.*;
public class drawRect extends JPanel
{
private int d = 25; //this determines the beginning length of the rect.
public void paintComponent(Graphics g)//paints circle on the screen
{
super.paintComponent(g); //prepares graphic object for drawing
g.fillRect(15,15, d, d); //paints rectangle on screen
//x , y, width, height
}
public void setD(int newD)
{
d = (newD >= 0 ? newD : 10); //if number is less than zero it will use 10 for diameter(compressed if statement)
repaint();
}
public Dimension getPrefferedSize()
{
return new Dimension(200, 200);
}
public Dimension getMinimumSize()
{
return getPrefferedSize();
}
}
更改“原點”,使其成為“縮放”的中心,基本上只是從中心點減去d
一半的過程。
因此,假設中心點為28
( (25 / 2) + 15
),則只需從該點減去d / 2
(25/2),即28 - (25 / 2) = 15
或足夠接近。 。
我修改了paintComponent
方法進行測試,因此矩形始終位於面板的中心,但是您可以提供任意值代替originX
和originY
@Override
public void paintComponent(Graphics g)//paints circle on the screen
{
super.paintComponent(g); //prepares graphic object for drawing
int originX = getWidth() / 2;
int originY = getHeight() / 2;
int x = originX - (d / 2);
int y = originY - (d / 2);
System.out.println(x + "x" + y);
g.fillRect(x, y, d, d); //paints rectangle on screen
//x , y, width, height
}
至於縮放圖像,您應該查看Graphics#drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
,但是請注意,這會將圖像縮放到絕對大小,不會保持圖像比例。
更好的解決方案可能是使用介於0和1之間的雙精度值,並將該值乘以各個元素,以獲得所需的絕對值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.