Can we convert a string into Rectangle Object? If possible how to do that?
Thanks.
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Ananth prasathPosted Jul 8, 2011, 6:16 AM
Public Sub MeasureStringMin(e As PaintEventArgs)
' Set up string.
Dim measureString As String = "Measure String"
Dim stringFont As New Font("Arial", 16)
' Measure string.
Dim stringSize As New SizeF()
stringSize = e.Graphics.MeasureString(measureString, stringFont)
' Draw rectangle representing size of string.
e.Graphics.DrawRectangle(New Pen(Color.Red, 1), 0F, 0F, _
stringSize.Width, stringSize.Height)
' Draw string to screen.
e.Graphics.DrawString(measureString, stringFont, Brushes.Black, _
New PointF(0, 0))
End Sub
Zoran HorvatPosted Jul 8, 2011, 6:16 AM
In particular cases yes, but then you must know exact format of the string and also it must be ensured that string format is not going to change in future. That is the reason why conversion from strings into objects is not recommended.
For example, rectangle can be converted to string and then back from string using this code:
Rectangle rect = new Rectangle(1, 2, 3, 4);
string strRect = string.Format("{0},{1},{2},{3}", rect.X, rect.Y, rect.Width, rect.Height);
// strRect at this point equals "1,2,3,4"
string[] parts = strRect.Split(new char[] { ',' });
int x = int.Parse(parts[0]);
int y = int.Parse(parts[1]);
int width = int.Parse(parts[2]);
int height = int.Parse(parts[3]);
Rectangle newRect = new Rectangle(x, y, width, height);
Point is that we have made both to string and from string conversions, so we're in charge of it and can guarantee that format will be such that Rectangle instance can be recreated from given string.
Zoran
VulpesPosted Jul 8, 2011, 6:15 AM