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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
VulpesRank #55 · 29.2K reputationPosted Jul 8, 2011, 2:15 AM EDT
Zoran HorvatRank #792 · 2.9K reputationPosted Jul 8, 2011, 2:16 AM EDT
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
Ananth prasath24 reputationPosted Jul 8, 2011, 2:16 AM EDT
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