如何将文本居中放置在矩形中? [英] How can I center text in a rectangle?

查看:196
本文介绍了如何将文本居中放置在矩形中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。我目前正在努力寻找一个基于矩形的任何坐标(不仅仅是固定的集合)来居中文本的公式。我目前正在使用这个库(因为我受项目限制):



#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 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.


这篇关于如何将文本居中放置在矩形中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆