我正在使用 openframeworks(通过 OpenGL 呈现)并且我正在尝试从它的中心旋转图像。
我知道我应该使用 ofRotate()
和 ofTranslate()
但我自己还没弄明白。到目前为止,这是我尝试过的:
ofPushMatrix();
ofRotate(ofRandom(10),0.0,0.0,1.0);
leafImg.draw(100,100);
ofPopMatrix();
最佳答案
无需做太多数学运算,您就可以使用嵌套坐标系来偏移图像,以便在旋转时从中心旋转。简而言之,您将这样做:
- 将坐标系移动到图像的中心
- 从那里开始旋转
- 在该坐标系内做更深一层并平移图像大小的一半,这样您就可以偏移回“0,0”
在代码中这将是:
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();
我使用缩进使坐标系的嵌套方式更加明显。
这等同于:
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();
如您所见,旋转到中心非常简单。在业余时间尝试找出如何针对任意点旋转。
在幕后有一些线性代数在进行,但是 push/pop 矩阵调用基本上会为您处理具体的矩阵乘法。您仍然需要了解和练习使用 pushMatrix/popMatrix 调用。虽然是Processing,但是原理完全一样,语法也很相似,所以推荐这篇文章:2D Transformations
关于c++ - Openframeworks - 通过 OpenGL 调用从中心旋转图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12516550/