如何以编程方式测量 ASP.NET 中的字符串像素宽度?

发布于 2024-10-30 20:02:26 字数 92 浏览 3 评论 0原文

如何获得字符串的大小?在 Windows 窗体中,这很简单,我只需使用图形对象,然后使用 MeasureString 函数。在 ASP.NET 中我不知道如何做到这一点。

How do you get the size of a string? In Windows Forms it's easy, I just use graphics object and then MeasureString function. In ASP.NET I'm not sure how to do this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

拔了角的鹿 2024-11-06 20:02:27

您可以按如下所示对字符串使用 Length 属性:

http://www.dotnetperls.com/string-length

You can use the Length property on a string as follows:

http://www.dotnetperls.com/string-length

来世叙缘 2024-11-06 20:02:27

在服务器端这是完全不可能的事情(假设“ASP.NET”是指使用 ASP.NET 创建的网页)。 ASP.NET 输出 HTML,这是一种由客户端浏览器解释和呈现的标记语言。相同的 HTML 代码可以在不同的设备、不同的浏览器、使用不同的安装字体等上显示,从而导致显示效果截然不同。

您的 ASP.NET 站点在服务器上运行代码,不知道您的客户端使用哪种字体、什么分辨率等。实现这一点的唯一理论上方法是运行客户端代码(例如JavaScript、Silverlight、Flash……)以向服务器报告。然而,这将是相当困难的。

一般来说,你不需要那样做,你也不想那样做。

It is a completely impossible thing to do on server side (assuming by “ASP.NET”, you mean web pages created using ASP.NET”). ASP.NET outputs HTML, which is a markup language interpreted and rendered by a browser on the client. The same HTML code can be displayed on various devices, in various browsers, using various installed fonts, etc., resulting in grossly differing display.

Your ASP.NET site, running code on the server, does not know which font, what resolution, etc. your client uses. The only theoretical way this could be done would be to run client-side code (e.g. JavaScript, Silverlight, Flash, …) to report back to the server. However, this would be quite difficult.

Generally, you do not need to do that, you do not want to do that.

飘然心甜 2024-11-06 20:02:27

@Tom Gullen,@asawyer

这是我的临时解决方案,目前似乎有效。仅供参考,我的项目恰好是一个 ASP.NET 应用程序,其中涉及许多动态接口(那是另一个故事)。无论如何,我的短期解决方案发布在下面。当用户单击文本框(自定义组合框)时,我实际上正在使用 modalpopupextender (带有列表框)。 ajax 组合框工作得不太好,特别是当组合框很多并且您无法在下拉列表上设置下拉宽度时。

Friend Function ResizePopup(ByVal sender As Object, ByVal standardwidth As Integer) As Integer
    Dim lst As ListBox = CType(sender, ListBox)
    Dim itemlength As Single = 0

    'get longest string length
    For Each item As ListItem In lst.Items
        If item.Text.Length > itemlength Then
            itemlength = item.Text.Length
        End If
    Next

    'set a general multiplier
    Dim newWidth As Integer = itemlength * 7

    'compare to width of control, if larger, then use value else return control width
    If newWidth > standardwidth Then
        Return newWidth
    Else
        Return standardwidth
    End If

End Function

@Tom Gullen, @asawyer

This is my temporary solution and it seems to be working for now. fyi, my project happened to be a asp.net application with many dynamic interfaces involved in it (thats another story). At anyrate my short term solution is posted below. Im acually using a modalpopupextender (with listbox) on the fly when the user clicks a textbox (custom combobox). The ajax combobox doesn't work very well especially when there is many of them and you can't set the dropdown width on a dropdownlist.

Friend Function ResizePopup(ByVal sender As Object, ByVal standardwidth As Integer) As Integer
    Dim lst As ListBox = CType(sender, ListBox)
    Dim itemlength As Single = 0

    'get longest string length
    For Each item As ListItem In lst.Items
        If item.Text.Length > itemlength Then
            itemlength = item.Text.Length
        End If
    Next

    'set a general multiplier
    Dim newWidth As Integer = itemlength * 7

    'compare to width of control, if larger, then use value else return control width
    If newWidth > standardwidth Then
        Return newWidth
    Else
        Return standardwidth
    End If

End Function
云柯 2024-11-06 20:02:27

@Eystein Bye 的解决方案,通过使用变得稍微干净一些:

using (Bitmap objBitmap = new Bitmap(5000, 200))
{
     using (Graphics objGraphics = Graphics.FromImage(objBitmap))
     {
          SizeF stringSize = objGraphics.MeasureString(txt, new Font("Arial", 12));
          return stringSize.Width;
     }
}

@Eystein Bye's solution, made slightly cleaner with usings:

using (Bitmap objBitmap = new Bitmap(5000, 200))
{
     using (Graphics objGraphics = Graphics.FromImage(objBitmap))
     {
          SizeF stringSize = objGraphics.MeasureString(txt, new Font("Arial", 12));
          return stringSize.Width;
     }
}
椒妓 2024-11-06 20:02:26

正如汤姆·古伦所说。您只需创建一个位图并整理字符串即可。我有这个代码用来查找像素的宽度/长度。只需更改字体和大小即可。

// Bitmap class namespace:
using System.Drawing;

...

private float GetWidthOfString(string str)
{
    Bitmap objBitmap = default(Bitmap);
    Graphics objGraphics = default(Graphics);

    objBitmap = new Bitmap(500, 200);
    objGraphics = Graphics.FromImage(objBitmap);

    SizeF stringSize = objGraphics.MeasureString(str, new Font("Arial", 12));

    objBitmap.Dispose();
    objGraphics.Dispose();
    return stringSize.Width;
}

只是想举个例子。

Like Tom Gullen is saying. You can just create a bitmap and messure the string. I have this code I use to find the width/length in pixel. Just change the font and size.

// Bitmap class namespace:
using System.Drawing;

...

private float GetWidthOfString(string str)
{
    Bitmap objBitmap = default(Bitmap);
    Graphics objGraphics = default(Graphics);

    objBitmap = new Bitmap(500, 200);
    objGraphics = Graphics.FromImage(objBitmap);

    SizeF stringSize = objGraphics.MeasureString(str, new Font("Arial", 12));

    objBitmap.Dispose();
    objGraphics.Dispose();
    return stringSize.Width;
}

Just wanted to show an example.

风柔一江水 2024-11-06 20:02:26

如果您使用的是 JQuery,请参阅此答案

Determine Pixel Length of String in Javascript /jQuery?

我相信如果没有的话你也可以做类似的事情。

If you are using JQuery, see this answer

Determine Pixel Length of String in Javascript/jQuery?

I'm sure if not you can work something similar.

鸠魁 2024-11-06 20:02:26

String.Length

返回字符串的长度(字符数)。

C#

string MyString = "Stack Overflow String";
Response.Write(MyString.Length);

VB.net

Dim MyString As String = "Stack Overflow String"
Response.Write(MyString.Length);

MSDN 参考

http://msdn.microsoft.com/en-us/library/system.string.length.aspx

服务器端物理字符串大小

不知道为什么这么多人
显然决心提出这样的想法:在服务器端做这个“完全不可能”,但事实并非如此。您只需要一点创意,并愿意进行大量测试。

据我所知,没有本地函数可以测量字符串的像素尺寸。您可以通过以下方式来实现。请注意,您需要了解:

  • 字体系列
  • 字体大小
  • 容器尺寸(用于文本换行时)
  • 任何其他 CSS 规则(例如字间距)都会使计算更加不准确且更加复杂。如果准确性很重要,请尝试避免它。

1.将其渲染为图像并测量图像尺寸

将文本绘制为位图,然后测量它。这应该是相当准确的。

2.使用固定宽度字体

如果您使用固定宽度字体并且文本不换行,则只需将其宽度乘以字符数即可。

3.粗略估计

您可以通过选择一些任意字符宽度数字并将其乘以总字符数来对非固定宽度字体进行相当粗略的估计。取决于你想要多准确。

String.Length

Returns the length of the string (number of characters).

C#

string MyString = "Stack Overflow String";
Response.Write(MyString.Length);

VB.net

Dim MyString As String = "Stack Overflow String"
Response.Write(MyString.Length);

MSDN Reference

http://msdn.microsoft.com/en-us/library/system.string.length.aspx

Physical String Size Serverside

I'm not sure why so many people are
apparently determined to put forward the idea that it is 'flat out impossible' to do this server side, it isn't. You just need to be a little bit creative, and be willing to do a lot of testing.

There is no native function I know of to measure the pixel dimensions of a string. You can achieve it in the following ways. Note you need to know:

  • The font family
  • Font size
  • Container dimensions (for when the text wraps lines)
  • Any other CSS rules such as word spacing are going to make the calculation a lot less accurate and more complex. Try and avoid it if accuracy is important.

1. Render it to an image and measure image size

Draw the text to a bitmap, and then measure it. This should be reasonably exact.

2. Use a fixed width font

If you are using a fixed width font and the text doesn't wrap, you can simply multiply its width by the number of characters.

3. Rough estimation

You could get a reasonably rough estimation on non fixed width fonts by picking some arbitrary character width number and multiplying it by total characters. Depends how accurate you want to be.

何以笙箫默 2024-11-06 20:02:26

以下方法将提供以给定字体呈现的字符串的大小:

private RectangleF sizeOfString(string text, Font font)
{
    GraphicsPath path = new GraphicsPath();
    path.AddString(text, font.FontFamily, (int)font.Style, font.Size, new Point(0, 0), new StringFormat());
    return path.GetBounds();
}

然后您可以使用它来获取宽度,如下所示

float width = sizeOfString("Hello World", someFont).Width;

The following method will provide the size of a String rendered in a given font:

private RectangleF sizeOfString(string text, Font font)
{
    GraphicsPath path = new GraphicsPath();
    path.AddString(text, font.FontFamily, (int)font.Style, font.Size, new Point(0, 0), new StringFormat());
    return path.GetBounds();
}

You could then use this to get the width as follows

float width = sizeOfString("Hello World", someFont).Width;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文