-3

我有自己的自定义控件,它为其内容维护支持图像。此缓冲区的类型为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().

是否可以调整图像大小以保存 Graphics 对象?

4

1 回答 1

-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();
            }
        });

    }
}
于 2013-02-20T15:28:56.027 回答