1. ホーム
  2. Java

Java のドローイング。Graphicsクラスを使って、直線、矩形、楕円・円弧・扇形、画像、テキストを描画する。

2022-03-01 13:53:44
<パス

この記事へのリンク https://blog.csdn.net/xietansheng/article/details/55669157

Java Swingによるグラフィカルインターフェースの開発(目次)

1. グラフィックス描画用キャンバス

Graphicsクラスはキャンバスに相当し、各SwingコンポーネントはGraphicsオブジェクトを介して描画されることで表示されます。描画の原点は、以下のようにコンポーネントの左上に位置します。

Graphics クラスで共通する描画関連のメソッドです。

o パラメータ / セット。

// Create a copy of Graphics
Graphics create()
// Recycle Graphics
void dispose()

// Set the color of the brush
void setColor(Color c)
// Erase an area (show the background color after erasing)
void clearRect(int x, int y, int width, int height)


1. 線分/折れ線。

// Draw a line segment (or points if both points are the same)
void drawLine(int x1, int y1, int x2, int y2)
// draws a polyline based on the given multiple point coordinates
void drawPolyline(int xPoints[], int yPoints[], int nPoints)


2. 長方形 / 多角形。

// Draw a rectangle (hollow)
void drawRect(int x, int y, int width, int height)
// Fill a rectangle (solid)
void fillRect(int x, int y, int width, int height)

// draw a rectangle with rounded corners
void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)
// Fill a rounded rectangle
void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)

// Draw a 3D rectangle
void draw3DRect(int x, int y, int width, int height, boolean raised)
// Fill a 3D rectangle
void fill3DRect(int x, int y, int width, int height, boolean raised)

// draw a polygon based on the given coordinates of multiple points (first and last connected)
void drawPolygon(int xPoints[], int yPoints[], int nPoints)
// fill a polygon based on the given multiple point coordinates (first and last connected)
void fillPolygon(int xPoints[], int yPoints[], int nPoints)


3. 円弧/セクター。

// Draw an arc (arc)
void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)
// Fill an arc (sector)
void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)


4. 楕円形 :

// Draw an ellipse
void drawOval(int x, int y, int width, int height)
// Fill an ellipse
void fillOval(int x, int y, int width, int height)


5. 写真

/*
 * Read the image first
 */
// Toolkit toolkit class to read an image (GIF, JPEG or PNG) locally, on the network or in memory
Image image = Toolkit.getDefaultToolkit().getImage(String filename);
Image image = Toolkit.getDefaultToolkit().getImage(URL url);
Image image = Toolkit.getDefaultToolkit().createImage(byte[] imageData);

// ImageIO toolkit class to read images locally, on the network or in memory (BufferedImage inherits from Image)
BufferedImage bufImage = ImageIO.read(File input);
BufferedImage bufImage = ImageIO.read(URL input);
BufferedImage bufImage = ImageIO.read(InputStream input);

/*
 * PS_01: Image width and height: BufferedImage can get the width and height of the image directly by bufImage.getWidth() and bufImage.getHeight() methods;
 * Image gets the width and height by passing an additional ImageObserver parameter.
 *
 * PS_02: Image cropping: BufferedImage The bufImage.getSubimage(int x, int y, int w, int h) method can intercept any part of the image.
 * Any part of the image, returning a new instance of BufferedImage.
 *
 * PS_03: Image Scaling: Image can be scaled by the image.getScaledInstance(int width, int height, int hints) method.
 * Scaling, returning a new instance of Image.
 */

// Draw an image (all component classes implement the ImageObserver interface, i.e. the component instance is an ImageObserver)
boolean drawImage(Image image, int x, int y, int width, int height, ImageObserver observer)


6.テキスト

// Set the font (font, style, size)
void setFont(Font font)
// draw a piece of text, where the (x, y) coordinates refer to the position of the lower left corner of the text sequence
void drawString(String str, int x, int y)


2. グラフィックス2D

Graphicsのサブクラスは、通常、Swingコンポーネントの実際の描画に使用されます。 Graphics2D これは、より複雑な要件を描画するためのリッチなインターフェイスを提供するものです。

Graphics2D クラス内のメソッドの一部です。

1. パラメータ/設定

// Set the background (show this background after erasing)
void setBackground(Color color)
// Set the stroke's outline characteristics (such as brush width, solid line, dashed line, etc.)
void setStroke(Stroke s)


2. 描画結果の変形

// Panning
void tran
            }
        });
    }

    /**
     * window
     */
    public static class MyFrame extends JFrame {

        public static final String TITLE = "Java graphics drawing";

        public static final int WIDTH = 250;
        public static final int HEIGHT = 300;

        public MyFrame() {
            super();
            initFrame();
        }

        private void initFrame() {
            // Set the window title and window size
            setTitle(TITLE);
            setSize(WIDTH, HEIGHT);

            // set the default action of the window close button (exit the process when you click close)
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

            // Set the window position to the center of the screen
            setLocationRelativeTo(null);

            // Set the content panel of the window
            MyPanel panel = new MyPanel(this);
            setContentPane(panel);
        }

    }

    /**
     * Content Panel
     */
    public static class MyPanel extends JPanel {

        private MyFrame frame;

        public MyPanel(MyFrame frame) {
            super();
            this.frame = frame;
        }

        /**
         * Draw the content of the panel: This method will be called once after the JPanel is created to draw the content,
         * If the data changes later and needs to be redrawn, you can call updateUI() method to trigger
         * The system calls this method again to draw the content of the updated JPanel.
         */
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            // Calling Graphics' paint method again will automatically erase the old content when it is painted

            /* Open the comments below to see the effect of each drawing */

            // 1. line / fold
            drawLine(g);

            // 2. rectangle / polygon
            // drawRect(g);

            // 3. arc / sector
            // drawArc(g);

            // 4. ellipse
            // drawOval(g);

            // 5. image
            // drawImage(g);

            // 6. text
            // drawString(g);
        }

        /**
         * 1. line segment / fold line
         */
        private void drawLine(Graphics g) {
            frame.setTitle("1. Line / Fold");

            // To create a copy of Graphics, you need to change the parameters of Graphics,
            // The copy must be used here, to avoid affecting the original settings of Graphics
            Graphics2D g2d = (Graphics2D) g.create();

            // Anti-aliasing
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            // Set the brush color
            g2d.setColor(Color.RED);

            // 1. Draw line segment with two points: point(20, 50), point(200, 50)
            g2d.drawLine(50, 50, 200, 50);

            // 2. Draw line with multiple points: point(50, 100), point(100, 130), point(150, 70), point(200, 100)
            int[] xPoints = new int[] { 50, 100, 150, 200 };
            int[] yPoints = new int[] { 100, 120, 80, 100 };
            int nPoints = 4;
            g2d.drawPolyline(xPoints, yPoints, nPoints);

            // 3. Draw line segment with two points (set line width to 5px): point(50, 150), point(200, 150)
            BasicStroke bs1 = new BasicStroke(5); // outline of the stroke (brush width/line width of 5px)
            g2d.setStroke(bs1);
            g2d.drawLine(50, 150, 200, 150);

            // 4. Draw dashed line: divide the dashed line into segments (both solid and blank segments are considered as segments), alternating between solid and blank segments,
            // The length of each segment (both solid and blank) drawn is taken from the dash dashed pattern array (starting from the first
            // element), the following array means that the length of each segment is: 5px, 10px, 5px, 10px, ...
            float[] dash = new float[] { 5, 10 };
            BasicStroke bs2 = new BasicStroke(
                    1, // brush width/line width
                    BasicStroke.CAP_SQUARE,
                    BasicStroke.JOIN_MITER,
                    10.0f,
                    dash, // dashed line pattern array
                    0.0f
            );
            g2d.setStroke(bs2);
            g2d.drawLine(50, 200, 200, 200);

            // Destroy the copy you created when you're done with it
            g2d.dispose();
        }

        /**
         * 2. rectangle / polygon
         */
        private void drawRect(Graphics g) {
            frame.setTitle(&quo

結果が表示されます。

4. コンポーネントに描画された内容を画像として保存する

// import javax.imageio;
// import java.awt.image;

// get to the component (panel) where the content needs to be saved
JPanel panel = (JPanel) frame.getContentPane();

// create a buffered image of the same width and height as the panel
BufferedImage image = new BufferedImage(
        panel.getWidth(), 
        panel.getHeight(), 
        BufferedImage.TYPE_INT_ARGB
);

// Get the canvas for the cached image
Graphics2D g2d = image.createGraphics();

// Paint the contents of the panel to the canvas
panel.paint(g2d);

try {
    // save the cached image to a local file
    ImageIO.write(image, "png", new File("panel.png"));
} catch (Exception e) {
    e.printStackTrace();
}


拡張する。 Java 画像操作 - 画像の読み込み、描画、拡大縮小、切り取り、保存