Find longest initial substring which renders in a limited width
I have a long string, ex: "Please help me to solve thi开发者_如何转开发s problem." This string is so long to fit in a width of 100 pixels. I need to get a substring of this string and substring will fit in 100 pixels. Ex: substring "Please help me to sol" is fit in 100 pixels.
Please help me how to estimate a substring like this. Thanks.
My application is Win Forms and C#.
As usual, the Win32 API has a function designed exactly for this: GetTextExtentExPoint
P/invoke declaration: http://pinvoke.net/default.aspx/gdi32/GetTextExtentExPoint.html
Looks like you could use TextRenderer::MeasureText().
this should work... not really tested and no optimisations, though
var g = Graphics.FromImage(someimage); // or any from hwnd etc... should use your panel/whatever
var f = new Font("YOURFONT", 12f, FontStyle.Regular, GraphicsUnit.Pixel); // replace with your vals
var yourtext = "yourtextyourtextyourtextyourtextyourtext";
while (g.MeasureString(yourtext, f).Width > 100)
yourtext = yourtext.Remove(yourtext.Length - 2, 1);
If all you are looking for is a good estimate, you might first measure the width of a representative string to determine the average character width of your font once. A good representative might not be just the alphabet; you might look for a character frequency histogram to get a better average width.
string Representative = "abcdefghijklmnopqrstuvwxyz";
float CharacterWidth;
using(Bitmap b = new Bitmap(0, 0))
using(Graphics g = Graphics.FromImage(b))
using(Font f = /* some font definition */)
{
CharacterWidth = g.MeasureString(Representative, f).Width / Representative.Length;
}
Then use that to estimate how many characters would fit within N pixels.
string Text = ...
int DisplayWidth = 100;
int FitLength = Math.Min(Text.Length, (int)(DisplayWidth / CharacterWidth));
string FitText = Text.Substring(0, FitLength);
精彩评论