티스토리 뷰

C#

5 함수, 타이머

김윤지. 2023. 4. 5. 21:16

172. 수학 함수 그리기

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;
using System.Windows.Forms.DataVisualization.Charting;

namespace _018_graph
{
  public partial class Form1 : Form
  {
    // 생성자
    public Form1()
    {
      InitializeComponent();
      this.Text = "Graph using Chart Control";
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      ChartSetting();
      DataSetting();
    }

    private void DataSetting()
    {
      for(double x = -20; x <= 20; x += 0.1)
      {
        double s = Math.Sin(x) / x;
        double c = Math.Cos(x) / x;
        chart1.Series[0].Points.AddXY(x, s);
        chart1.Series[1].Points.AddXY(x, c);
      }
    }

    private void ChartSetting()
    {
      // 배경색
      chart1.ChartAreas[0].BackColor = Color.DarkBlue;

      // ChartArea의 x축
      chart1.ChartAreas[0].AxisX.Minimum = -20;
      chart1.ChartAreas[0].AxisX.Maximum = 20;
      chart1.ChartAreas[0].AxisX.Interval = 2;
      chart1.ChartAreas[0].AxisX.MajorGrid.LineColor 
        = Color.Gray;
      chart1.ChartAreas[0].AxisX.MajorGrid.LineDashStyle
        = ChartDashStyle.Dash;

      // ChartArea의 y축
      chart1.ChartAreas[0].AxisY.Minimum = -2;
      chart1.ChartAreas[0].AxisY.Maximum = 2;
      chart1.ChartAreas[0].AxisY.Interval = 0.5;
      chart1.ChartAreas[0].AxisY.MajorGrid.LineColor
        = Color.Gray;
      chart1.ChartAreas[0].AxisY.MajorGrid.LineDashStyle
        = ChartDashStyle.Dash;

      // Series[0] 설정, 디폴트로 제공되는 시리즈
      chart1.Series[0].ChartType = SeriesChartType.Line;
      chart1.Series[0].Color = Color.LightGreen;
      chart1.Series[0].BorderWidth = 2;
      chart1.Series[0].LegendText = "sin(x) / x";

      // Series[1]을 추가
      chart1.Series.Add("Series2");

      // Series[1] 설정, 추가된 시리즈
      chart1.Series[1].ChartType = SeriesChartType.Line;
      chart1.Series[1].Color = Color.Orange;
      chart1.Series[1].BorderWidth = 2;
      chart1.Series[1].LegendText = "cos(x) / x";
    }
  }
}

 

 

 

 

<Timer 용어>

- Timer 컨트롤

- Enabled : 타이머 활성화

    - timer1.Enabled = true;

    - timer1.Start(); 와 동일 기능

- Interval : 이벤트 빈도(밀리초 1000이 1초)

- timer1.Tick : 이벤트

    - timer1.Tick += <tab>

 

 

147. 디지털 시계

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 _019_Timer
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent();
      this.Text = "나의 디지털 시계";
    }

    private void Form1_Load(object sender, EventArgs e)
    {
      ClientSize = new Size(300, 300);

      timer1.Enabled = true;
      timer1.Interval = 1000; // 단위: ms, 1초
      timer1.Tick += Timer1_Tick;

      label1.Font = 
        new Font("맑은 고딕", 16, 
          FontStyle.Bold | FontStyle.Italic);

      label1.ForeColor = Color.DarkSlateBlue;
    }

    private void Timer1_Tick(object sender, EventArgs e)
    {
      label1.Text = DateTime.Now.ToString();
      label1.Location = new Point(
        ClientSize.Width/2 - label1.Width/2, 
        ClientSize.Height/2 - label1.Height/2);
    }

    private void 종료ToolStripMenuItem_Click(object sender, EventArgs e)
    {
      this.Close();
    }
  }
}

 

 

 

<GDI+, Graphics Device Interface>

- WinForm은 GDI+를 사용

- 윈도우가 디바이스 드라이버에 독립적으로 프로그래밍 할 수 있도록 그래픽을 제공해주는 모든 기능

- Visual C++ 환경에서 .NET 환경으로 변경되며 더 많은 장점과 사용의 편리함을 제공해준다

 

<System.Drawing NameSpace>

- 클래스 및 구조체

    > Brush, Font, Graphics, Image, Pen, Color, Point, Rectangle, Size

- Pen 클래스 - 선과 곡선을 그리는데 사용되는 객체

- Color 구조체 - 이름(Color.Black), FromArgb() 메서드

- Brush 클래스 - 도형에 색상을 적용

    > SolidBrush/HatchBrush/TextureBrush/LinearGradientBrush/PathGradientBrush

- Font 클래스

    > Font Style 열거형 : Bold/Italic/Regular/Strikeout/Underline

    > Font f = new Font(“굴림“, 40, FontStyle.Bold | FontStyle.Italic);

- Graphics 클래스

    >DrawArc/DrawBezier/DrawCurve/DrawEllipse/DrawIcon/

DrawImage/DrawLine/DrawPie/DrawPolygon/DrawRectangle/
DrawString/FillEllipse/FillRectangle/FillRegion/RotateTransform

 

<165. WinForm 디지털/아날로그 시계>

- 현재 시간 : DateTime.Now

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 _020_FormClock
{
  public partial class Form1 : Form
  {
    // 이 클래스의 변수(필드)
    private Graphics g;
    private bool aClockFlag = true;
    private Point center; // 중심점
    private double radius;  // 반지름
    private int hourHand;   // 시침의 길이
    private int minHand;    // 분침의 길이
    private int secHand;    // 초침의 길이

    const int clientSize = 400; // 상수로 클리이언트 크기를 지정
    const int clockSize = 300;  // 시계의 크기

    public Form1()
    {
      InitializeComponent();
      this.Text = "Form Clock";
      panel1.BackColor = Color.WhiteSmoke;

      this.ClientSize = new Size(clientSize, 
        clientSize+menuStrip1.Height);

      // 그래픽스 객체를 만든다
      g = panel1.CreateGraphics();

      aClockSetting();
      dClockSetting();
      TimerSetting();
    }

    private void dClockSetting()
    {
      label1.Font = new Font("맑은 고딕", 16,
        FontStyle.Bold | FontStyle.Italic);

      label1.ForeColor = Color.DarkSlateBlue;
    }

    private void aClockSetting()
    {
      center = new Point(clientSize/2, clientSize/2);
      radius = clockSize/2;
      hourHand = (int)(radius*0.45);
      minHand = (int)(radius * 0.55);
      secHand = (int)(radius * 0.65);
    }

    private void TimerSetting()
    {
      Timer timer = new Timer();
      timer.Interval = 1000;
      timer.Tick += Timer_Tick;
      timer.Start();
    }

    // 현재 시간을 읽어와서, 시계를 그린다
    private void Timer_Tick(object sender, EventArgs e)
    {
      DateTime c = DateTime.Now;

      panel1.Refresh();

      if(aClockFlag == true) // 아날로그
      {
        DrawClockFace();  // 시계판

        // 시계바늘을 그린다.(핵심, 각도를 계산)
        double radHr = (c.Hour % 12 + c.Minute / 60) * 30
          * Math.PI / 180; // 시간당 30도
        double radMin = (c.Minute + c.Second / 60) * 6
          * Math.PI / 180; // 분당 6도
        double radSec = c.Second * 6 * Math.PI / 180; //초당 6도

        DrawHands(radHr, radMin, radSec);
      }
      else // 디지털시계
      {
        label1.Text = DateTime.Now.ToString();
        label1.Location = new Point(
          panel1.Width / 2 - label1.Width / 2,      // ClientSize -> panel1
          panel1.Height / 2 - label1.Height / 2);
      }
    }

    // 각도를 받아서 시계바늘 그리는 메소드
    private void DrawHands(double radHr, double radMin, double radSec)
    {
      DrawLine(0, 0, (int)(hourHand*Math.Sin(radHr)),
        (int)(hourHand *Math.Cos(radHr)), Brushes.RoyalBlue, 8);
      DrawLine(0,0, (int)(minHand * Math.Sin(radMin)),
        (int)(minHand * Math.Cos(radMin)), Brushes.SkyBlue, 6);
      DrawLine(0, 0, (int)(secHand * Math.Sin(radSec)),
        (int)(secHand * Math.Cos(radSec)), Brushes.OrangeRed, 4);

      // 배꼽
      int coreSize = 16;
      Rectangle r = new Rectangle(
        center.X - coreSize/2, center.Y - coreSize/2,
        coreSize, coreSize);
      g.FillEllipse(Brushes.Gold, r);
      g.DrawEllipse(new Pen(Brushes.Green, 3), r);
    }

    private void DrawLine(int x1, int y1, int x2, int y2, Brush brush, int thick)
    {
      Pen p = new Pen(brush, thick);
      p.EndCap = System.Drawing.Drawing2D.LineCap.Round;
      g.DrawLine(p, center.X + x1, center.Y + y1, 
        center.X + x2, center.Y - y2);
    }

    private void DrawClockFace()
    {
      Pen p = new Pen(Color.LightSteelBlue, 30);
      g.DrawEllipse(p, center.X-clockSize/2,
        center.Y-clockSize/2, clockSize, clockSize);

      //숫자판(점) 그리기
      int dotSize = 16;
      for(int d=0; d<360; d+=30)
      {
        int x = (int)(center.X + radius * Math.Sin(d * Math.PI / 180));
        int y = (int)(center.Y - radius * Math.Cos(d * Math.PI / 180));
        g.FillEllipse(Brushes.AliceBlue,
          new Rectangle(x - dotSize / 2, y - dotSize / 2, dotSize, dotSize));
      }
    }

    private void 아날로그ToolStripMenuItem_Click(object sender, EventArgs e)
    {
      aClockFlag = true;
      label1.Text = "";
    }

    private void 디지털ToolStripMenuItem_Click(object sender, EventArgs e)
    {
      aClockFlag = false;
    }

    private void 끝내기ToolStripMenuItem_Click(object sender, EventArgs e)
    {
      this.Close();
    }
  }
}

'C#' 카테고리의 다른 글

7 TwoForms  (0) 2023.04.19
6 Firebase  (0) 2023.04.13
4 Form  (0) 2023.03.29
3 반복문 예제 30개  (0) 2023.03.22
2주차  (0) 2023.03.15
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/09   »
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
글 보관함