gpt4 book ai didi

java - 翻转和旋转图像。仿射变换在 java 中无法正常工作

转载 作者:行者123 更新时间:2023-12-01 12:28:24 25 4
gpt4 key购买 nike

嘿,我实现了旋转和翻转图像的代码。

  • 向左、向右、上下颠倒旋转均有效。
  • 水平翻转、垂直翻转都有效。
  • 但他们不一起工作

当我翻转图像然后旋转时,它就会消失。

但是

当我翻转和翻转图像时(所以它与翻转之前一样),我可以正常旋转。

<小时/>

我尝试理解出了什么问题,我认为问题在于变换或缩放。

您知道如何修复此代码吗?

/**
* 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);

}
}

最佳答案

如果您希望它们一起工作,您必须保存通过转换制作的图像。这是一个例子

图像原点 = ...;
图像变换复制 = ...;
仿射变换 at = ...;
TransformedCopy.getGraphics().setTransform(at).drawImage(orig);
//transformedCopy 现在将拥有转换后图像的副本

关于java - 翻转和旋转图像。仿射变换在 java 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26140925/

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