C# Timer를 이용한 Image 업데이트 picturebox image버퍼

안녕하세요. C# 프로젝트를 실행하여 실시간 화면이 갱신되는 프로그램을 만들어 보겠어요. 

간단히 텍스트를 그려주는데 picturebox의 image에 그림을 그려 업데이트를 해줄 예정이에요. 

 

도구상자 timer

도구 상자에서 Timer를 추가합니다. 

윈도우폼

picturebox를 추가하고 흰색으로 변경해 놓았어요. 

배경색

소스로 가서 아래 내용을 추가합니다. 

  public Form1()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.Manual;
            Rectangle fullScrenn_bounds = Rectangle.Empty;
            foreach (var screen in Screen.AllScreens)
            {
                fullScrenn_bounds = Rectangle.Union(fullScrenn_bounds, screen.Bounds);
            }
            this.ClientSize = new Size(fullScrenn_bounds.Width, fullScrenn_bounds.Height);
            this.Location = new Point(fullScrenn_bounds.Left, fullScrenn_bounds.Top);

           pictureBox1.Size = new System.Drawing.Size(ClientSize.Width, ClientSize.Height);
           this.timer1.Start();
           this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
           pictureBox1.Image = new Bitmap(ClientSize.Width, ClientSize.Height);
           switch_time = 0;
        }

그럼 전체 화면으로 실행되는 그림박스를 만날 수 있어요. 

String draw_text="가동준비중";        
long switch_time=1;

두변수는 전역으로 일단 선언해 놓을게요. 

 private void timer1_Tick(object sender, EventArgs e)
        {
            switch_time = switch_time - my_util.gaptime();
            
            if (switch_time<0)
            {
                draw_text = "가동준비중";
            }
            else 
            {

            }
            
            draw_screen();
        }

timer1_tick 함수를 하나 만들어 두세요. myutil_.gaptime이 필요한데 내용은 별 내용 없습니다. 밀리세컨드를 이용해서 이전 그리기와 현재 그리기의 시간차를 구해오는 함수인데요. 내용은 아래와 같아요. 

public long gaptime()
        {
            DateTime TimeNow = DateTime.Now;
            long currenttime = TimeNow.Ticks/ TimeSpan.TicksPerMillisecond;
            if (oldtime==0)
            {
                oldtime = currenttime;
                return 0;
            }
            gapTime = currenttime - oldtime;
            Console.WriteLine("gapTime>" + gapTime);
            Console.WriteLine("oldtime>" + oldtime);
            Console.WriteLine("currenttime>" + currenttime);
            oldtime = currenttime;
            return gapTime;
        }

그리고 아래 변수를 보세요.

 long gapTime;
 long oldtime=0;

이걸 클래스내 전역으로 선언해 놓았어요. 

그리고 그리기 함수인데요.

private void draw_screen()
        {
            BufferedGraphicsContext currentContext;
            BufferedGraphics myBuffer;
            currentContext = BufferedGraphicsManager.Current;
            if (pictureBox1.Image == null)
            {
                return;
            }
            myBuffer = currentContext.Allocate(Graphics.FromImage(pictureBox1.Image), pictureBox1.DisplayRectangle);
            Rectangle ee = pictureBox1.ClientRectangle;
            //배경색 정리
            System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.White);
            myBuffer.Graphics.FillRectangle(ee, myBrush);
            Font drawFont = new Font("Arial", 150);
            SolidBrush drawBrush = new SolidBrush(Color.Black);
            StringFormat drawFormat = new StringFormat();
            float x = 150.0F;
            float y = 50.0F;
            //텍스트 출력
           myBuffer.Graphics.DrawString(draw_text, drawFont, drawBrush, x, y, drawFormat);
            myBuffer.Render();
            myBuffer.Dispose();
            pictureBox1.Invalidate();
        }

텍스트가 입력이 없을 때 가동 준비 중이라는 기본 텍스트가 화면에 출력됩니다.

텍스트가 입력이 될 때 코드에 

switch_time = 10000L; 스위치 타임에 10초의 시간을 넣었어요.

그럼 입력된 텍스트를 draw_text에 넣어서 출력을 해주고 10초 뒤 다시 준비 중이라는 글씨를 화면에 출력하게 되고요.

버퍼는 더블 버퍼를 이용한 방법인데요 이방식을 하는 건 화면 떨림 현상을 없애기 위해서 이렇게 처리해요. 

픽처 박스 image에 바로 그리게 되면 수정이 될 때마다 invalidate이벤트가 발생되어 눈이 엄청 피곤한 갱신 화면을 볼 수 있어요. 

 

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

ChromeDriver Chrome 용 WebDriver  (0) 2020.06.01
c# mysql maria db connect 연동  (0) 2020.04.22
c# hello word c# 시작 MessageBox.Show  (1) 2020.03.09
C# String 문자열 자르기 Substring 사용법  (0) 2020.03.05
c# EXCEL 파일 읽기  (2) 2020.02.25
블로그 이미지

은호아빠

여행, 맛집, 일상, 프로그래밍, 개발자, 윈도우, 웹, jsp, spring, db, mysql, oracle, c#

,