Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find middle of a button on screen

Ok I’m coding a button. I have done the box collision and all of the other stuff.

The problem I’m having is putting text in the middle of the button. No matter what I try it doesn’t work :/ .

Please help I’m bad at math.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

x = 120, y = 120, w = 120, h = 50
Screen dimensions = 480, 240

Is there an equation for this? I tried everything.

The best thing I have so far is

Brain.Screen.printAt(x + (w / 2, y + (h / 2), false, "Bruh");
// printAt args int x, int y, bool opaque, const char *text

The problem with that is the it’s not at the exact center
is a little bit to the top right.

https://i.stack.imgur.com/vA2UQ.png

>Solution :

You can compute the center-point of the button easily enough:

const int buttonCenterX = x+(w/2);
const int buttonCenterY = y+(h/2);

… for the next step you’ll need to center the text around that point. If your GUI API doesn’t provide a way to center the text for you, you can calculate the appropriate x/y position by hand, assuming you know (or have a way to calculate) the pixel-width and pixel-height of the text:

const int textHeight = [text string's height, in pixels]
const int textWidth  = [text string's width, in pixels]
const int textLeft = buttonCenterX-(textWidth/2);
const int textTop  = buttonCenterY-(textHeight/2);
drawTextAt(textLeft, textTop, textString);  // assuming drawTextAt() draws starting at the top-left of the string
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading