如何在 Java 中调整 AWT 多边形的大小

发布于 2024-11-01 23:17:58 字数 78 浏览 4 评论 0原文

Java API 中是否有任何内置方法可以让我调整多边形的大小?

编写我自己的方法是一个非常简单的任务,还是已经有其他方法了?

Are there any in-built methods in the Java API which would allow me to resize a polygon?

Would it be quite a simple task to write my own method, or are there any others already made?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小草泠泠 2024-11-08 23:17:58

不,没有内置任何东西,尽管如此,当您绘制多边形时,您可以使用应用的变换矩阵来绘制多边形,该变换矩阵可以为您缩放多边形。 (或旋转、倾斜等)。

参见

Graphics2D.setTransform(transform);

假设您正在 JPanel 中绘制多边形,并且您已经重写了 JPanel 的 PaintComponent 方法。将 Graphics 对象转换为 Graphics2D 对象,并使用变换来适当缩放它:

public void paintComponent(Graphic g) {

     Graphics2D g2d = (Graphics2D) g;
     AffineTransform saveTransform = g2d.getTransform();

     try {
         AffineTransform scaleMatrix = new AffineTransform();
         scaleMatrix.scale(1.5, 1.5);
         //or whatever you want

         g2d.setTransform(scaleMatrix);
         g2d.drawPolygon(myPolygon);
     } finally {
         g2d.setTransform(saveTransform);
     }
}

您有可能可以在其他地方(一次)设置变换矩阵,而不是每次都在 PaintComponent 方法中设置,但我在这里这样做是为了展示如何做到这一点。

另请注意,这将移动多边形,您可能希望将其应用于变换:

  • 添加平移以将多边形移动到原点
  • 添加比例
  • 添加平移以将多边形移回原始位置

,这样,物体不会移动,只会缩放。

No, nothing built in, altho, when you draw the polygon, you can draw the polygon with a transformation matrix applied which could scale the polygon for you. (or rotate, skew, etc, etc).

see

Graphics2D.setTransform(transform);

Lets assume you are drawing the polygon in a JPanel, and you have overridden the paintComponent method of JPanel. Cast the Graphics object to a Graphics2D object, and use transforms to scale it as appropriate:

public void paintComponent(Graphic g) {

     Graphics2D g2d = (Graphics2D) g;
     AffineTransform saveTransform = g2d.getTransform();

     try {
         AffineTransform scaleMatrix = new AffineTransform();
         scaleMatrix.scale(1.5, 1.5);
         //or whatever you want

         g2d.setTransform(scaleMatrix);
         g2d.drawPolygon(myPolygon);
     } finally {
         g2d.setTransform(saveTransform);
     }
}

Chances are you can set up the transformation matrix elsewhere (once) instead of each time in the paintComponent method, but i did here to show how to do it.

Also note, that this will move the polygon, you would probably want apply this to the transform:

  • add a translate to move the polygon to the origin
  • add a scale
  • add a translate to move the polygon back to the original position

in this way, the object doesn't move it just scales.

玉环 2024-11-08 23:17:58

是的,AffineTransform.createTransformedShape(Shape) 将创建任何 Shape 的转换副本(可能是 PolygonPath2D。)

Yes, AffineTransform.createTransformedShape(Shape) will create a transformed copy of any Shape (which may be a Polygon or Path2D.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文