【发布时间】:2012-07-09 07:01:51
【问题描述】:
我正在使用 Java 的 Graphics2D 在组件上绘制,并使用 AffineTransform 来操作我的绘图。 Graphics2D 为此提供了一种方法变换,它采用 AffineTransform。
有时我需要在不使用内置转换的情况下手动操作一个点。 但是,当我尝试使用与 Graphics2D.transform 相同的变换来变换一个点时,有时结果点并不相同。
下面的代码重现了这个问题(它是 Scala 代码,但我认为你可以想象 Java 代码。):
var transformationMatrix = new AffineTransform()
/*
* transformationMatrix is modified throughout the program
* ...
*/
override def paintComponent(g: Graphics2D) = {
super.paintComponent(g)
/* 1. transform using graphics transform */
g.transform(transformationMatrix)
g.setColor(Color.RED)
g.fill(new Rectangle(0, 0, 1, 1))
/* 2. transform point manually */
g.setTransform(new AffineTransform) // reset transformation to standard
val p0 = new Point(0, 0)
val pDest = new Point()
transformationMatrix.transform(p0, pDest)
g.setColor(Color.BLUE)
g.fill(new Rectangle(pDest.x, pDest.y, 1, 1)
}
预期行为
蓝色矩形(手动计算)覆盖红色矩形(通过变换计算)。
经验丰富的行为
我承认我的 transformationMatrix 并不是真正的整数,但这应该不是问题,不是吗?
affineTransform = 1.1, 0.0, 520.55
0.0, 1.1, 182.54999999999995
0.0, 0.0, 1.0
这是一个错误还是我错过了一些深刻的见解?
编辑:如果您将 transformationMatrix 设置为
,您可以重现该错误transformationMatrix = new AffineTransform(1.1, 0.0, 0.0, 1.1, 521.55, 183.54999999999995)
在paintComponent 的开头。请注意,g 的类型是 Graphics2D。
【问题讨论】:
-
我想知道调用paint() 时是否可能有不同的转换处于活动状态。我会在方法开始时尝试 g.getTransform() 并使用结果来恢复“标准”转换。
-
这也无济于事。 g.getTransform() 返回单位矩阵并将其保存并稍后恢复会导致相同的行为。
标签: java swing scala transform graphics2d