Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. RectangleF to and back from string?

RectangleF to and back from string?

Scheduled Pinned Locked Moved C#
tutorialquestion
8 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • C Offline
    C Offline
    Chesnokov Yuriy
    wrote on last edited by
    #1

    How to convert RectangleF to and back from string representation in a similar way as Int32.Parse()?

    Чесноков

    L P D 3 Replies Last reply
    0
    • C Chesnokov Yuriy

      How to convert RectangleF to and back from string representation in a similar way as Int32.Parse()?

      Чесноков

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      You could use this[^] to convert it to a string, but you would need to write your own method to reconvert from strings to the structure.

      The best things in life are not things.

      1 Reply Last reply
      0
      • C Chesnokov Yuriy

        How to convert RectangleF to and back from string representation in a similar way as Int32.Parse()?

        Чесноков

        P Offline
        P Offline
        Pete OHanlon
        wrote on last edited by
        #3

        The following class could be used (with a bit of beefing up) to convert back from a string representation:

        namespace ParseRectangleF
        {
        using System;
        using System.Drawing;

        public static class ParserUtility
        {
        /// <summary>
        /// Parse the input string into a valid RectangleF format.
        /// </summary>
        /// <param name="value">The string to convert into the RectangleF format.</param>
        /// <returns>The parsed rectangle.</returns>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null or an empty string.</exception>
        /// <exception cref="ArgumentException">Thrown if the input string is not in a valid format.</exception>
        public static RectangleF Parse(string value)
        {
        if (string.IsNullOrEmpty(value))
        throw new ArgumentNullException(value);
        // Remove any { or } characters, as generated by the ToString() method.
        value = value.Replace("{", string.Empty).Replace("}", string.Empty).Replace(" ", string.Empty);
        var rectangle = new RectangleF();
        rectangle.X = GetValue(value, "X=");
        rectangle.Y = GetValue(value, "Y=");
        rectangle.Width = GetValue(value, "Width=");
        rectangle.Height = GetValue(value, "Height=");
        return rectangle;
        }

        /// <summary>
        /// Get the relevant value out of the input text and convert it into
        /// a float.
        /// </summary>
        /// <param name="value">The input string to retrieve the value from.</param>
        /// <param name="key">The key used to retrieve the value.</param>
        /// <returns>The value retrieved from the text.</returns>
        /// <exception cref="ArgumentException">Thrown if the input string is not in a valid format.</exception>
        private static float GetValue(string value, string key)
        {
          if (!key.EndsWith("="))
          {
            key += "=";
          }
          int ordinal = value.IndexOf(key, StringComparison.CurrentCultureIgnoreCase);
          int length = ordinal + key.Length;
          int commaPos = value.IndexOf(",", length);
          if (commaPos < length)
          {
            commaPos = value.Length;
          }
          string text = value.Substring(length, commaPos - length);
        
          float output;
          if (!float.TryParse(text, out output))
          {
            throw new ArgumentException(
              string.Format("The input {0} is not the right format for Parse. It should be fo
        
        C 1 Reply Last reply
        0
        • P Pete OHanlon

          The following class could be used (with a bit of beefing up) to convert back from a string representation:

          namespace ParseRectangleF
          {
          using System;
          using System.Drawing;

          public static class ParserUtility
          {
          /// <summary>
          /// Parse the input string into a valid RectangleF format.
          /// </summary>
          /// <param name="value">The string to convert into the RectangleF format.</param>
          /// <returns>The parsed rectangle.</returns>
          /// <exception cref="ArgumentNullException">Thrown if <paramref name="value"/> is null or an empty string.</exception>
          /// <exception cref="ArgumentException">Thrown if the input string is not in a valid format.</exception>
          public static RectangleF Parse(string value)
          {
          if (string.IsNullOrEmpty(value))
          throw new ArgumentNullException(value);
          // Remove any { or } characters, as generated by the ToString() method.
          value = value.Replace("{", string.Empty).Replace("}", string.Empty).Replace(" ", string.Empty);
          var rectangle = new RectangleF();
          rectangle.X = GetValue(value, "X=");
          rectangle.Y = GetValue(value, "Y=");
          rectangle.Width = GetValue(value, "Width=");
          rectangle.Height = GetValue(value, "Height=");
          return rectangle;
          }

          /// <summary>
          /// Get the relevant value out of the input text and convert it into
          /// a float.
          /// </summary>
          /// <param name="value">The input string to retrieve the value from.</param>
          /// <param name="key">The key used to retrieve the value.</param>
          /// <returns>The value retrieved from the text.</returns>
          /// <exception cref="ArgumentException">Thrown if the input string is not in a valid format.</exception>
          private static float GetValue(string value, string key)
          {
            if (!key.EndsWith("="))
            {
              key += "=";
            }
            int ordinal = value.IndexOf(key, StringComparison.CurrentCultureIgnoreCase);
            int length = ordinal + key.Length;
            int commaPos = value.IndexOf(",", length);
            if (commaPos < length)
            {
              commaPos = value.Length;
            }
            string text = value.Substring(length, commaPos - length);
          
            float output;
            if (!float.TryParse(text, out output))
            {
              throw new ArgumentException(
                string.Format("The input {0} is not the right format for Parse. It should be fo
          
          C Offline
          C Offline
          Chesnokov Yuriy
          wrote on last edited by
          #4

          Thank you for the code, why the same can not be executed with System.Drawing.RectangleConverter. It worked with Rectangle but failed with RectangleF

          Чесноков

          P 1 Reply Last reply
          0
          • C Chesnokov Yuriy

            Thank you for the code, why the same can not be executed with System.Drawing.RectangleConverter. It worked with Rectangle but failed with RectangleF

            Чесноков

            P Offline
            P Offline
            Pete OHanlon
            wrote on last edited by
            #5

            You can achieve the same effect with the RectangleConverter, if you use the following code:

            RectangleF rect = (RectangleF)(Rectangle)conv.ConvertFromInvariantString("10,10,100,300");

            The ConvertFrom methods return an object, so you need to cast it into a Rectangle first before you can cast it into a RectangleF. It's a bit backwards, I know, but it does work.

            Forgive your enemies - it messes with their heads

            My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

            C 1 Reply Last reply
            0
            • P Pete OHanlon

              You can achieve the same effect with the RectangleConverter, if you use the following code:

              RectangleF rect = (RectangleF)(Rectangle)conv.ConvertFromInvariantString("10,10,100,300");

              The ConvertFrom methods return an object, so you need to cast it into a Rectangle first before you can cast it into a RectangleF. It's a bit backwards, I know, but it does work.

              Forgive your enemies - it messes with their heads

              My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

              C Offline
              C Offline
              Chesnokov Yuriy
              wrote on last edited by
              #6

              the values in RectangleF are fractional

              Чесноков

              P 1 Reply Last reply
              0
              • C Chesnokov Yuriy

                the values in RectangleF are fractional

                Чесноков

                P Offline
                P Offline
                Pete OHanlon
                wrote on last edited by
                #7

                Chesnokov Yuriy wrote:

                the values in RectangleF are fractional

                I know. I'm just showing what happens, hence the reason you have to cast it.

                Forgive your enemies - it messes with their heads

                My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility

                1 Reply Last reply
                0
                • C Chesnokov Yuriy

                  How to convert RectangleF to and back from string representation in a similar way as Int32.Parse()?

                  Чесноков

                  D Offline
                  D Offline
                  DaveyM69
                  wrote on last edited by
                  #8

                  The following two methods are based on the ConvertFrom and ConvertTo methods of the RectangleConverter class, tweaked for RectangleF and other bits removed as we know the types required in advance.

                  using System;
                  using System.ComponentModel;
                  using System.Drawing;
                  using System.Globalization;

                  public class RectangleFUtilities
                  {
                  public static bool TryParse(string s, out RectangleF result)
                  {
                  if (string.IsNullOrEmpty(s))
                  {
                  result = RectangleF.Empty;
                  return false;
                  }
                  s = s.Trim();
                  if (s.Length == 0)
                  {
                  result = RectangleF.Empty;
                  return false;
                  }
                  CultureInfo culture = CultureInfo.CurrentCulture;
                  string[] strArray = s.Split(new char[] { culture.TextInfo.ListSeparator[0] });
                  float[] numArray = new float[strArray.Length];
                  for (int i = 0; i < numArray.Length; i++)
                  {
                  if (!float.TryParse(strArray[i], out numArray[i]))
                  {
                  result = RectangleF.Empty;
                  return false;
                  }
                  }
                  if (numArray.Length != 4)
                  {
                  result = RectangleF.Empty;
                  return false;
                  }
                  result = new RectangleF(numArray[0], numArray[1], numArray[2], numArray[3]);
                  return true;
                  }

                  public static string ToString(RectangleF rectangleF)
                  {
                      CultureInfo culture = CultureInfo.CurrentCulture;
                      string separator = culture.TextInfo.ListSeparator + " ";
                      TypeConverter converter = TypeDescriptor.GetConverter(typeof(float));
                      string\[\] strArray = new string\[4\];
                      int num = 0;
                      strArray\[num++\] = converter.ConvertToString(null, culture, rectangleF.X);
                      strArray\[num++\] = converter.ConvertToString(null, culture, rectangleF.Y);
                      strArray\[num++\] = converter.ConvertToString(null, culture, rectangleF.Width);
                      strArray\[num++\] = converter.ConvertToString(null, culture, rectangleF.Height);
                      return string.Join(separator, strArray);
                  }
                  

                  }

                  Dave
                  Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
                  BTW, in software,

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups