Reputation: 11797
I have a rectangular image (i.e. 1280 x 1024) that I need to rotate around its central point and then translate to a given point.
In a widget paintEvent method, that's what I do:
def paintEvent(self, event):
# self._center are the coordinates where I want to set the rotated image's center.
t = QtGui.QTransform()
s = self._pm.size() # self._pm is the image to rotate.
t.translate(s.width() / 2, s.height() / 2)
t.rotate(self._degrees)
t.translate(-s.width() / 2, -s.height() / 2)
# now my image is properly rotated. Now I need to translate it to the final
# coordinates.
t.translate (self._center.x, self._center.y)
p = QtGui.QPainter(self)
p.setTransform(t)
p.drawPixmap(0, 0, self._pm)
p.end()
And that's fine with rotation. Problem is that I can't find a way to display my image with a new center, it only works if self._degrees
is 0.
If I apply another translate
to the QTransform object and self._degrees
is not 0, the image is never centered where I'd expect it to be.
Could somebody point me to the right direction, please?
Edit
PS: I forgot to mention that the new center's coordinate are based on the original image's coordinates, not on the rotated image's ones.
Upvotes: 0
Views: 3581
Reputation: 6584
You should perform the translation before the rotation (a QTransform
modifies the coordinates system).
For example: def paintEvent(self, event): rect = QRect( 0, 0 , 20, 10 )
self._center = QPoint( 50, 50 )
t = QTransform()
#Do not forget to substract the rect size to center it on self._center
t.translate (self._center.x() -rect.width() / 2, self._center.y() -rect.height() / 2)
t.translate(rect.width() / 2, rect.height() / 2)
t.rotate(45.0)
t.translate(-rect.width() / 2, -rect.height() / 2)
p = QPainter(self)
p.save()
#Paint original rect
p.setBrush( QBrush( Qt.black ) )
p.drawRect( rect )
# Paint rect with transformation
p.setTransform(t)
p.setBrush( QBrush( Qt.red ) )
p.drawRect( rect )
# Paint self._center
p.restore()
p.setPen( QPen( Qt.black, 5 ) )
p.drawPoint( self._center )
p.end()
Upvotes: 1
Reputation: 37512
If I understand you correctly self._center
contains information where center of rotation should be placed. In such case it is quite simple to do:
def paintEvent(self, event):
t = QtGui.QTransform()
s = self._pm.size() # self._pm is the image to rotate.
t.translate(-self._center.x, -self._center.y)
t.rotate(self._degrees)
t.translate(self._center.x, self._center.y)
p = QtGui.QPainter(self)
p.setTransform(t)
p.drawPixmap(0, 0, self._pm)
p.end()
Remember that setTransform
set transformation of painters coordinate system.
Upvotes: 0