首页 > 解决方案 > 如何根据子标签调整 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;

    }

容器预览结果:

从指定限制下降一行的用户控件

https://i.stack.imgur.com/iSI76.jpg

对于一条线

https://i.stack.imgur.com/zWFGR.jpg

在应用程序内部动态生成

在此处输入图像描述

标签: c#winformsuser-controlsresize

解决方案


推荐阅读