Openframeworks - rotate an image from its center through OpenGL calls

匆匆过客 提交于 2019-12-13 06:26:59

问题


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:

  1. Move the coordinate system to centre of the image
  2. Rotate from there
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!