[C#기초] 11. 이미지

INDEX

  1. 이미지
  2. 비트맵
  3. 임의의 크기의 비트맵 생성 및 클리어
  4. 더블 버퍼링
  5. 리소스 이미지 다루기

이미지

GDI+에서 다룰 수 있는 이미지 형식

이미지를 다루는 클래스

이미지 로딩 메서드

이미지 출력 메서드(Graphics)

이미지 출력 예제 코드

private void Form1_Paint(object sender, PaintEventArgs e)
{
    Image myImage = Image.FromFile("Photo.jpg");
    e.Graphics.DrawImage(myImage, 0, 0);
    myImage.Dispose();
}

비트맵

Bitmap 클래스

비트맵을 이용한 이미지 로딩

비트맵 출력

비트맵 출력 예제 코드

private void Form1_Paint(object sender, PaintEventArgs e)
{
    Bitmap myImage = new Bitmap("test1.jpg");

    //클라이언트 영역 지정
    SetClientSizeCore(myImage.Width, myImage.Height);
    e.Graphics.DrawImage(myImage, 0, 0);
    myImage.Dispose();
}

임의의 크기의 비트맵 생성 및 클리어

임의의 비트맵

임의 크기의 비트맵 생성 및 클리어 예제 코드

Bitmap bitmap;

public Form1()
{
    InitializeComponent();
    bitmap = new Bitmap(400, 300);
    SetClientSizeCore(400, 300);
}

private void Form1_Paint(object sender, PaintEventArgs e)
{
    //메모리에서 그려지는 부분
    Graphics bitmapGraphics = Graphics.FromImage(bitmap);
    bitmapGraphics.Clear(Color.Yellow);
    for(int i =0; i<10; i++)
    {
        bitmapGraphics.DrawString("C# Programming", Font, Brushes.Black, 10,10*i);
    }
    bitmapGraphics.DrawRectangle(Pens.Black, 100, 10, 200, 100);
    //폼에 출력
    e.Graphics.DrawImage(bitmap, 0, 0);
    bitmapGraphics.Dispose();
}

400x300 크기의 비트맵을 로딩하고 이미지 아래의 내용 출력

  • “C# Programming” 출력 X 10
  • 배경색은 Yellow로 출력
  • 사각형 출력

더블 버퍼링

더블 버퍼링

더블버퍼링 객체 구조

더블 버퍼링

더블 버퍼링 예제 코드

BufferedGraphicsContext context;
BufferedGraphics graphics;
Image myImage;
public Form1()
{
    InitializeComponent();
    // 참조
    context = BufferedGraphicsManager.Current;
    // 버퍼 크기 설정
    context.MaximumBuffer = new Size(800, 600);
    // 버퍼 그래픽스 객체 생성 및 잠조
    graphics = context.Allocate(CreateGraphics(), new Rectangle(0, 0, 800, 600));
    // 버퍼 지우기
    graphics.Graphics.Clear(Color.Yellow);
    myImage = Image.FromFile("temp.jpg");
    SetClientSizeCore(800, 600);
}

private void Form1_Paint(object sender, PaintEventArgs e)
{
    // 더블 버퍼에 출력
    Random rand = new Random();
    for (int i =0; i<100;i++)
    {
        graphics.Graphics.DrawImage(myImage, rand.Next(0, 700), rand.Next(0, 500));
    }
    //화면에 출력
    graphics.Render(e.Graphics);
}

화면에 이미지 100개를 출력

  • 더블 버퍼링을 사용하지 않을 경우
    • 이미지 100개 그리는 과정을 실시간으로 확인 가능
    • 100번 새로고침하는 것처럼 보여짐 (깜빡이 현상이 보임)
  • 더블 버퍼링 사용하는 경우
    • 이미지 100개 그리는 연산이 작업이 끝난 뒤 출력됨
    • 사용자 눈에는 한번에 짠 하고 나타남

리소스 이미지 다루기

리소스 이미지

리소스 이미지 출력 예제 코드

출력할 이미지를 먼저 리소스에 등록 후…

public Form1()
{
    InitializeComponent();
    SetClientSizeCore(Properties.Resources.temp.Width, Properties.Resources.temp.Height);
}

private void Form1_Paint(object sender, PaintEventArgs e)
{
    //Bitmap bitmap = Properties.Resources.temp;
    e.Graphics.DrawImage(Properties.Resources.temp, 0, 0);
}