gpt4 book ai didi

java - Graphics2D 转换结果与手动转换不匹配

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:08:55 26 4
gpt4 key购买 nike

我正在使用 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)
}

预期行为

蓝色矩形(手动计算) overdraw 了红色矩形(通过变换计算)。

有经验的行为

The blue rectangle has an offset of 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 类型。

最佳答案

您的转换基本上只是 (520.55, 182.55) 的翻译。并且因为它具有小数像素值,所以它实际上对舍入的选择很敏感。如果您启用了抗锯齿功能,您实际上会得到一个 4 像素的红色 Blob ,覆盖了重叠的像素。否则,鉴于舍入为整数和截断为整数之间的歧义,您看到的行为(分歧)是合理的。

关于java - Graphics2D 转换结果与手动转换不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11402530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com