调整图纸大小以匹配框架大小 [英] Resize drawing to match frame size
问题描述
我写了一个应用程序,根据固定的像素位置自定义绘制paint()内的所有内容。然后我禁用框架的大小调整,使其始终可见。
I've written an app that custom draws everything inside paint() based on fixed pixel positions. Then I disabled resize of the frame so its always visible.
但是,现在我希望能够调整它的大小,但我不想更改我的绘制代码。我希望我可以抓住300x300平方的Graphics g对象并在我的所有绘制代码之后将其调整为JFrame当前大小,但我不知道我在做什么。
However, now I would like to be able to resize it but I dont want to change my drawling code. I was hoping I could grab the 300x300 square of the Graphics g object and resize it to the JFrame current size after all of my drawling code, but I have no idea what I'm doing.
这里是示例代码。在这里我希望100x100平方保持在中间,与调整大小的JFrame成比例:
Here sample code. In this I want the 100x100 square to remain in the middle, proportionate to the resized JFrame:
package DrawAndScale;
import java.awt.Color;
import java.awt.Graphics;
public class DASFrame extends javax.swing.JFrame {
public DASFrame() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
this.setSize(300, 300);
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DASFrame().setVisible(true);
}
});
}
@Override
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fill3DRect(100, 100, 100, 100, true);
}
}
谢谢。
推荐答案
假设您将绘制300x300的方法重命名为paint300,请定义缓冲图像:
Assuming you rename your method that paints for 300x300 as paint300, define a buffered image:
@Override public void paint(Graphics g) {
Image bufferImage = createImage(300, 300); // empty image
paint300(bufferImage.getGraphics()); // fill the image
g.drawImage(bufferImage, 0, 0, null); // send the image to graphics device
}
以上是您想要绘制的时间全尺寸(300x300)。
如果您的窗口调整大小:
Above is when you want to draw at full size (300x300). If your window is resized:
@Override public void paint(Graphics g) {
Image bufferImage = createImage(300, 300);
paint300(bufferImage.getGraphics());
int width = getWidth();
int height = getHeight();
CropImageFilter crop =
new CropImageFilter((300 - width)/2, (300 - height)/2 , width, height);
FilteredImageSource fis = new FilteredImageSource(bufferImage, crop);
Image croppedImage = createImage(fis);
g.drawImage(croppedImage, 0, 0, null);
}
新类来自java.awt.image。*。
The new classes are from from java.awt.image.*.
我没有测试这段代码。只是向你发送正确的方向。
I didn't test this code. It's just to send you in the right direction.
这篇关于调整图纸大小以匹配框架大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!