graphics

37
Windows Programming(11)_Graphics 1 Graphics Graphics GDI Graphics Color Rectangle Pen Brush Bitmap Paint Event

Upload: milo

Post on 04-Jan-2016

146 views

Category:

Documents


0 download

DESCRIPTION

Graphics. GDI Graphics Color Rectangle Pen Brush Bitmap Paint Event. Windows. Windows. Device Driver. Windows. Windows. (GDI). Program. Program. Program. Program. Device. Device. Device. Device. 장치에 독립적. 장치에 의존적. GDI(Graphic Device Interface). Windows OS & GDI - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Graphics

Windows Programming(11)_Graphics 1

GraphicsGraphics

GDI Graphics Color Rectangle Pen Brush Bitmap Paint Event

Page 2: Graphics

Windows Programming(11)_Graphics 2

GDI(Graphic Device Interface)GDI(Graphic Device Interface) Windows OS & GDI

• 화면과 프린터에 정보를 표시하는 작업을 담당 • 운영체제의 하위 시스템 중 하나로 GDI32.DLL 로 존재• GDI+ 는 Microsoft Windows XP 운영 체제의 하위 시스템을 구성하는 API 로 이전 버전의 Wi

ndows 에 포함된 GDI 의 후속 제품 , 새로운 기능을 추가하고 기존의 기능을 최적화

Application program & GDI• Windows 운영체제가 출력장치를 제어할 수 있도록 응용 프로그램에 제공하는 모든 기능 (AP

I:Application Programming Interface) • 응용 프로그램과 디바이스 드라이버의 중간 역할• GDI+ 클래스에서 제공되는 메서드를 호출하면 호출된 메서드에서 해당 장치 드라이버를 호출

ProgramProgram

WindowsWindows

DeviceDeviceProgramProgram

WindowsWindows

DeviceDevice

Device Driver

장치에 독립적 장치에 의존적

(GDI)

Page 3: Graphics

Windows Programming(11)_Graphics 3

GDI GDI 사용 목적사용 목적 장치에 독립적

• 장치에 의존하지 않으므로 장치가 변경되더라도 프로그램의 수정이 불필요

• 특정 디스플레이 장치의 세부 사항을 고려하지 않고도 화면이나 프린터에 정보 표시가능

장치에 간접접근• 멀티태스킹을 위한 화면 분할 처리를 하는 운영체제에서 하나의

응용프로그램이 출력장치를 독점하지 못하도록 운영체제를 통하여 간접접근

Page 4: Graphics

Windows Programming(11)_Graphics 4

Window Application program

Window Application program

Graphics 객체 생성 /그래픽 함수 호출

Graphics 객체 생성 /그래픽 함수 호출

GDI32.DLLGDI32.DLL

Device DriverDevice Driver

(1) 출력 전에 윈도즈 운영체제의 GDI와 통신하는 Graphics 객체 생성

(2) Graphics 객체의 그래픽함수 호출로 출력 작업 지시

(3) Graphics 객체의 그래픽 함수는 GDI 를 통해 출력 처리 .

(4) GDI 는 응용프로그램의 출력정보를 가지는 Graphics 를 참고하여 다양한 상황을 고려하여 장치드라이버를 호출하여 출력

윈도우 프로그램의 출력 과정윈도우 프로그램의 출력 과정

Page 5: Graphics

Windows Programming(11)_Graphics 5

GDI+ GDI+ 를 관리하는 를 관리하는 NameSpaceNameSpace

System.Drawing • GDI+ 기본 그래픽 기능 관리 • Rectangle, Point, Color, Size 등 GDI+ 기본 형식 구조체 제공• Graphics, Pen, Brush, Font, Bitmap 클래스 제공

System.Drawing.Drawing2D • 고급 2 차원 및 벡터 그래픽 기능을 제공 • LinearGradientBrush, Matrix( 기하학적 변환에 사용 ), GraphicsPath( 연결된 일련의 선과 곡선 ) 클래스 제공

System.Drawing.Imaging • 고급 GDI+ 이미징 기능을 제공• Metafile 클래스

System.Drawing.Text • 고급 GDI+ 입력 체계 기능 제공• 글꼴 컬렉션 제공

System.Drawing.Printing • 인쇄 관련 서비스 제공• PrintDocument 클래스 제공

Page 6: Graphics

Windows Programming(11)_Graphics 6

System.DrawingSystem.Drawing

GDI+ 기본 그래픽 기능 사용을 위한 네임스페이스 클래스

• Graphics : 출력에 대한 정보를 관리하는 객체 출력영역 , 원점정보 , 그리기 함수 등 제공

• Pen , Pens, SystemPens : 선과 곡선을 그리는 데 사용• Brush, Brushes : 도형의 내부를 채우는 데 사용• Region : 사각형과 경로로 구성된 그래픽 모양의 내부를 설명• Font : 글꼴 , 크기 및 스타일 특성을 포함하여 텍스트의 특정 형식을 정의• Icon : 개체를 나타내는 데 사용하는 작은 비트맵 이미지인 Windows

아이콘 , 투명한 비트맵 형식• Image : Bitmap 및 Metafile 하위 클래스에 기능을 제공하는 추상 클래스 • Bitmap : 그래픽 이미지의 픽셀 데이터와 그 특성으로 구성되는 GDI+

비트맵 , 픽셀 데이터로 정의된 이미지에서 작업하는 데 사용되는 개체

Page 7: Graphics

Windows Programming(11)_Graphics 7

필수 구조체 • Point, PointF: 2 차원 평면의 한 점을 정의하는 X, Y 좌표의 쌍

Offset() 메서드로 포인트의 위치 값 변경처리

• Size, SizeF : 보통 사각형의 너비와 높이의 정수 쌍• Color : ARGB 색을 나타내는 구조체• Rectangle, RectangleF : 위치와 크기로 사각형 표현

System.DrawingSystem.Drawing

Page 8: Graphics

Windows Programming(11)_Graphics 8

Color Color 구조체구조체

ARGB(alpha-red-green-blue) 색을 표현 주요 멤버

• FromArgb() : ARGB 값으로 칼라 설정• FromName() : 알려진 시스템 칼라 (KnownColor) 이름으로 지정• ToArgb() : Color 형의 ARGB 값 추출• A,R,G,B : alpha,red,green,blue 값을 확인하는 속성• GetBrightness(), GetHue(), GetSaturation(): : 밝기 , 색상 , 채도

추출• 시스템 표준색 속성 :

Color.Blue Color.Red Color.Green Color.Black Color.BlueViolet Color.Brown Color.Chocolate Color.Cyan Color.DarkBlue, Color.Gold Color.Gray Color.GreenYellow Color.Lavender Color.Olive, Color. Orange Color. Violet, …

Page 9: Graphics

Windows Programming(11)_Graphics 9

System.Drawing.SystemColors System.Drawing.SystemColors

Windows 표시 요소의 색 (Color 구조체 ) 들을 속성으로 제공하는 클래스

속성 설명ActiveCaption 활성 타이틀바의 배경색

ActiveCaptionText 활성 타이틀바의 텍스트 색

Control 버튼과 다른 3D 요소들의 배경색ControlDark 3D 요소의 그림자 색ControlLight 3D 요소의 강조 색ControlText 버튼과 다른 3D 요소의 텍스트 색Desktop Windows 데스크탑 색

GrayText 사용자 인터페이스 요소가 비활성화 되었을 때의 텍스트 색Highlight 강조된 텍스트의 배경색 ( 선택된 텍스트 , 선택된 메뉴 항목 )

HighlightText 강조된 텍스트의 전경색 ( 선택된 텍스트 , 선택된 메뉴 항목 )

Page 10: Graphics

Windows Programming(11)_Graphics 10

속성 설명InactiveBorder 비활성 창의 테두리 색InactiveCaption 비활성 타이틀바의 배경색

InactiveCaptionText 비활성 타이틀바의 텍스트 색

Menu 메뉴 배경색MenuText 메뉴 텍스트 색Window 창의 사용자 영역의 배경색

// 칼라 정의 및 사용 예//alpha=100, r=200,g=200, b= 10Color c1 = Color.FromArgb(100, 200, 200, 10); //System.Drawing.KnownColor 열거형내의 이름으로 칼라 지정Color c2 = Color.FromName("Blue"); // 시스템 정의 색 Color c3 = Color.Green

//칼라 사용

this.ForeColoe = c2;

objGraphics.Clear(this.BackColor);

Pen myPen = new Pen(Color.BlueViolet, 5);

if (this.BackColor == SystemColors.ControlDark) { this.BackColor = SystemColors.Control; }

Page 11: Graphics

Windows Programming(11)_Graphics 11

Rectangle Rectangle 구조체 구조체

위치와 크기로 사각형 표현 생성자

• Rectangle (Point, Size) • Rectangle (Int32, Int32, Int32, Int32)

주요속성• X : Rectangle 구조체의 왼쪽 위 모퉁이의 x 좌표 • Y : Rectangle 구조체의 왼쪽 위 모퉁이의 y 좌표• Width : Rectangle 구조체의 너비 • Height : Rectangle 구조체의 높이 • Left : Rectangle 구조체의 왼쪽 가장자리의 x 좌표• Right : Rectangle 구조체의 X 및 Width 속성 값의 합인 X 좌표 • Top : Rectangle 구조체의 위쪽 가장자리의 y 좌표 . • Bottom : Rectangle 구조체의 Y 및 Height 속성 값의 합인 Y 좌표• Location : Rectangle 구조체의 왼쪽 위 모퉁이의 좌표 • Size : Rectangle 의 크기

Page 12: Graphics

Windows Programming(11)_Graphics 12

주요 메서드• Contains() : 지정된 점이 이 Rectangle 에 의해 정의된 사각형 영역 안에 들어 있는지 여부를 확인

Rectangle.Contains (Point) Rectangle.Contains (Rectangle) Rectangle.Contains (Int32, Int32)

// Rectangle 사용 예Rectangle rect = new Rectangle(0,0,100,50); //X=0, Y=0, Width=100, Height = 50MessageBox.Show("Left=" + r1.Left + " Right=" + r1.Right + " Top=" + r1.Top + " Bottom=" + r1.Bottom, "Rectangle"); Point p = new Point(20, 30); //X=20, Y=30

if (rect.Contains(p){ //Point p 가 Rectangle rect안에 존재하는가 확인 …}

Rectangle Rectangle 구조체 구조체

Page 13: Graphics

Windows Programming(11)_Graphics 13

그래픽 좌표계 그래픽 좌표계 & & 점점 //선선

그래픽 기본 좌표계

출력화면의 픽셀 ( 점 ) 출력화면의 선

기본 좌표계는 원점이 왼쪽 위 모퉁이에 있으며 x 축은 오른쪽을 향하고 y 축은 아래쪽을 향하며 , 기본 좌표계의 눈금 단위는 픽셀

Page 14: Graphics

Windows Programming(11)_Graphics 14

타원타원 , , 호호 , , 다각형다각형

Point(x,y)

w

h 30

180

시작 각도 30 도 , 전진 각도 180 도인 원호 (Arc)

시작점 (x,y), 폭 (w), 높이 (h) 인 사각형에 내접하는 타원 (Ellipse)

여러 점들로 구성된 다각형들

Point(x1,y1)

Point(x2,y2)

Point(x3,y3)

세 점들로 구성된 삼각형

•타원 (Ellipse) •원호 (Arc)

•다각형 (Polygon)

Page 15: Graphics

Windows Programming(11)_Graphics 15

곡선곡선

•cardinal spline점과 장력으로 표현된 곡선 (Curve)

•3 차원 곡선 스플라인 (Bezier spline)두 끝점과 제어점로 표현된 곡선 (Bezier)

Page 16: Graphics

Windows Programming(11)_Graphics 16

Graphics Graphics 객체 객체

Graphics 객체를 통해 GDI 와 통신(1)Graphics 객체 생성(2)Graphics 객체를 사용하여 도형을 그리거나 이미지 표시(3)Graphics 객체 리소스 해제 (Dispose())

주요속성• PageUnit : 그래픽 표현 단위 설정 (Default:Pixel)

: GraphicsUnit.Display, GraphicsUnit.Document, GraphicsUnit.Inch, GraphicsUnit.Milimeter, GraphicsUnit.Pixel, GraphicsUnit.Point

• Clip : 그리기 영역을 제한하는 Region 을 가져오거나 설정 • DpiX, DpiY : 현재 Graphics 의 가로 , 세로 해상도

Page 17: Graphics

Windows Programming(11)_Graphics 17

Graphics Graphics 객체 생성 방법객체 생성 방법

1.폼 또는 컨트롤의 Paint 이벤트 PaintEventArgs 에서 Graphics 개체에 대한 참조 얻기 폼 또는 컨트롤을 그릴 때 사용private void Form1_Paint(object sender, PaintEventArgs pe) { Graphics g = pe.Graphics; … }

2.폼 또는 컨트롤의 CreateGraphics() 메서드 해당 폼이나 컨트롤의 그리기 화면을 나타내는 Graphics 개체에 대한

참조 얻기 이미 있는 폼이나 컨트롤에서의 그리기 작업에 이용 Graphics g = this.CreateGraphics();

3.Image 에서 상속된 개체에서 Graphics 개체 생성 기존 이미지를 변경하려는 경우에 유용Bitmap myBitmap = new Bitmap(@"C:\Pics\myPic.bmp"); Graphics g = Graphics.FromImage(myBitmap);

Page 18: Graphics

Windows Programming(11)_Graphics 18

Graphics Graphics 객체의 그리기 함수객체의 그리기 함수 Clear (): 전체 그리기 화면을 지우고 , 지정한 색으로 배경을 칠하는 함수 DrawArc() : 좌표 , 너비 , 높이의 쌍으로 지정된 타원의 부분을 나타내는 호를 그리는

함수 DrawEllipse() : 좌표 , 높이 , 너비의 쌍으로 지정된 경계 사각형에 의해 정의되는

타원을 그리는 함수 DrawLine() : 좌표 쌍에 의해 지정된 두 개의 점을 연결하는 선을 그리는 함수 DrawLines() : Point 구조체의 배열을 연결하는 일련의 선 세그먼트를 그리는 함수 DrawPie() : 좌표 쌍 , 너비 , 높이 및 두 개의 방사형 선에 의해 지정된 타원으로

정의된 부채꼴 모양을 그리는 함수 DrawPolygon() : Point 구조체의 배열에 의해 정의된 다각형을 그리는 함수 DrawRectangle(): 좌표 쌍 , 너비 및 높이에 의해 지정된 사각형을 그리는 함수 DrawRectangles(): Rectangle 구조체에 의해 지정된 일련의 사각형을 그리는 함수 DrawString() : 지정된 위치에 지정된 Brush 및 Font 개체로 지정된 텍스트 문자열을

그리는 함수

•선 그리기 함수 형식 : Graphics.DrawLine (Pen, Point, Point)

•원 그리기 함수 형식 : Graphics.DrawEllipse (Pen, Rectangle)

•사각형 그리기 함수 형식 : Graphics.DrawRectangle (Pen, Rectangle)

Page 19: Graphics

Windows Programming(11)_Graphics 19

DrawPath() : GraphicsPath 를 그리는 함수 DrawBezier() : 네 개의 Point 구조체로 정의되는 곡선을 그리는 함수 DrawBeziers(): 일련의 3 차원 곡선 스플라인을 Point 구조체의 배열에서 그리는 함수

DrawClosedCurve(): Point 구조체의 배열에 의해 정의되는 닫힌 카디널 스플라인을

그리는 함수 DrawCurve() : Point 구조체의 지정된 배열을 따라 카디널 스플라인을 그리는 함수 DrawIcon() : 지정된 Icon 에 의해 나타나는 이미지를 지정된 좌표에 그리는 함수 DrawIconUnstretched() : 이미지의 크기 조정 없이 지정된 Icon 에 의해 나타나는

이미지를 그리는 함수 DrawImage() : 지정된 Image 를 지정된 위치에 원래 크기로 그리는 함수 DrawImageUnscaled() : 지정된 이미지를 좌표 쌍으로 지정된 위치에 원래 실제

크기로 그리는 함수 DrawImageUnscaledAndClipped() : 지정된 사각형에 맞게 이미지 크기를 조정하여

클리핑하지 않고 지정된 이미지를 그리는 함수•이미지 그리기 함수 형식 : Graphics.DrawImage (Image, Point)

Page 20: Graphics

Windows Programming(11)_Graphics 20

•FillEllipse : 지정된 경계 사각형에 의해 정의되는 타원의 내부를 채웁니다 .

•FillClosedCurve : Point 구조체의 배열에 의해 정의된 닫힌 카디널 스플라인의 내부를

채웁니다 .

•FillPath :GraphicsPath 의 내부를 채웁니다 .

•FillPie : 타원에 의해 정의되는 부채꼴 섹션의 내부를 채웁니다 .

•FillPolygon :Point 구조체에 의해 지정된 점의 배열에 의해 정의되는 다각형의 내부를

채웁니다 .

•FillRectangle : Point 구조체에 의해 지정된 점의 배열에 의해 정의되는 다각형의

내부를 채웁니다 .

•FillRectangles : Rectangle 구조체에 의해 지정된 일련의 사각형의 내부를 채웁니다

사각형 채우기 함수 형식 : Graphics.FillRectangle (Brush, Rectangle)

Graphics Graphics 객체의 채우기 함수객체의 채우기 함수

Page 21: Graphics

Windows Programming(11)_Graphics 21

//다양한 그리기 함수 사용 예// 폼 컨트롤에 해당하는 graphics 객체 생성System.Drawing.Graphics objGraphics = this.CreateGraphics(); //Pen 객체 생성Pen myPen = new Pen(Color.Green, 2); //Brush 객체 생성SolidBrush brush = new SolidBrush(Color.BlueViolet);//사각형 객체 생성Rectangle rect = new Rectangle(100, 100, 40, 40);//Line 그리기objGraphics.DrawLine(myPen, new Point(100, 100), new Point(150, 150));Point[] plist = { new Point(100, 100), new Point(150, 50), new Point(200, 100), new Point(250, 50)};//여러 라인 그리기objGraphics.DrawLines(Pens.Plum , plist);//채워진 사각형 , 원 그리기objGraphics.FillRectangle(brush, rect);objGraphics.FillEllipse (Brushes.LightSkyBlue, 150, 100, 40, 40);//곡선 그리기 objGraphics.DrawBezier(Pens.Blue, new Point(10, 100), new Point(60, 50), new Point(100, 100), new Point(150, 50));//다각형 그리기objGraphics.DrawPolygon (Pens.Purple , plist );// 자원 해제myPen.Dispose();brush.Dispose();objGraphics.dispose();

Page 22: Graphics

Windows Programming(11)_Graphics 22

PenPen

선과 곡선을 그리는 데 사용되는 개체 생성자

• Pen (Brush)• Pen (Color) • Pen (Brush, Single)• Pen (Color, Single)

속성• Brush : Pen 의 특성을 결정하는 Brush • Color : Pen 의 색• Width : Pen 의 굵기• StartCap , EndCap : Pen 을 사용하여 그리는 선의 시작 부분 , 끝

부분에 사용되는 캡 스타일 Linecap. ArrowAnchor , Linecap. DiamondAnchor Linecap. Round

Page 23: Graphics

Windows Programming(11)_Graphics 23

DashStyle 속성 : 펜의 모양의 정하는 속성

Pens class : 모든 표준 색에 사용되는 펜 (굵기 1)• Pens.Blue Pens.Red Pens.Green Pens.Black Pens.BlueViolet Pens.Brown Pens.C

hocolate Brushes.Cyan Pens.DarkBlue, Pens.Gold Pens.Gray Pens.GreenYellow Pens.Lavender Pens.Olive, Pens. Orange Pens. Violet

값 설명Dash 대쉬 (-) 로 구성된 선을 지정 .

DashDot 대쉬와 점의 패턴으로 구성된 선을 지정 .

DashDotDot 대쉬와 두 개의 점으로 구성된 선을 지정 .

Dot 점으로 구성된 선을 지정 .

Solid 실선을 지정 .

Page 24: Graphics

Windows Programming(11)_Graphics 24

BrushBrush

사각형 , 타원 , 파이 , 다각형 및 경로와 같은 그래픽 도형의 내부를 채우는 데 사용할 개체

상속 계층 구조 System.Object

System.MarshalByRefObject System.Drawing.Brush System.Drawing.Drawing2D.HatchBrush

System.Drawing.Drawing2D.LinearGradientBrush System.Drawing.Drawing2D.PathGradientBrush

System.Drawing.SolidBrush System.Drawing.TextureBrush

SolidBrush HatchBrush TextureBrush LinearGradientBrush PathGradientBrush

Page 25: Graphics

Windows Programming(11)_Graphics 25

System.Drawing.SolidBrush• 단일 색의 BrushSolidBrush shadowBrush = new SolidBrush(Color.Blue);

System.Drawing.TextureBrush• 이미지를 사용하여 도형 내부를 채우는 BrushBitmap image1 = (Bitmap) Image.FromFile(@"C:\Images\music.bmp", tru

e); TextureBrush texture = new TextureBrush(image1);

System.Drawing.Drawing2D.HatchBrush• 무늬 스타일 (HatchStyle) 을 사용하는 사각형 BrushHatchBrush brush = new HatchBrush(HatchStyle.Cross,

Color.White, Color.Black);

System.Drawing.Brushes• 모든 표준 색에 사용되는 BrushBrushes.Black, Brushed.Red, Brushes.Blue, Brushes.Green,..

Page 26: Graphics

Windows Programming(11)_Graphics 26

Font Font

System.Drawing.Font• 글꼴 , 크기 및 스타일 특성을 포함하여 텍스트의 특정 형식을 정의하는

객체

System.Drawing.FontFamily • 비슷한 기본 디자인 및 스타일의 특정 변형이 있는 형식의 그룹을 정의

• Families 속성으로 설치된 모든 글꼴 확인 가능

Font Style

설명

Bold 굵은 텍스트 Italic 기울임꼴 텍스트

Regular 일반 텍스트 Strikeout

중간에 줄이 있는 텍스트

Underline

밑줄이 그어진 텍스트

//Font 생성 예

FontFamily fontFamily = new FontFamily("Arial");

Font font = new Font( fontFamily, 16,

FontStyle.Regular, GraphicsUnit.Pixel);

font = new Font("Arial Black", 20,

FontStyle.Bold | FontSytle.Italic);

Page 27: Graphics

Windows Programming(11)_Graphics 27

// Font , FontFamily 사용 예//ListBox 에 모든 글꼴을 얻어서 항목을 선택하면 해당 문자열 그리기private void fontFamilyToolStripMenuItem_Click(object sender, EventArgs e) { ListBox listBox1 = new ListBox(); listBox1.Width = 200; listBox1.Location = new Point(40, 120); listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged); this.Controls.Add(listBox1);// FontFamily 의 모든 등록 글꼴을 리스트박스에 얻어옴 foreach (FontFamily oneFontFamily in FontFamily.Families) { listBox1.Items.Add(oneFontFamily.Name); }}//리스트박스 항목 선택 처리void listBox1_SelectedIndexChanged(object sender, EventArgs e){ // 폼 컨트롤에 해당하는 graphics 객체 생성 Graphics objGraphics = this.CreateGraphics(); Color bgc = this.BackColor; objGraphics.Clear(bgc); // 배경색으로 지우기 //선택한 폰트로 문자열 그리기 string fname = ((ListBox) sender).SelectedItem.ToString() ; // 선택된 항목 얻기 Font font = new Font(fname, 12); objGraphics.DrawString(fname, font, Brushes.Black, new PointF(40, 100));}

Page 28: Graphics

Windows Programming(11)_Graphics 28

BitmapBitmap

픽셀단위의 그림을 나타내는 객체 상속 계층 구조 System.Object

System.MarshalByRefObject System.Drawing.Image System.Drawing.Bitmap

생성자• Bitmap (Image) : 지정된 기존 이미지에서 Bitmap 객체 생성• Bitmap (Stream) : 지정된 데이터 스트림에서 Bitmap 객체 생성• Bitmap (String) : 지정된 파일명에서 Bitmap 객체 생성 • Bitmap (Image, Size) : 지정된 크기와 함께 지정된 기존 이미지에서 Bit

map 객체 생성• Bitmap (width, height ) : 지정된 폭과 높이의 Bitmap 객체 생성

Page 29: Graphics

Windows Programming(11)_Graphics 29

BitmapBitmap

주요 멤버• Height : Image 의 높이 ( 픽셀 ) 속성• Size : Image 의 너비와 높이를 픽셀로 반환하는 속성 . • Width : 이 Image 의 너비 ( 픽셀 ) 속성• GetPixel () : Bitmap 의 지정된 픽셀의 칼라값 얻기 • SetPixel() : Bitmap 에서 지정된 픽셀의 칼라값 설정 • FromFile(): 지정된 파일에서 Image 생성 • Save() : Image 를 지정된 형식의 지정된 스트림에 저장 • GetBounds() : 지정된 단위로 Image 의 범위를 RectangleF 로 반환• RotateFlip() : Image 를 회전하거나 , 대칭 이동

Page 30: Graphics

Windows Programming(11)_Graphics 30

//비트맵 사용 예// 폼 컨트롤에 해당하는 graphics 객체 생성 System.Drawing.Graphics objGraphics = this.CreateGraphics(); Bitmap image1; //Image 얻기 . string [] fname = {"lighthouse.bmp", "flower.jpg"}; //이미지 파일명 목록 int x = 0; int y = 120; for (int i = 0; i < fname.Length; i++) { //이미지 파일명으로 비트맵 생성 image1 = new Bitmap(fname[i]); //이미지 그리기 , x,y 위치에 이미지 크기로 출력 objGraphics.DrawImage(image1, x, y); //사각영역 내 에 확대 , 축소 objGraphics.DrawImage(image1, new Rectangle (x,y,100,100)); //원본의 일부 영역 확대 , 축소 Rectangle dRect = new Rectangle(x, y, 100, 100); // 출력영역 Rectangle sRect = new Rectangle(210, 0, 50,50); // 원본이미지의 영역 objGraphics.DrawImage(image1,dRect,sRect , GraphicsUnit.Pixel); //이미지 정보를 문자열로 출력 string msg = "Name : " + fname[i] + " Size : " + image1.Size; objGraphics.DrawString(msg, this.Font, Brushes.Black, new PointF(x, y-20)); x += (image1.Width + 40); //다음 이미지의 x 좌표 계산 image1.Dispose(); //이미지 리소스 해제}

Page 31: Graphics

Windows Programming(11)_Graphics 31

컨트롤의 컨트롤의 Paint Paint 처리처리

폼이나 컨트롤을 다시 그리거나 그래픽 정보를 표현할 때 사용

방법(1)OnPaint() 재정의

(2)Paint 이벤트 핸들러 구현

Paint 이벤트• 무효 영역이 생길 경우 발생

• Update() 함수 호출

Page 32: Graphics

Windows Programming(11)_Graphics 32

Invalid Region(Invalid Region( 무효 영역무효 영역 ))

화면을 다시 그려야 하는 영역 무효영역이 생기는 경우

• 윈도우가 생성될 때• 최소화 또는 최대화 되었을 때• 다른 윈도우에 가려졌다가 보여질 때

무효 영역 생성 함수• Control.Invalidate () : 컨트롤의 전체 화면을 무효화• Control.Invalidate(Rectangle) : 지정된 사각 영역을 무효화

Page 33: Graphics

Windows Programming(11)_Graphics 33

//PaintEventHandler 를 사용한 마우스 위치에 원 그리기 public partial class frmPaint : Form { // 마우스 포인터를 위한 멤버변수 Point mp1 = new Point(10,10); private void frmPaint_MouseClick(object sender, MouseEventArgs e) { mp1 = new Point (e.X, e.Y); // 마우스 위치를 멤버변수에 저장 Invalidate(); // 폼 전체 영역을 무효영역으로 처리 } private void frmPaint_Paint(object sender, PaintEventArgs e) { int r = 10; //반지름 Size s = new Size(2*r, 2*r); // 원의 크기

// 마우스의 현재위치를 중심으로 하는 반지름 10 인 파란색 원그리기 Pen myPen = new Pen(Color.Blue, 2); //Pen 객체 생성 mp1.Offset(-r, -r); // 마우스의 위치를 중심점으로 처리하기 위해 시작점 위치 변경 // 사각형 객체 생성 ( 마우스의 위치를 중심점으로 하는 폭 , 높이 20 인 사각형 ) Rectangle rect = new Rectangle(mp1, s); // 사각형에 내접하는 원 그리기 e.Graphics .DrawEllipse(myPen, rect); myPen.Dispose(); //Pen 객체의 리소스 해제 }}

Page 34: Graphics

Windows Programming(11)_Graphics 34

// 폼에 그려진 그래픽요소 유지 방법 (1), 마우스 좌표를 컬렉션에 보관하여 원 그리기 public partial class frmPaint : Form { // 마우스 포인터를 보관할 리스트 멤버 변수 ArrayList mplist = new ArrayList(); private void frmPaint_MouseClick(object sender, MouseEventArgs e) { Point p = new Point (e.X, e.Y); mplist.Add (p); // 마우스 위치를 리스트에 보관 Invalidate(); // 폼 전체 영역을 무효영역으로 처리 } private void frmPaint_Paint(object sender, PaintEventArgs e) { int r = 10; //반지름 Size s = new Size(2*r, 2*r); // 원의 크기 myPen = new Pen(Color.SkyBlue, 2); // 새로운 Pen 객체 생성 // 현재까지 클릭된 마우스포인터로 원 그리기 foreach (Point p in mplist) { p.Offset(-r, -r); // 마우스의 위치를 중심점으로 처리 rect = new Rectangle(p, s); // 사각형 객체 생성 objGraphics.DrawEllipse(Pens.Red , rect); // 원 그리기 e.Graphics.DrawEllipse(myPen, rect); // 사각형에 내접하는 원 그리기 } myPen.Dispose(); //Pen 객체의 리소스 해제 } }

Page 35: Graphics

Windows Programming(11)_Graphics 35

// 폼에 그려진 그래픽요소 유지 방법 (2), 비트맵 사용 public partial class frmPaint : Form { Bitmap reDraw; // 비트맵 멤버변수 private void frmPaint_Load(object sender, EventArgs e) { // 클라이언트 크기의 비트맵 생성 reDraw = new Bitmap (this.ClientRectangle.Width , this.ClientRectangle.Height ) ; } private void frmPaint_Paint(object sender, PaintEventArgs e) { e.Graphics .DrawImage (reDraw, 0,0); //비트맵을 그리기 } private void frmPaint_MouseDown(object sender, MouseEventArgs e) { // 비트맵으로부터 그래픽객체 생성 Graphics objG = Graphics.FromImage(reDraw); // 마우스 위치를 중점으로 하는 지름 30 인 원 그리기 Rectangle rect = new Rectangle(e.X - 15, e.Y - 15, 30, 30); objG.FillEllipse(Brushes.Orange, rect); }

Invalidate(); // 폼 전체 영역을 무효영역으로 처리 }}

Page 36: Graphics

Windows Programming(11)_Graphics 36

/*Animation 예 , 그래픽에 애니메이션 효과를 줄 때 깜빡임 현상을 줄이기 위해 폼의 DoubleBuffered 속성을 true 로 설정 */public partial class frmAnimation : Form { int w = 100; int h = 100; Timer t1; private void InitializeComponent() { this.ClientSize = new System.Drawing.Size(300, 300); this.DoubleBuffered = true; } private void frmAnimation_Load(object sender, EventArgs e) { t1 = new Timer(); t1.Tick += new EventHandler(t1_Tick); t1.Interval = 200; t1.Start(); } void t1_Tick(object sender, EventArgs e) { Invalidate(); //0.2초마다 이벤트 발생 , 다시 그리기 } private void frmAnimation_Paint(object sender, PaintEventArgs e) {

Bitmap image1 = new Bitmap("hart.gif"); //Image 얻기 . // 화면 중앙 위치로 그리기 int x = ClientRectangle.Width / 2 - (w / 2); int y = ClientRectangle.Height / 2 - (h / 2); Rectangle rect = new Rectangle(x, y, w, h); e.Graphics.DrawImage(image1, rect); w += 20; h += 20; image1.Dispose(); } private void frmAnimation_Click(object sender, EventArgs e) { t1.Stop(); } private void frmAnimation_DoubleClick(object sender, EventArgs e) { t1.Start(); } }

Page 37: Graphics

Windows Programming(11)_Graphics 37

//Graphics Path 를 사용한 여러 그래픽요소 그리기 public partial class frmGPath : Form { System.Drawing.Drawing2D.GraphicsPath shapes = new System.Drawing.Drawing2D.GraphicsPath(); private void frmGPath_Load(object sender, EventArgs e) { makeShapes(); } private void frmGPath_Paint(object sender, PaintEventArgs e) { e.Graphics.DrawPath(Pens.Black, shapes); // Graphics Path 를 그리기// e.Graphics.FillPath(Brushes.Blue, shapes); // Graphics Path 를 채우기 }//Graphics Path 에 그래픽 요소 추가 private void makeShapes() { Rectangle rect = this.ClientRectangle; //클라이언트 영역 얻기 shapes.Reset(); // Graphics Path 초기화

shapes.AddEllipse(0, 0, rect.Width, rect.Height); // 원 그리기 shapes.AddLine(0, rect.Height / 2, rect.Width, rect.Height / 2); // 수

평선 그리기

string stringText = "Graphics Path Test"; FontFamily family = new FontFamily("Arial"); int fontStyle = (int)FontStyle.Bold ; int emSize = 15; Point origin = new Point(rect.Width / 2, rect.Height / 2); StringFormat format = StringFormat.GenericDefault; // 문자열 추가 shapes.AddString(stringText, family, fontStyle, emSize, origin, format); } }