I'm trying to make the OF window get resized proportionally maintaining the same ratio between width
and height
of the window.
For example, if you created a window with 400x300
dimensions and if you stretch the width to 800
, then the height will automatically be stretched to 600
even though you only stretched the window horizontally.
Anyways, in order to implement this feature, I needed to use ofSetWindowShape()
inside windowResized()
listener.
I could quickly prototype this on MacOS X and it worked very well.
Here's 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 on Ubuntu, the app freezes as soon as I resize the window. It seems ofSetWindowShape()
calls windowResized()
listener and therefore it goes into an infinite loop.
(windowResized -> ofSetWindowShape -> windowResized -> ofSetWindowShape....)
How can I change the code so it can also work on Ubuntu without the problem? Any advice or guidance would be greatly appreciated!
P.S: I would also appreciate if Linux users can confirm the app freezing.