8,757
社区成员
发帖
与我相关
我的任务
分享
TextBlock measureTextBlock = new TextBlock();
_measureTextBlock.FontFamily = target.FontFamily;
_measureTextBlock.FontSize = target.FontSize;
_measureTextBlock.FontStretch = target.FontStretch;
_measureTextBlock.FontStyle = target.FontStyle;
_measureTextBlock.FontWeight = target.FontWeight;
_measureTextBlock.UseLayoutRounding = target.UseLayoutRounding;
_measureTextBlock.Text = text;
_measureTextBlock.Measure(new Size(double.MaxValue, double.MaxValue));
return new Size(_measureTextBlock.ActualWidth, _measureTextBlock.ActualHeight);
public class Helper
{
[DllImport("gdi32")]
private static extern bool GetTextExtentPoint32(IntPtr hdc, string lpString, int cbString, out Size lpSize);
[DllImport("gdi32")]
private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
[DllImport("gdi32")]
private static extern IntPtr DeleteObject(IntPtr hDC);
public static Size MeasureTextWidth(System.Drawing.Graphics graphics, string text, System.Drawing.Font textFont)
{
IntPtr hdc = graphics.GetHdc();
IntPtr hFont = textFont.ToHfont();
SelectObject(hdc, hFont);
Size size = new Size();
GetTextExtentPoint32(hdc, text, text.Length, out size);
graphics.ReleaseHdc();
DeleteObject(hFont);
return size;
}
}