简体   繁体   English

Java在中心旋转图像

[英]Java rotate an image in the center

How do i rotate an image in the center if itself? 如何在中心旋转图像? this code works, but it rotates the image in the top-left corner of the screen: 此代码有效,但它会旋转屏幕左上角的图像:

    AffineTransform oldtrans = new AffineTransform();
    AffineTransform trans = new AffineTransform();

    trans.setToIdentity();
    trans.rotate(Math.toRadians(angle));
    trans.translate(_x-(width/2), _y-(height/2));
    g.setTransform(trans);
    g.drawImage(this.getImage(), (int)_x, (int)_y, (int)width, (int)height, null);
    trans.setToIdentity();
    g.setTransform(oldtrans);

Please help!!! 请帮忙!!!

你应该在rotate()调用中再给出两个参数:

affineTransform.rotate(Math.toRadians(angle), m_imageWidth/2, m_imageHeight/2); 

You're halfway there, literally. 从字面上看,你已经到了一半了。 What you have to do is two translations. 你要做的是两个翻译。 Something along the lines of: 有点像:

  1. Translate the image to its centre (tanslate(x-width/2, y-width/2). 将图像平移到其中心(tanslate(x宽度/ 2,y宽度/ 2)。
  2. Rotate the image by angle radians (like you have). 按角度弧度旋转图像(就像你一样)。
  3. Translate the image back to its original position (tanslate(x+width/2, y+width/2). 将图像转换回原始位置(tanslate(x + width / 2,y + width / 2)。

Hope this works for you. 希望这对你有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM