Obtener líneas paralelas

Con esta función podrás calcular los puntos que representan una línea paralela a otra.

Hemos usado la clase Point3D que ya conoces de posts anteriores para representar los puntos finales de la línea a calcular.

A continuación indicamos el código de la función:

        /// <summary>

        /// Obtiene dos puntos que representan la paralela a una línea a una distancia

        /// </summary>

        /// <param name=”p1“>Punto inicial de la línea a controlar</param>

        /// <param name=”p2“>Punto final de la línea a controlar</param>

        /// <param name=”Offset“>Distancia para los puntos paralelos</param>

        /// <param name=”r1“>Por referencia. Punto paralelo a p1 en función de la distancia</param>

        /// <param name=”r2“>Por referencia. Punto paralelo a p2 en función de la distancia</param>

        /// <returns>True o False en función de si tiene éxito o no</returns>

        public static bool ParalelLine (Point3D p1, Point3D p2, double Offset, ref Point3D r1, ref Point3D r2)

        {

            try

            {

                double r = Math.Sqrt(Math.Pow(p1.x – p2.x, 2) + Math.Pow(p1.y – p2.y, 2));

                double StX = p1.x + Offset * (p2.y – p1.y) / r;

                double StY = p1.y + Offset * (p1.x – p2.x) / r;

                double EnX = p2.x + Offset * (p2.y – p1.y) / r;

                double EnY = p2.y + Offset * (p1.x – p2.x) / r;

                r1 = new Point3D(StX, StY, p1.z);

                r2 = new Point3D(EnX, EnY, p1.z);

                return true;

            }

            catch (Exception)

            {

                return false;

            }

        }

Como puedes ver recibe dos puntos que representan la recta principal y la distancia para establecer la línea paralela. Recibe dos parámetros de la clase Punto3D por referencia donde almacena el resultado. Si tiene éxito devuelve true, si hay errores devuelve false.

El valor del parámetro offset puede ser positivo o negativo, según su signo la paralela se generará a la derecha o la izquierda de la línea principal.

Para poner a prueba la función puedes crear un formulario parecido al siguiente:

En este formulario podrás entrar las coordenadas de la recta, el offset y la precisión para el resultado que se mostrará en las etiquetas R1 y R2.

A continuación el código para los eventos del formulario:

        private void txtPt1X_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPt1Y_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPt1Z_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPt2X_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPt2Y_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPt2Z_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtOffset_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), true, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void txtPrecision_KeyPress(object sender, KeyPressEventArgs e)

        {

            TextBox tb = sender as TextBox;

            string antT = tb.Text;

            string t = tb.Text;

            e.Handled = MyClase.OnlyNumbers(e.KeyChar.ToString(), false, ref t);

            if (antT != t)

            {

                tb.Text = t;

                tb.SelectionStart = tb.Text.Length;

            }

        }

 

        private void btCalcular_Click(object sender, EventArgs e)

        {

            this.lblMsg.Text = “Mensaje:”;

            this.lblR1X.Text = “0”;

            this.lblR1Y.Text = “0”;

            this.lblR1Z.Text = “0”;

            this.lblR2X.Text = “0”;

            this.lblR2Y.Text = “0”;

            this.lblR2Z.Text = “0”;

            // Verificar los valores en los TextBox

            // Si recibimos MinValue significa que no hay valor válido.

            if (!MyClase.IsNumeric(this.txtPt1X.Text) ||

                !MyClase.IsNumeric(this.txtPt1Y.Text) ||

                !MyClase.IsNumeric(this.txtPt1Z.Text) ||

                !MyClase.IsNumeric(this.txtPt2X.Text) ||

                !MyClase.IsNumeric(this.txtPt2Y.Text) ||

                !MyClase.IsNumeric(this.txtPt2Z.Text) ||

                !MyClase.IsNumeric(this.txtOffset.Text ) ||

                !MyClase.IsNumeric(this.txtPrecision.Text))

            {

                this.lblMsg.Text = “Formato erróneo en los números o en la precisión.”;

                return;

            }

            Point3D _pt1 = new Point3D(this.txtPt1X.ToDouble(), this.txtPt1Y.ToDouble(), this.txtPt1Z.ToDouble());

            Point3D _pt2 = new Point3D(this.txtPt2X.ToDouble(), this.txtPt2Y.ToDouble(), this.txtPt2Z.ToDouble());

            double _offset = this.txtOffset.ToDouble();

            int precision = this.txtPrecision.ToInteger();

            Point3D _r1 = new Point3D();

            Point3D _r2 = new Point3D();

            if (MyClase.ParalelLine(_pt1,_pt2,_offset,  ref _r1, ref _r2))

            {

                this.lblR1X.Text = MyClase.Trunk(_r1.x, Convert.ToInt16(precision)).ToString();

                this.lblR1Y.Text = MyClase.Trunk(_r1.y, Convert.ToInt16(precision)).ToString();

                this.lblR1Z.Text = MyClase.Trunk(_r1.z, Convert.ToInt16(precision)).ToString();

                this.lblR2X.Text = MyClase.Trunk(_r2.x, Convert.ToInt16(precision)).ToString();

                this.lblR2Y.Text = MyClase.Trunk(_r2.y, Convert.ToInt16(precision)).ToString();

                this.lblR2Z.Text = MyClase.Trunk(_r2.z, Convert.ToInt16(precision)).ToString();

            }

        }

Cuando lo ejecutes deberías obtener un resultado parecido al siguiente:

Ponlo a prueba, piensa en cómo mejorarlo y comparte con nosotros tus progresos.

Deja un comentario

Tu dirección de correo electrónico no será publicada.

Información básica sobre protección de datos Ver más

  • Responsable: MTB Software de Ponent, SLU.
  • Finalidad:  Moderar los comentarios.
  • Legitimación:  Por consentimiento del interesado.
  • Destinatarios y encargados de tratamiento:  No se ceden o comunican datos a terceros para prestar este servicio. El Titular ha contratado los servicios de alojamiento web a Hostinet, SL que actúa como encargado de tratamiento.
  • Derechos: Acceder, rectificar y suprimir los datos.
  • Información Adicional: Puede consultar la información detallada en la Política de Privacidad.

Esta web utiliza cookies propias y de terceros para su correcto funcionamiento y para fines analíticos. Al hacer clic en el botón Aceptar, acepta el uso de estas tecnologías y el procesamiento de tus datos para estos propósitos. Ver Política de cookies
Privacidad