본문 바로가기
C#/WPF

WPF 선그리기 예제

by 샤나엘 2020. 10. 28.
반응형

WPF ( Windows Presentation Foundation ) 에서 선그리는 예제입니다.

 

Windows에 Canvas를 추가하고, Name은 "canvas"로 설정했습니다.

Windows에 Loaded 이벤트를 등록하고, 해당 이벤트가 발생할 때 Canvas에 Line을 설정하여 그려지도록 했습니다.

 

아래 예제 소스와 실행결과를 남겨두니 도움이 되셨으면 좋겠습니다.

 

[xaml]

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded">
    <Canvas x:Name="canvas"/>
</Window>

 

 

 

 

[xaml.cs]

using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        int i = 0;
        int[,] a = new int[1000, 2];          // 좌표를 1000개 만든다

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            int x = 0;
            int y = 0;

            for(x = 0; x < 500; x += 10)
            {
                y = (x % 30 == 0) ? 100 : 300;

                a[i, 0] = x;
                a[i, 1] = y;

                Line line = null;
                if (i == 0)
                {
                    line = CreateLine(a[i, 0], a[i, 1], 0, 0, Brushes.Red, 3, null);
                }
                else
                {
                    line = CreateLine(a[i, 0], a[i, 1], a[i - 1, 0], a[i - 1, 1], Brushes.Red, 3, null);
                }

                this.canvas.Children.Add(line);

                i++;
            }
        }

        public Line CreateLine(double x1, double y1, double x2, double y2, Brush brush, double thickness, DoubleCollection dashStyle)
        {
            Line line = new Line();

            //첫번째 좌표 설정
            line.X1 = x1;
            line.Y1 = y1;

            //두번째 좌표 설정
            line.X2 = x2;
            line.Y2 = y2;

            line.Stroke = brush;//선색 지정
            line.StrokeThickness = thickness;//선 두께 지정
            line.StrokeDashArray = dashStyle;//점선 설정 - new DoubleCollection { 점 길이, 점 간격}

            return line;
        }
    }
}

 

 

 

[실행결과]

반응형

댓글