Click here to Skip to main content
15,891,721 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi. I'm currently struggling trying to find a formula for centering a text based on any coordinates of a rectangle (not just a fixed set). I'm currently using this libraries (as I am restricted by the project):

#include <iostream>
#include <cstring>
#include <fstream>
#include <graphics.h>
#include <winbgim.h>

What I have tried:

I tried different methods, mostly tring to find some fixed variabiles for some fixed coordinates (such as rectangle(x1+98, x2+91, x3+98, x4+13), etc.). Also, I tried using the textwidth function (x1/2-textwidth/2) but I couldn't find a method.
Posted
Updated 15-Jan-18 1:51am

You have to determine the size of the text in pixels and calculate the top and left positions for centering in a given rectangle:
C++
int text_w = textwidth(textstring);
int text_h = textheight(textstring);
int rect_w = rect_right - rect_left;
int rect_h = rect_bottom - rect_top;
int x = rect_left + (rect_w - text_w) / 2;
int y = rect_top + (rect_h - text_h) / 2;
rectangle(rect_left, rect_top, rect_right, rect_bottom);
outtextxy(x, y, textstring);
 
Share this answer
 
v2
Comments
CPallini 15-Jan-18 8:27am    
I guess it should be
x = (rect_w - text_w) / 2 + rect_left;
and so on.
Jochen Arndt 15-Jan-18 8:31am    
Oops.
Thank you Carlo.
Of course textwidth (as well as textheight) is the way to go. If W is the rectangle width and w is the text width the text should be placed at x = X + (W-w)/2 (where X is the rectangle horizontal position and x is the text horizontal position).
There could be some additional offset, but you should be able to determine it experimentally.
 
Share this answer
 
Comments
Member 13623637 15-Jan-18 8:22am    
int gd = DETECT, gm;
    initgraph(&gd, &gm, NULL);
    int rect_left = 123, rect_top = 17 , rect_right = 183 , rect_bottom = 37 ;
    int text_w = textwidth("FII");
    int text_h = textheight("FII");
    int rect_w = rect_right - rect_left;
    int rect_h = rect_bottom - rect_top;
    int x = (rect_w - text_w) / 2;
    int y = (rect_h - text_h) / 2;
    rectangle(rect_left, rect_top, rect_right, rect_bottom);
    outtextxy(x, y, "FII");
    getch();
    closegraph();


So I tried Jochen Arndt code and this shows up: image. Also tried adding
x = rect_w + ((rect_w - text_w) / 2)
but all it does is getting closer to the rectangle: image

Also, CPallini, how can I find out the horizontal position? Is it an operation between the rect_top and rect_bottom? Sorry for bothering you guys but I'm kinda new to this.
CPallini 15-Jan-18 8:30am    
If you use Jochen code then add rect_left, to x: namely
x = rect_left + (rect_w - text_w)/2;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900