Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all articles
Browse latest Browse all 18858

Drawing multiple lines from a loop

$
0
0

Hopefully this is the right forum.

I've only been programming for a few days.

So I have this little C# program that draws a nice pattern. In WinForms the main code is

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;
            Rectangle rect = this.ClientRectangle;
            int cx = rect.Width;
            int cy = rect.Height;
            float scale = (float)cy / (float)cx;
            Pen pen = new Pen(Color.Black);
            for (int x = 0; x < cx; x += 7)
            {
                g.DrawLine(pen, 0, x * scale, cx - x, 0);
                g.DrawLine(pen, 0, (cx - x) * scale, cx - x, cx * scale);
                g.DrawLine(pen, cx - x, 0 * scale, cx, (cx - x) * scale);
                g.DrawLine(pen, cx - x, cx * scale, cx, x * scale);
            }
            g.Dispose();
            pen.Dispose();
        }

And in WPF my code is

public MainWindow()
        {
            InitializeComponent();

            for (int x = 0; x < myCanvas.Width; x+=7)
            {
                var myLine1 = new Line();
                myLine1.StrokeThickness = 1;
                myLine1.Stroke = Brushes.Black;
                myLine1.X1 = 0;
                myLine1.Y1 = x;
                myLine1.X2 = myCanvas.Width - x;
                myLine1.Y2 = 0;
                myCanvas.Children.Add(myLine1);

                var myLine2 = new Line();
                myLine2.StrokeThickness = 1;
                myLine2.Stroke = Brushes.Black;
                myLine2.X1 = 0;
                myLine2.Y1 = myCanvas.Width - x;
                myLine2.X2 = myCanvas.Width - x;
                myLine2.Y2 = myCanvas.Width;
                myCanvas.Children.Add(myLine2);

                var myLine3 = new Line();
                myLine3.StrokeThickness = 1;
                myLine3.Stroke = Brushes.Black;
                myLine3.X1 = myCanvas.Width - x;
                myLine3.Y1 = 0;
                myLine3.X2 = myCanvas.Width;
                myLine3.Y2 = myCanvas.Width- x;
                myCanvas.Children.Add(myLine3);

                var myLine4 = new Line();
                myLine4.StrokeThickness = 1;
                myLine4.Stroke = Brushes.Black;
                myLine4.X1 = myCanvas.Width - x;
                myLine4.Y1 = myCanvas.Width;
                myLine4.X2 = myCanvas.Width;
                myLine4.Y2 = x;
                myCanvas.Children.Add(myLine4);
            }
        }

How do I reduce the amount of code in the WPF version?

Thanks.

Marcus



Viewing all articles
Browse latest Browse all 18858

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>