Skip to content

Instantly share code, notes, and snippets.

@rsodre
Created March 23, 2017 14:27
Show Gist options
  • Save rsodre/d6ccaf498da64fd4b985f70598f1cd23 to your computer and use it in GitHub Desktop.
Save rsodre/d6ccaf498da64fd4b985f70598f1cd23 to your computer and use it in GitHub Desktop.
Transform matrix to fit any rect into any other rect. For OpenFrameworks (or anything else, really)
#pragma once
#include "ofMain.h"
void transformToFit( ofRectangle src, ofRectangle dst, bool upscale=true ) {
// Scale
float scaleX = ( dst.width / src.width );
float scaleY = ( dst.height / src.height );
float sc = ( scaleX < scaleY ? scaleX : scaleY );
if ( ! upscale )
sc = ofClamp( sc, 0.0f, 1.0f );
// Position (scaled)
float gapX = floorf( (src.width * sc) < dst.width ? ( dst.width - (src.width * sc) ) * 0.5f : 0.0 ) ;
float gapY = floorf( (src.height * sc) < dst.height ? ( dst.height - (src.height * sc) ) * 0.5f : 0.0 ) ;
// Transform!!
glTranslatef( dst.x + gapX, dst.y + gapY, 0 );
glScalef( sc, sc, sc );
glTranslatef( -src.x, -src.y, 0 );
}
void transformToFit( ofPoint src, ofPoint dst, bool upscale=true ) {
transformToFit( ofRectangle(0, 0, src.x, src.y), ofRectangle(0, 0, dst.x, dst.y), upscale );
}
void transformToFit( ofPoint src, ofRectangle dst, bool upscale=true ) {
transformToFit( ofRectangle(0, 0, src.x, src.y), dst, upscale );
}
void transformToFit( int srcWidth, int srcHeight, ofRectangle dst, bool upscale=true ) {
transformToFit( ofRectangle(0, 0, srcWidth, srcHeight), dst, upscale );
}
void transformToFit( int srcWidth, int srcHeight, int dstWidth, int dstHeight, bool upscale=true ) {
transformToFit( ofRectangle(0, 0, srcWidth, srcHeight), ofRectangle(0, 0, dstWidth, dstHeight), upscale );
}
void transformToFit( ofImage src, ofRectangle dst, bool upscale=true ) {
transformToFit( ofRectangle(0, 0, src.getWidth(), src.getHeight()), dst, upscale );
}
void transformToFit( ofFbo src, ofRectangle dst, bool upscale=true ) {
transformToFit( ofRectangle(0, 0, src.getWidth(), src.getHeight()), dst, upscale );
}
void transformToFit( ofImage src, ofImage dst, bool upscale=true ) {
transformToFit( ofRectangle(0, 0, src.getWidth(), src.getHeight()), ofRectangle(0, 0, dst.getWidth(), dst.getHeight()), upscale );
}
void transformToFit( ofImage src, ofFbo dst, bool upscale=true ) {
transformToFit( ofRectangle(0, 0, src.getWidth(), src.getHeight()), ofRectangle(0, 0, dst.getWidth(), dst.getHeight()), upscale );
}
void transformToFit( ofRectangle src, ofImage dst, bool upscale=true ) {
transformToFit( src, ofRectangle(0, 0, dst.getWidth(), dst.getHeight()), upscale );
}
void transformToFit( ofRectangle src, ofFbo dst, bool upscale=true ) {
transformToFit( src, ofRectangle(0, 0, dst.getWidth(), dst.getHeight()), upscale );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment