【发布时间】:2014-10-01 12:02:39
【问题描述】:
嘿,我实现了旋转和翻转图像的代码。
- 左、右、颠倒旋转有效。
- 水平翻转,垂直工作。
- 但他们不能一起工作
当我翻转图像然后旋转时,它会消失。
但是
当我翻转和翻转图像时(就像翻转前一样),我可以正常旋转。
我试图了解哪里出了问题,我认为问题在于变换或缩放。
您知道如何修复此代码吗?
/**
* Paint the icons of this compound icon at the specified location
*
* @param c
* The component on which the icon is painted
* @param g
* the graphics context
* @param x
* the X coordinate of the icon's top-left corner
* @param y
* the Y coordinate of the icon's top-left corner
*/
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g.create();
AffineTransform af = g2.getTransform();
int cWidth = icon.getIconWidth() / 2;
int cHeight = icon.getIconHeight() / 2;
int xAdjustment = (icon.getIconWidth() % 2) == 0 ? 0 : -1;
int yAdjustment = (icon.getIconHeight() % 2) == 0 ? 0 : -1;
if (rotate == Rotate.DOWN) {
g2.translate(x + cHeight, y + cWidth);
g2.rotate(Math.toRadians(90));
icon.paintIcon(c, g2, -cWidth, yAdjustment - cHeight);
} else if (rotate == Rotate.UP) {
g2.translate(x + cHeight, y + cWidth);
g2.rotate(Math.toRadians(-90));
icon.paintIcon(c, g2, xAdjustment - cWidth, -cHeight);
} else if (rotate == Rotate.UPSIDE_DOWN) {
g2.translate(x + cWidth, y + cHeight);
g2.rotate(Math.toRadians(180));
icon.paintIcon(c, g2, xAdjustment - cWidth, yAdjustment - cHeight);
} else if (rotate == Rotate.VERTICAL) {
g2.translate(0, getIconHeight());
g2.scale(1, -1);
icon.paintIcon(c, g2, x, y);
vert = !vert; //boolean flag
} else if (rotate == Rotate.HORIZONTAL) {
g2.translate(getIconWidth(), 0);
g2.scale(-1, 1);
icon.paintIcon(c, g2, x, y);
hor = !hor; //boolean flag
} else if (rotate == Rotate.VERTICALLY_HORIZONTAL) {
g2.translate(getIconWidth(), getIconHeight());
g2.scale(-1, -1);
icon.paintIcon(c, g2, x, y);
hor = !hor;
vert = !vert;
} else if (rotate == Rotate.CENTER) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
AffineTransform original = g2.getTransform();
AffineTransform at = new AffineTransform();
at.concatenate(original);
at.translate((getIconWidth() - icon.getIconWidth()) / 2,
(getIconHeight() - icon.getIconHeight()) / 2);
at.rotate(Math.toRadians(angle), x + cWidth, y + cHeight);
g2.setTransform(at);
icon.paintIcon(c, g2, x, y);
g2.setTransform(original);
}
}
【问题讨论】:
-
在
icon.paintIcon之后需要恢复g2的原始状态,做逆运算。 -
也许可以,但是当布尔标志 vert 设置为 true 时,我尝试执行此逆运算: if(vert) { g2.translate(0, getIconHeight()); g2.scale(1, -1); }
-
有人知道如何用数学方法求逆吗?
-
g2.scale(1, -1); g2.translate(0, -getIconHeight()); -
好吧,当有一个垂直翻转时,我设置了布尔标志“vert”,并且在用于旋转 LEFT(上)和 DOWN(右)的 if 块中,我在正常平移和旋转之前进行此反转,但它没有不工作
标签: java swing java-2d flip affinetransform