Display size calculations problem

I came accross a problem while making my current project. The concept would be to create a black square on a white background of 1000 by 1000 pixels, but have it be at the center of the screen. Taking into account the fact that this should work on different sizes of screens, I tried this:

int fartop=displayHeight-1000/2;
int farleft=displayWidth-1000/2;

void setup(){
  size(1000,1000); //I think this doesn't matter since I put the project on full screen one line later
  fullScreen();
  background(255);
}

void draw(){
  fill(0);
  rect(farleft, fartop, 1000, 1000);
}

However, the result I got was this:


My screen size is 1920 by 1080, so logically, farleft should be equal 460 and fartop should be equal 40. But after checking the variables’ values directly, I realised they were both equal -500.
I then tried defining the variables as such to understand the problem:

int fartop=displayHeight-1000;
int farleft=displayWidth-1000;

And after this, both variables were equal -1000.
When defining the variables as just my display sizes, it gave the correct screen resolution I’m using, but as soon as I start affecting the variable, it ignores it for some reason.
I’ve also tried the following:

int fartop=displayHeight;
int farleft=displayWidth;

void setup(){
  size(1000,1000);
  fullScreen();
  background(255);
  fartop=fartop-1000/2;
  farleft=farleft-1000/2;
}

But the result is the same. I have no idea what could be causing this, and I’d appreciate some insight grealy. Thank you in advance.

Three points:

  • The position 0,0 is in the upper left corner and not in the center

  • Maybe displayWidth and displayHeight get defined only after size() or fullscreen()? So is width and height by the way.

  • I wouldn’t use size and fullscreen together. Just use the latter (one or the other).

2 Likes

Thank you for the answer!

Thank you for the reminder! That is why I substract the size of the square then divide the remaining space by two, in order to get the same space on both sides!
After modifying my code as such:

int fartop=0;
int farleft=0;

void setup(){
  fullScreen();
  background(255);
  fartop=(displayHeight-1000)/2;
  farleft=(displayWidth-1000)/2;
}

void draw(){
  fill(0);
  rect(farleft, fartop, 1000, 1000);
}

It gave me the awaited result! Much thanks for the help!

Hello @Jellyfish_Grave,

Another way:

void setup()
  {
  println(displayWidth, displayHeight); //print before fullscreen()
  fullScreen();
  background(255);
  println(displayWidth, displayHeight); //print after fullscreen()
  }

void draw()
  {
  fill(0);
  translate(displayWidth/2, displayHeight/2);
  rectMode(CENTER);
  rect(0, 0, 1000, 1000);
  }

I encourage you to peruse the tutorials, references and examples here:

:)

1 Like

I see, thank you! This does clear some things up, I appreciate the help given!
I will check this link out, thank you for the ressource.