프로그래밍 언어/C#

C# 선그리기(Pen,DrawLine)

원원 2017. 8. 14. 16:49

안녕하세요. 오늘은 C#으로 윈도우폼에서 선 그리는것을 할 것입니다.


기본적으로 컴퓨터의 좌표계를 알아야 합니다.



컴퓨터의 좌표계입니다.




선을 그리기 위해서는 네단계가 필요합니다. 

첫번째로 Graphics개체에 대한 참조를 가져옵니다.

두번째로 선의 굵기와 색을 정합니다.  

세번째로는 시작점과 끝점을 정합니다.

네번째로 Graphics개체를 해제합니다.


첫번째) Graphics개체에 대한 참조

  Graphics graphics = CreateGraphics();


두번째)선의 굵기와 색 정하기

System.Drawing.Pen에 있는 Pen 클래스를 사용합니다.

1. Pen name = new Pen(color);

2. Pen name = new Pen(color,width);

color : 선의 색

width : 선의 굵기

1.로 한다면 width은 1로 됩니다.




세번째)시작점과 끝점 정하기

System.Drawing.Graphics에 있는 DrawLine함수를 사용합니다.

DrawLine(pen, x1, y1, x2, y2);

pen : 첫번째에서 정했던 선의 색과 굵기입니다.

x1,y1 : 시작점입니다.

x2,y2 : 끝점입니다.


네번째)Graphics개체를 해제

graphics.Dispose();



버튼을 클릭하면 대각선 그리기를 해보겠습니다.

Form에 버튼을 배치합니다.



버튼을 클릭하면 대각선 선이 그려집니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
    public partial class Fk : Form
    {
        public Fk()
        {
            InitializeComponent();
            this.Size = new Size(400400);
  
            
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Graphics graphics = CreateGraphics();
            Pen pen = new Pen(Color.Black);
            graphics.DrawLine(pen,0,0,400,400);
            graphics.DrawLine(pen,0,400,400,0);
            
            graphics.Dispose();
        }
    }
}
cs



버튼을 클릭하면 4등분하는 것을 해보겠습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
 
 
namespace WindowsFormsApplication3
{
    public partial class Fk : Form
    {
        public Fk()
        {
            InitializeComponent();
            this.Size = new Size(400400);
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            Graphics graphics = CreateGraphics();
            Pen pen = new Pen(Color.Black);
 
            for (int i = 1; i < 4; i++)
            {
                graphics.DrawLine(pen, 0100 * i, this.Width, 300 - 100 * (i - 1));
                graphics.DrawLine(pen, 100 * i, 0300 - 100 * (i - 1), this.Height);
            }
            graphics.Dispose();
 
        }
    }
}
 
cs



'프로그래밍 언어 > C#' 카테고리의 다른 글

C# 예외처리 try,catch,finally  (0) 2021.11.14
C# this키워드  (0) 2021.10.23
C# 생성자  (0) 2021.10.18
C# Format 메소드 사용하기  (0) 2021.10.02
C# 문자열 다루기  (0) 2021.10.02