温馨提示×

如何在Java中对正方形进行缩放操作

小樊
82
2024-08-30 07:32:02
栏目: 编程语言

在Java中,可以使用Graphics2D类的scale()方法来对正方形进行缩放操作

import javax.swing.*;
import java.awt.*;

public class SquareScalingExample extends JFrame {
    public SquareScalingExample() {
        setTitle("Square Scaling Example");
        setSize(400, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);

        Graphics2D g2d = (Graphics2D) g;

        // 设置缩放比例
        double scaleX = 2.0;
        double scaleY = 2.0;

        // 获取画布的宽度和高度
        int canvasWidth = getWidth();
        int canvasHeight = getHeight();

        // 计算正方形的大小和位置
        int squareSize = 100;
        int squareX = (canvasWidth - squareSize) / 2;
        int squareY = (canvasHeight - squareSize) / 2;

        // 绘制原始正方形
        g2d.setColor(Color.BLUE);
        g2d.fillRect(squareX, squareY, squareSize, squareSize);

        // 应用缩放
        g2d.scale(scaleX, scaleY);

        // 计算缩放后的正方形的位置
        int scaledSquareX = (int) (squareX / scaleX);
        int scaledSquareY = (int) (squareY / scaleY);

        // 绘制缩放后的正方形
        g2d.setColor(Color.RED);
        g2d.fillRect(scaledSquareX, scaledSquareY, squareSize, squareSize);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            new SquareScalingExample().setVisible(true);
        });
    }
}

这个示例将创建一个包含两个正方形的窗口。第一个正方形是蓝色的,表示原始大小。第二个正方形是红色的,表示缩放后的大小。通过调整scaleX和scaleY变量的值,可以控制正方形的缩放比例。

0