I am trying to resize the OF window proportionally, keeping the same ratio between the width and height window.
For example, if you created a window with dimensions of 400x300 , and if you stretch the width to 800 , the height will automatically be stretched to 600 , although you only stretched this window horizontally.
In any case, to implement this function, I needed to use ofSetWindowShape() inside the windowResized() listener.
I could quickly prototype this on MacOS X, and it worked very well.
Here is the code:
ofApp.h
enum ScaleDir { //window scaling directions SCALE_DIR_HORIZONTAL, SCALE_DIR_VERTICAL, }; ScaleDir scaleDir; int windowWidth, windowHeight; //original window dimensions float widthScaled, heightScaled; //scaled window dimensions float windowScale; //scale amount (1.0 = original) bool bScaleDirFixed; //is direction fixed?
ofApp.cpp
//-------------------------------------------------------------- void ofApp::setup(){ windowWidth = ofGetWidth(); windowHeight = ofGetHeight(); windowScale = 1.0f; widthScaled = windowWidth * windowScale; heightScaled = windowHeight * windowScale; } //-------------------------------------------------------------- void ofApp::update(){ if (bScaleDirFixed) { bScaleDirFixed = false; } } //-------------------------------------------------------------- void ofApp::draw(){ ofSetColor(255, 0, 0); ofSetCircleResolution(50); ofDrawEllipse(widthScaled/2, heightScaled/2, widthScaled, heightScaled); //the ellipse will be scaled as the window gets resized. } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ if (!bScaleDirFixed) { int gapW = abs(widthScaled - w); int gapH = abs(heightScaled - h); if (gapW > gapH) scaleDir = SCALE_DIR_HORIZONTAL; else scaleDir = SCALE_DIR_VERTICAL; bScaleDirFixed = true; } float ratio; if (scaleDir == SCALE_DIR_HORIZONTAL) { ratio = static_cast<float>(windowHeight) / static_cast<float>(windowWidth); h = w * ratio; windowScale = static_cast<float>(w) / static_cast<float>(windowWidth); } else if (scaleDir == SCALE_DIR_VERTICAL) { ratio = static_cast<float>(windowWidth) / static_cast<float>(windowHeight); w = h * ratio; windowScale = static_cast<float>(h) / static_cast<float>(windowHeight); } widthScaled = windowWidth * windowScale; heightScaled = windowHeight * windowScale; ofSetWindowShape(widthScaled, heightScaled); }
However, if I run the same code in Ubuntu, the application freezes as soon as I resize the window. It seems that ofSetWindowShape() calls the windowResized() listener, and so it goes into an infinite loop.
(windowResized → ofSetWindowShape → windowResized → ofSetWindowShape ....)
How can I change the code so that it can work on Ubuntu without problems? Any advice or recommendations would be greatly appreciated!
PS: I would also appreciate if Linux users can confirm the application freezes.