问题
I'm using openframeworks (which renders through OpenGL) and I'm trying to rotate an image from it's center.
I know I should use ofRotate()
and ofTranslate()
but I haven't managed to figure it out by myself. Here's what I've tried so far:
ofPushMatrix();
ofRotate(ofRandom(10),0.0,0.0,1.0);
leafImg.draw(100,100);
ofPopMatrix();
回答1:
Without doing too much math you can use a nested coordinate system offset the image so that when you rotate, you rotate from the centre. In short you'll be doing this:
- Move the coordinate system to centre of the image
- Rotate from there
- Within that coordinate system do one level deeper and translate back by half the image size so you're offset back to '0,0'
In code this would be:
ofPushMatrix();
ofTranslate(leafImg.width/2, leafImg.height/2, 0);//move pivot to centre
ofRotate(ofGetFrameNum() * .01, 0, 0, 1);//rotate from centre
ofPushMatrix();
leafImg.draw(-leafImg.width/2,-leafImg.height/2);//move back by the centre offset
ofPopMatrix();
ofPopMatrix();
I've used the indenting to make it more obvious how the coordinate systems nest.
It's the same as:
ofPushMatrix();
ofTranslate(leafImg.width/2, leafImg.height/2, 0);//move pivot to centre
ofRotate(ofGetFrameNum() * .01, 0, 0, 1);//rotate from centre
ofPushMatrix();
ofTranslate(-leafImg.width/2,-leafImg.height/2,0);//move back by the centre offset
leafImg.draw(0,0);
ofPopMatrix();
ofPopMatrix();
It's fairly simple to rotate to centre as you can see. In your spare time try to work out how to rotate against an arbitrary point.
Behind the scenes there's a bit of linear algebra going on, but push/pop matrix calls basically handle the nitty gritty matrix multiplications for you. Still you need to understand and practice working with pushMatrix/popMatrix calls. Even though this is for Processing, the principle is exactly the same and the syntax is very similar, so I recommend this article: 2D Transformations
来源:https://stackoverflow.com/questions/12516550/openframeworks-rotate-an-image-from-its-center-through-opengl-calls