在Java中,要实现正方形的平移变换,可以使用Graphics类的drawRect()方法和translate()方法。以下是一个简单的示例:
import javax.swing.*;
import java.awt.*;
public class SquareTranslationDemo extends JFrame {
public SquareTranslationDemo() {
setTitle("Square Translation Demo");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
@Override
public void paint(Graphics g) {
super.paint(g);
// 设置正方形的初始位置和大小
int x = 100;
int y = 100;
int width = 50;
int height = 50;
// 绘制原始正方形
g.setColor(Color.BLUE);
g.drawRect(x, y, width, height);
// 平移变换
int translationX = 50;
int translationY = 50;
g.translate(translationX, translationY);
// 绘制平移后的正方形
g.setColor(Color.RED);
g.drawRect(x, y, width, height);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SquareTranslationDemo demo = new SquareTranslationDemo();
demo.setVisible(true);
});
}
}
在这个示例中,我们首先绘制了一个蓝色的正方形,然后使用g.translate()
方法进行平移变换。平移的距离由translationX
和translationY
决定。最后,我们在平移后的位置绘制了一个红色的正方形。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:Java中正方形边框的绘制技巧