Как я могу повернуть изображение с помощью Java / Swing и затем установить его происхождение на 0,0? - PullRequest
3 голосов
/ 22 апреля 2010

Я могу повернуть изображение, которое было добавлено в JLabel. Единственная проблема заключается в том, что если высота и ширина не равны, повернутое изображение больше не будет отображаться в начале координат JLabel (0,0).

Вот что я делаю. Я также пытался использовать AffineTransform и вращать само изображение, но с теми же результатами.

Graphics2D g2d = (Graphics2D)g;
g2d.rotate(Math.toRadians(90), image.getWidth()/2, image.getHeight()/2);
super.paintComponent(g2d);

Если у меня есть изображение, ширина которого больше его высоты, то поворот этого изображения с использованием этого метода, а затем рисование приведет к тому, что изображение будет нарисовано вертикально над точкой 0,0 и горизонтально справа от точки 0 , 0.

Ответы [ 4 ]

4 голосов
/ 22 апреля 2010

Используйте g2d.transform (), чтобы сдвинуть изображение туда, где оно необходимо. Я просто представляю, каким может быть расчет, но я думаю что-то вроде:

int diff = ( image.getWidth() - image.getHeight() ) / 2;
g2.transform( -diff, diff );

Кстати, у вас могут быть проблемы с меткой, сообщающей о ее предпочтительном размере - вам может потребоваться переопределить getPreferredSize () и учесть изменение ширины и высоты изображений при повороте.

3 голосов
/ 22 апреля 2010
AffineTransform trans = new AffineTransform(0.0, 1.0, -1.0, 0.0, image.getHeight(), 0.0);
g2d.transform(trans);
g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
2 голосов
/ 20 июня 2012

Следующая функция будет вращать буферизованное изображение, которое будет неопределенным, если оно будет идеальным квадратом или нет.

public BufferedImage rotate(BufferedImage image)
{
  /*
   * Affline transform only works with perfect squares. The following
   *   code is used to take any rectangle image and rotate it correctly.
   *   To do this it chooses a center point that is half the greater
   *   length and tricks the library to think the image is a perfect
   *   square, then it does the rotation and tells the library where
   *   to find the correct top left point. The special cases in each
   *   orientation happen when the extra image that doesn't exist is
   *   either on the left or on top of the image being rotated. In
   *   both cases the point is adjusted by the difference in the
   *   longer side and the shorter side to get the point at the 
   *   correct top left corner of the image. NOTE: the x and y
   *   axes also rotate with the image so where width > height
   *   the adjustments always happen on the y axis and where
   *   the height > width the adjustments happen on the x axis.
   *   
   */
  AffineTransform xform = new AffineTransform();

  if (image.getWidth() > image.getHeight())
  {
    xform.setToTranslation(0.5 * image.getWidth(), 0.5 * image.getWidth());
    xform.rotate(_theta);

    int diff = image.getWidth() - image.getHeight();

    switch (_thetaInDegrees)
    {
    case 90:
      xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth() + diff);
      break;
    case 180:
      xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth() + diff);
      break;
    default:
      xform.translate(-0.5 * image.getWidth(), -0.5 * image.getWidth());
      break;
    }
  }
  else if (image.getHeight() > image.getWidth())
  {
    xform.setToTranslation(0.5 * image.getHeight(), 0.5 * image.getHeight());
    xform.rotate(_theta);

    int diff = image.getHeight() - image.getWidth();

    switch (_thetaInDegrees)
    {
    case 180:
      xform.translate(-0.5 * image.getHeight() + diff, -0.5 * image.getHeight());
      break;
    case 270:
      xform.translate(-0.5 * image.getHeight() + diff, -0.5 * image.getHeight());
      break;
    default:
      xform.translate(-0.5 * image.getHeight(), -0.5 * image.getHeight());
      break;
    }
  }
  else
  {
    xform.setToTranslation(0.5 * image.getWidth(), 0.5 * image.getHeight());
    xform.rotate(_theta);
    xform.translate(-0.5 * image.getHeight(), -0.5 * image.getWidth());
  }

  AffineTransformOp op = new AffineTransformOp(xform, AffineTransformOp.TYPE_BILINEAR);

  BufferedImage newImage =new BufferedImage(image.getHeight(), image.getWidth(), image.getType());
  return op.filter(image, newImage);
}
1 голос
/ 22 апреля 2010

Класс Rotated Icon может быть тем, что вы ищете.

...