如何将文本居中放置在矩形中? [英] How can I center text in a rectangle?
问题描述
您好。我目前正在努力寻找一个基于矩形的任何坐标(不仅仅是固定的集合)来居中文本的公式。我目前正在使用这个库(因为我受项目限制):
#include< iostream>
#include< ; cstring>
#include< fstream>
#include< graphics.h>
#include< winbgim.h> < br $> b $ b
我尝试了什么:
我尝试了不同的方法,主要是tring找到一些固定坐标的固定变量(如矩形(x1 + 98,x2 + 91,x3 + 98,x4 + 13)等)。另外,我尝试使用textwidth函数(x1 / 2-textwidth / 2)但我找不到方法。
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.
推荐答案
你必须确定大小以像素为单位的文本并计算在给定矩形中居中的顶部和左侧位置:
You have to determine the size of the text in pixels and calculate the top and left positions for centering in a given rectangle:
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);
当然textwidth
(以及如textheight
)是要走的路。如果W
是矩形宽度而w
是文字宽度文本应放在x = X +(Ww)/ 2
(其中X
是矩形水平位置和x
是文本水平位置)。
可能会有一些额外的偏移,但你应该能够通过实验确定它。
Of coursetextwidth
(as well astextheight
) is the way to go. IfW
is the rectangle width andw
is the text width the text should be placed atx = X + (W-w)/2
(whereX
is the rectangle horizontal position andx
is the text horizontal position).
There could be some additional offset, but you should be able to determine it experimentally.
这篇关于如何将文本居中放置在矩形中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!