大家好,
我的作业涉及在 Swing GUI 中绘制和操作形状。
我遇到了一个问题,当我尝试镜像我的形状时,我没有得到我想要的结果。
在Jpanels paintComponent中调用了drawallnodes方法
public void drawallnodes(ArrayList<DevicesEditor> nodes, Graphics2D g2)
{
int arraysize = nodes.size();
ArrayList<DevicesEditor> temparray;
AffineTransform at = new AffineTransform();
if (nodes.size() != 0)
{
System.out.println("nodes.size " + nodes.size());
if (currentarrayindex >= 0)
{
AffineTransform afx = new AffineTransform();// for rotate
for (int i = 0; i <= currentarrayindex; i++)
{
if (nodes.get(i).getWasAngleChanged())
{
afx.rotate(
Math.toRadians(nodes.get(i).getAngleInDegrees()),
nodes.get(i).getCenter().x,
nodes.get(i).getCenter().y);
nodes.get(i).setShape(
afx.createTransformedShape(nodes.get(i).getShape()));
nodes.get(i).setWasAngleChanged(false);
nodes.get(i).setokrajRectangle();
}
try
{
Rectangle r = nodes.get(i).getShape().getBounds();
}
catch (Exception e)
{
System.out.println(
"Exception found at getbounds, no shape with getbounds found");
}
AffineTransform saveXform = g2.getTransform();
g2.setColor(nodes.get(i).getColor());
int w = getWidth();
// it gets the JPanels width, which is set to 758px
at = AffineTransform.getTranslateInstance(w, 0);
System.out.println("*********Get width of shape: " + w);
at.scale(-1, 1); // mirror -x, y
g2.setPaint(Color.red);
g2.draw(at.createTransformedShape(nodes.get(i).getShape()));
try
{
g2.drawString(nodes.get(i).getText(),
(int) nodes.get(i).getCenter().getX(),
(int) nodes.get(i).getCenter().getY());
}
catch (Exception e)
{
System.err.println("No text found at node");
}
try
{
g2.draw((Shape) nodes.get(i).getShape());
}
catch (Exception e)
{
System.err.println("No shape found at node");
}
// g2.transform(AffineTransform.getRotateInstance(0, 1));
g2.setTransform(saveXform);
}
}
}
}
当我镜像形状时,例如,我在右侧绘制,但镜像图像出现在左侧...我想镜像形状并在同一位置获得镜像形状,而不是在我的 jpanel 上。 ...
谢谢你的帮助
最佳答案
当您使用像 scale(-1,1)
这样的简单仿射变换来变换形状时,它将在x=0 水平镜像。也就是说,当您在 (300,100) 处有一个对象时,它之后会在 (-300,100) 处。
为了“就地”(即,在其中心点的 x 坐标处)镜像对象,您必须
- 移动物体使其中心位于x=0
- 镜像对象
- 将物体移回原来的位置
这个转换序列可以(并且应该)由单个 AffineTransform
表示,该 AffineTransform
可以通过连接表示各个步骤的 AffineTransforms
获得。例如,您可以创建一个像
private static Shape mirrorAlongX(double x, Shape shape)
{
AffineTransform at = new AffineTransform();
at.translate(x, 0);
at.scale(-1, 1);
at.translate(-x, 0);
return at.createTransformedShape(shape);
}
为了绘制一个在其中心水平翻转(即镜像)的形状,您可以调用
g.fill(mirrorAlongX(shape.getBounds2D().getCenterX(), shape));
顺便说一句:摆脱所有这些被捕获的Exceptions
!这是一种可怕的风格。例如。用类似
String text = nodes.get(i).getText();
if (text != null)
{
g2.drawString(text, ...);
}
else
{
System.err.println("No text found at node"); // May not even be necessary...
}
关于java - JAVA中的镜像(Swing),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21855511/