본문 바로가기

Win32 api

Win32 api 강의 23화.

- 텍스처 이미지를 로드하고 그리기.

// CTexture.h
...
    HDC m_hDC;
    HBITMAP m_hBitmap;
    BITMAP m_tBitInfo;

public:
    void Load(const wstring& _strFilePath);
    HDC GetDC() const { return m_hDC; }
    UINT GetWidth() const { return m_tBitInfo.bmWidth; }
    UINT GetHeight() const { return m_tBitInfo.bmHeight; }
...

 

BITMAP 은 단순 구조체이며 비트맵 이미지의 각종 정보가 들어감. 

Texture 클래스에서는 연결된 비트맵에 대한 정보를 저장하기 위해 m_tBitinfo 멤버를 선언.

 

// CTexture.cpp
void CTexture::Load(const wstring& _strFilePath)
{
    // IMAGE_BITMAP은 비트맵 이미지를 로드하는 데 사용됩니다.
    // LR_LOADFROMFILE 플래그는 파일에서 이미지를 로드하도록 지정합니다.
    // LR_CREATEDIBSECTION 플래그는 DIB 섹션을 생성하여 이미지 데이터를 메모리에 저장하도록 지정합니다.
    m_hBitmap = (HBITMAP)LoadImage(nullptr, _strFilePath.c_str(), 
        IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION);
    assert(m_hBitmap && "CTexture::Load : LoadImage Failed");

    // CreateCompatibleDC: 지정된 DC와 호환되는 메모리 DC를 생성.
    m_hDC = CreateCompatibleDC(CCore::GetInstance()->GetMainDC());
    // SelectObject: DC에 GDI 객체(여기서는 비트맵)를 선택.
    HBITMAP hPrevBit = (HBITMAP)SelectObject(m_hDC, m_hBitmap);
    DeleteObject(hPrevBit);

    // Bitmap 정보 얻기.
    GetObject(m_hBitmap, sizeof(BITMAP), &m_tBitInfo);
}

 

Texture 의 DC 를 생성하고, 비트맵을 DC 에 연결함. 비트맵 정보도 저장.

// CPlayer.cpp
void CPlayer::render(HDC hDC)
{
    Vector2 pos = GetPos();
    Vector2 size = GetSize();

    int imageWidth = (int)m_pTexture->GetWidth();
    int imageHeight = (int)m_pTexture->GetHeight();

    // 오브젝트의 렌더링 로직 구현.
    if (m_pTexture)
    {
        BitBlt(hDC,
            static_cast<int>(pos.x - (imageWidth * 0.5f)),
            static_cast<int>(pos.y - (imageHeight * 0.5f)),
            imageWidth, imageHeight,
            m_pTexture->GetDC(),
            0, 0,
            SRCCOPY);
    }
    else
    {
        // Texture가 없으면 단색 사각형으로 렌더링.
        Rectangle(hDC,
            static_cast<int>(pos.x - (size.x * 0.5f)),
            static_cast<int>(pos.y - (size.y * 0.5f)),
            static_cast<int>(pos.x + (size.x * 0.5f)),
            static_cast<int>(pos.y + (size.y * 0.5f)));
    }
}

 

Player 에서 원하는 이미지를 m_pTexture 에 로드한 뒤, render 함수를 만들어 이미지를 그려줌.

        TransparentBlt(hDC,
            static_cast<int>(pos.x - (imageWidth * 0.5f)),
            static_cast<int>(pos.y - (imageHeight * 0.5f)),
            imageWidth, imageHeight,
            m_pTexture->GetDC(),
            0, 0,
            imageWidth, imageHeight,
            RGB(255, 0, 255)); // 투명색 지정 (마젠타)

 

BitBlt 대신 TransparentBlt 함수를 사용하면 배경색을 크로마키처럼 제외하여 그릴 수 있음.

이 함수를 사용하기 위해서는

#pragma comment(lib, "Msimg32.lib")

 

 

프로젝트 속성에서 링커 > 입력 > 추가 종속성에 Msimg32.lib 를 추가하거나 위처럼 #pragma comment ... 를 입력해주면 된다.

 

본래 wingdi.h 에 선언되어 있고 정의는 빠져 있음. Windows.h 에서 wingdi.h 를 참조하기 때문에 구현부를 채워줘야 함.

'Win32 api' 카테고리의 다른 글

Win32 api 강의 25 - 26화.  (0) 2025.09.17
Win32 api 강의 24화.  (0) 2025.09.17
Win32 api 강의 21 - 22화.  (0) 2025.09.16
Win32 api 강의 17 - 18화.  (0) 2025.09.15
Win32 api 15 - 16화.  (0) 2025.09.14