旋转图像,图像宽度和高度不均匀

时间:2014-07-10 13:59:25

标签: java image rotation graphics2d

我正在尝试旋转宽度和高度不均匀的图像说:890W 180H ...适用于(512X512)或(72x72)

以下代码适用于高度和宽度相同的图像。如果我在paintComponent()上旋转相同的图像将旋转正常,但它会导致图像平移问题。有人可以为我提供一种旋转图像的替代方法,而无需使用' g.rotate()'在paintComponent()上,或者至少帮助我理解如何在宽度和高度不等的图像上执行旋转

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;

import javax.swing.JPanel;

public class ImageHolder extends JPanel implements MouseListener {
  BufferedImage image;
  int imageX = 0, imageY = 0;
  int parentWidth, parentHeight;

  public ImageHolder() {}


  public ImageHolder(BufferedImage image) {
    this.image = image;
    setSize(new Dimension(800, 600));
    setPreferredSize(new Dimension(800, 600));
    parentWidth = this.getWidth();
    parentHeight = this.getHeight();
    imageX = (this.getWidth() - image.getWidth())/2;
    imageY = (this.getHeight() - image.getHeight())/2;
    addMouseListener(this);
 }

 @Override
 protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.drawImage(image, imageX, imageY, (int) image.getWidth(), (int) image.getHeight(), null);
 }

 @Override
 public void mouseClicked(MouseEvent e) {
    rotate(Math.PI / 2);
    repaint();
 }

 private void rotate(double d) {
    BufferedImage clonedImage =new BufferedImage((int) this.image.getWidth(), (int) this.image.getHeight(),this.image.getType());
    Graphics2D g2d = clonedImage.createGraphics();
    g2d.rotate(d, clonedImage.getWidth() / 2, clonedImage.getHeight() / 2);
    g2d.drawImage(this.image, null, 0, 0);
    g2d.dispose();
    this.image = clonedImage;
}


@Override
public void mousePressed(MouseEvent e) {}

@Override
public void mouseReleased(MouseEvent e) {}

@Override
public void mouseEntered(MouseEvent e) {}

@Override
public void mouseExited(MouseEvent e) {}

}

1 个答案:

答案 0 :(得分:1)

您应该使用以下一系列命令来获得有效的转换:

g.translate(newCenterX, newCenterY);
g.rotate(d);
g.translate(-centerX, -centerY);

其中centerX/Y是原始中心的坐标,newCenterX/Y是新中心的坐标。请注意,旋转90°会切换图像的宽度/高度,从而也会切换它们的中心X / Y坐标。这意味着以下内容:

Rotation    X    Y
0°          X    Y
90°         Y    X
180°        X    Y
270°        Y    X
360°        X    Y

因此newCenterX/Y取决于d

的值