我有自己的自定义控件,可以为其内容维护背景图像。此缓冲区的类型为BufferedImage
。
注意!背景图像的使用是由于要求。不要教我在paintComponent()
目前我正在按以下方式调整图片大小:
@Override
public void setBounds(int x, int y, int width, int height) {
if( bufferedImage == null ) {
bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
}
else {
if( bufferedImage.getWidth() < width || bufferedImage.getHeight() < height ) {
BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
newImage.createGraphics().drawImage(bufferedImage, 0, 0, null);
bufferedImage = newImage;
}
}
super.setBounds(x, y, width, height);
}
不幸的是,这需要创建新的BufferedImage
对象,因此使之前获得的Graphics
对象无效。
所以我必须拥有自己的方法
public Graphics2D createImageGraphics() {
if( bufferedImage != null ) {
return bufferedImage.createGraphics();
}
else {
return null;
}
}
虽然我想覆盖getGraphics()
。
是否可以调整图像大小以保存图形对象?
答案 0 :(得分:-1)
以下是在Swing中执行自定义绘画的小例子:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JFrameTest {
private boolean drawOval = false;
protected void initUI() {
final JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (drawOval) {
g.setColor(Color.BLUE);
g.drawOval(0, 0, 100, 100);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
};
AbstractAction drawAction = new AbstractAction("Draw") {
@Override
public void actionPerformed(ActionEvent e) {
drawOval = true;
panel.repaint();
}
};
JButton drawButton = new JButton(drawAction);
JPanel buttonPanel = new JPanel();
buttonPanel.add(drawButton);
JFrame frame = new JFrame();
frame.add(panel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new JFrameTest().initUI();
}
});
}
}