c# - 如何根据子标签调整 UserControl 的宽度和高度?
问题描述
我正在编写一个克隆消息应用程序。我有一个名为“Bubble”的用户控件,用作消息气泡。它的用户控件布局是这样的:
它只包含 lblMessage、lblTime 和 pictureBox。lblMessage 的 AutoSize 属性关闭,并且 Anchor 位于左上角。我的目标是根据内容调整或包装它。我可以使用此代码垂直调整大小。
void SetHeight()
{
//SizeF maxSize = new Size(500, int.MaxValue);
Graphics g = CreateGraphics();
SizeF size = g.MeasureString(lblMessage.Text, lblMessage.Font, lblMessage.Width);
lblMessage.Height = int.Parse(Math.Round(size.Height + 2, 0).ToString());
lblTime.Top= lblMessage.Bottom +10;
this.Height = lblTime.Bottom + 10;
}
我的结果是这样的:
我可以垂直调整大小,但不能同时水平调整。我垂直调整大小的方法是使用 lblMessage 的 width 属性作为限制大小。我想根据短文本的大小调整用户控件的大小。我想过为 MeasureString 创建一个 maxSize,但我无法让它工作。我试图找到一个在达到某个宽度值时从底线继续的函数。我期待着你的帮助。
我深入搜索了所有stackowerflow问题,但没有一个对我有用。
** Jimi评论后编辑
我试图将他的解决方案应用于我的项目。我不认为我做的一切都是正确的,但是有一点评论,至少对我有用的东西出现了。
private void Bubble_Paint(object sender, PaintEventArgs e)
{
float minimumWidth = lblTime.Width + pictureBox1.Width + 35;
float maximumWidth = 500;
string measureString = lblMessage.Text;
Font stringFont = new Font("Helvetica", 12.0F);
CharacterRange[] characterRanges = { new CharacterRange(0, measureString.Length) };
float layautWidth = maximumWidth - minimumWidth;
RectangleF layoutRect = new RectangleF(10, 6, layautWidth, this.Height);
StringFormat stringFormat = new StringFormat();
stringFormat.SetMeasurableCharacterRanges(characterRanges);
Color myColor = Color.FromArgb(211, 212, 212);
SolidBrush myBrush = new SolidBrush(myColor);
Region[] stringRegions = e.Graphics.MeasureCharacterRanges(measureString, stringFont, layoutRect, stringFormat);
RectangleF measureRect1 = stringRegions[0].GetBounds(e.Graphics);
//When I gave Rectangle to the DrawString, some last letter was truncated, so I used plain text printing until I got to the bottom line.
if (measureRect1.Height < 30)
e.Graphics.DrawString(measureString, stringFont, myBrush, 10, 6, stringFormat);
else e.Graphics.DrawString(measureString, stringFont, myBrush, measureRect1, stringFormat);
e.Graphics.DrawRectangle(new Pen(Color.Transparent, 0), Rectangle.Round(measureRect1));
this.Width = Convert.ToInt32(measureRect1.Width + minimumWidth);
lblTime.Top = Convert.ToInt32(measureRect1.Height) + 10;
this.Height = lblTime.Bottom + 10;
}
容器预览结果:
从指定限制下降一行的用户控件
对于一条线
在应用程序内部动态生成
解决方案
推荐阅读
- react-native - 将本机反应升级到 0.61 后出现“未创建任何 Firebase 应用程序”
- php - Bootstrap 4 Collapse 将所有项目一起打开和关闭
- sql - SQL 查询四舍五入到最接近的整数
- reactjs - React useMemo hook memoize 是否应该使用相同的依赖值重复调用?
- python-3.x - 如何实现BLE安全?
- r - 从多个数据帧连续子集行,直到满足条件
- python - PyCharm IDE 不会从 Crypto.Cipher 导入 AES 加载
- javascript - 从事件侦听器中分离事件目标的父 dom 时,不会对 Dom 元素进行垃圾收集
- laravel - POST http://127.0.0.1:8000/api/customers 422(无法处理的实体)
- python - 在 Windows 上的 vscode 中安装 psycopg2 时出错