Unable to center a rectangle

So I’ve been playing around with this library and I came across a noob-ish issue when it comes to graphics programming. what I wanted was to be able to center a rectangle of specified width and height regardless of the window size. I tried different ways of doing it, and I asked a bunch more less mathematically-illiterate people and I still cannot get it to be in the center.

#include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include <cinder/gl/draw.h>
#include <cinder/gl/wrapper.h>

using namespace ci;
using namespace ci::app;

class BasicApp : public App {
  public:

	void setup() override;
	void update() override;
	void draw() override;

	float Cx,Cy;
	float width,height;
	float TopLeftX, TopLeftY;
	float BottomRightX, BottomRightY;
	int screenWidth, screenHeight;
};

void BasicApp::setup()
{
	width = 50.0f;
	height = 50.0f;

	screenWidth = getWindowWidth();
	screenHeight = getWindowHeight();

	Cx = width / 2 + TopLeftX;
	Cy = height / 2 + TopLeftY;

	TopLeftX = screenWidth - width/2;
	BottomRightX = screenWidth + width/2;

	TopLeftY = screenHeight - height/2;
	BottomRightY = screenHeight + height/2;
}

void prepareSettings( BasicApp::Settings* settings ) {}
void BasicApp::update() {}

void BasicApp::draw()
{
	gl::drawStrokedRect(Rectf(TopLeftX,TopLeftY,BottomRightX,BottomRightY), 7.0);
}

CINDER_APP( BasicApp, RendererGl, prepareSettings )

Though when I compile and run the app, it just looks like this

I am on arch linux if that somehow matters.

void BasicApp::draw()
{
	gl::setMatricesWindow ( getWindowSize() );

	vec2 rectSize { 128.0f, 64.0f };
	vec2 center = app::getWindowCenter ( );

	gl::drawStrokedRect ( Rectf ( center - rectSize / 2.0f, center + rectSize / 2.0f ), 7.0f );
}
2 Likes

:open_mouth:
Thank you so much! :grinning:

Additional note: after the window has been created, Cinder will call setup() first and resize() next (if your application provides an override of this function). It will also call resize() every time the window size changes. If you only call getWindowWidth() in your setup(), you will not be notified of this.

So, either add a resize() function to update screenWidth and screenHeight, or just call getWindowWidth() in your draw() method.

~Paul

1 Like