MeasureString in sharpDX

We are developing an application to connect to window 8 using SharpDX . Now we have to declare a rowset within the Rectangle . To do this, we are trying to figure out the width and height of the font using SharpDX.DrawingSizeF . eg:

 Windows.Graphics g; Model.Font font; DrawingSizeF size = g.MeasureString(quote, font.Font, new DrawingSizeF(font.Width, font.Height)); 

we are trying to figure out MeasureString using Windows.Graphics . Is it possible? Or is there any other way to get MeasureString in SharpDX or using Direct2D ?

+4
source share
2 answers

I have code from this post that works well for me. What I came across, after some of my own actions, is this:

 public System.Drawing.SizeF MeasureString(string Message, DXFonts.DXFont Font, float Width, ContentAlignment Align) { SharpDX.DirectWrite.TextFormat textFormat = Font.GetFormat(Align); SharpDX.DirectWrite.TextLayout layout = new SharpDX.DirectWrite.TextLayout(DXManager.WriteFactory, Message, textFormat, Width, textFormat.FontSize); return new System.Drawing.SizeF(layout.Metrics.Width, layout.Metrics.Height); } 

If you insert text, font, suggested width and alignment, it exports the size of the rectangle to hold the text. Of course, you are looking for height, but this includes width, since text rarely fills the entire space.

Note. As suggested by the commentator, there should actually be the following code for Dispose () resources:

 public System.Drawing.SizeF MeasureString(string Message, DXFonts.DXFont Font, float Width, ContentAlignment Align) { SharpDX.DirectWrite.TextFormat textFormat = Font.GetFormat(Align); SharpDX.DirectWrite.TextLayout layout = new SharpDX.DirectWrite.TextLayout(DXManager.WriteFactory, Message, textFormat, Width, textFormat.FontSize); textFormat.Dispose(); // IMPORTANT! If you don't dispose your SharpDX resources, your program will crash after a while. return new System.Drawing.SizeF(layout.Metrics.Width, layout.Metrics.Height); } 
+1
source

I modified the first answer to eliminate the restriction of lack of access to DXFont in VB.net:

 Public Function MeasureString(Message As String, textFormat As SharpDX.DirectWrite.TextFormat, Width As Single, Align As ContentAlignment) As System.Drawing.SizeF Dim layout As SharpDX.DirectWrite.TextLayout = New SharpDX.DirectWrite.TextLayout(New DirectWrite.Factory, Message, textFormat, Width, textFormat.FontSize) Return New System.Drawing.SizeF(layout.Metrics.Width, layout.Metrics.Height) End Function 
0
source

Source: https://habr.com/ru/post/1437157/


All Articles