Search code examples
qtdrawqpixmap

How can I rotate the QBitmap nicely while still drawing the position accurately?


I want to draw a QBitmap over an arbitrary point.

For example, I want to draw a point (5, 5) on the QBitmap to match a point (10,10) on the screen.

I also want to change the angle of the QBitmap around that point, but if I rotate it, the drawing will be out of position.

How can I rotate the QBitmap nicely while still drawing the position accurately?

bool MyApp::eventFilter(QObject *obj, QEvent *event)
{
   QBitmap qBmp = QBitmap(".\\pix1.bmp");
   
   int iPixX = 10;
   int iPixY = 10;
   
   int iDrawPointX = 5;
   int iDrawPointY = 5;
   
   if( event->type() == QEvent::Paint ) {
        QPainter painter(m_pUi->drawLayer);

        painter.setPen( QPen(Qt::black) );
        painter.translate(iPixX, iPixY);        
        painter.rotate(45);
        painter.translate(iPixX - iDrawPointX, iPixY - iDrawPointX);

        painter.drawPixmap(0, 0, qBmp);
    }

    painter.end();
    return true;
  }
  
  return false;
 }

Solution

  • Make translation to position your bitmap in screen coordinates:

    painter.translate(iPixX - iDrawPointX,iPixY - iDrawPointY);
    

    Make translation to position the bitmap in the point which is the origin of rotation operation (this is your missed step, (5,5) coord of bitmap will be rotation origin point):

    painter.translate(-iPixX, -iPixY);
    

    Make rotation:

    painter.rotate(45);
    

    Back to screen coordinates position:

    painter.translate(iPixX, iPixY);    
    

    The full code:

        painter.translate(iPixX, iPixY);        
        painter.rotate(45);
        painter.translate(-iPixX, -iPixY);
        painter.translate(iPixX - iDrawPointX,iPixY - iDrawPointY);