【问题标题】:Rotating an Image object旋转图像对象
【发布时间】:2015-05-13 01:30:04
【问题描述】:

我有一个方法getImage() 需要旋转Image,将其存储在一个新变量中,然后返回新的Image。这是我的尝试,图像似乎是空的或什么的。它只是没有显示在屏幕上:

public Image getImage() {
    buffImage.createGraphics().rotate(direction);
    return buffImage;
}

当我取出buffImage.createGraphics().rotate(direction); 时,图像在屏幕上绘制得很好,没有问题,但当然没有旋转。

【问题讨论】:

  • rotate 设置了平移矩阵,这样当您在Graphics 上下文中绘制某些东西时,它会“旋转”指定的量,而不会旋转现有图像跨度>
  • 这个example 生成源图像的旋转版本,但它也确保生成的图像大小能够适合新旋转的图像。
  • example 在另一个Graphics 上下文中旋转图像,这可能更简单,但这取决于您要实现的目标...
  • IMO,旋转后需要重新绘制图像。

标签: java image graphics rotation bufferedimage


【解决方案1】:

因此,基于this answer 中的示例,您应该能够设计一种可以将源图像旋转给定度数的旋转方法,例如...

  // Make sure you actually load some image and assign it to this
  // variable, otherwise you will have a NullPointerException to 
  // deal with
  private BufferedImage source;

  public Image rotateBy(double degrees) {

    // The size of the original image
    int w = source.getWidth();
    int h = source.getHeight();
    // The angel of the rotation in radians
    double rads = Math.toRadians(degrees);
    // Some nice math which demonstrates I have no idea what I'm talking about
    // Okay, this calculates the amount of space the image will need in
    // order not be clipped when it's rotated
    double sin = Math.abs(Math.sin(rads));
    double cos = Math.abs(Math.cos(rads));
    int newWidth = (int) Math.floor(w * cos + h * sin);
    int newHeight = (int) Math.floor(h * cos + w * sin);

    // A new image, into which the original can be painted
    BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = rotated.createGraphics();
    // The transformation which will be used to actually rotate the image
    // The translation, actually makes sure that the image is positioned onto
    // the viewable area of the image
    AffineTransform at = new AffineTransform();
    at.translate((newWidth - w) / 2, (newHeight - h) / 2);

    // And we rotate about the center of the image...
    int x = w / 2;
    int y = h / 2;
    at.rotate(rads, x, y);
    g2d.setTransform(at);
    // And we paint the original image onto the new image
    g2d.drawImage(source, 0, 0, null);
    g2d.dispose();

    return rotated;
  }

【讨论】:

    【解决方案2】:

    您可以只使用Rotated Icon 并在JLabel 中显示Icon

    Rotated Icon 是一个可重用的类,因此您无需担心将旋转代码添加到需要此功能的每个类中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      • 2014-02-18
      • 1970-01-01
      相关资源
      最近更新 更多