Determine Label Size based upon amount of text and font size in Winforms/C#

前端 未结 11 1760
半阙折子戏
半阙折子戏 2020-11-30 01:27

I\'d like to know if there\'s a better approach to this problem. I want to resize a label (vertically) to accomodate certain amount of text. My label has a fixed width (abou

11条回答
  •  清歌不尽
    2020-11-30 02:14

    System.Drawing.Graphics has a MeasureString method that you can use for this purpose. Use the overload that takes a string, a font, and an int "width" parameter; this last parameter specifies the maximum width allowed for the string - use the set width of your label for this parameter.

    MeasureString returns a SizeF object. Use the Height property of this returned object to set the height of your label.

    Note: to get a Graphics object for this purpose, you can call this.CreateGraphics.

提交回复
热议问题