카테고리 없음

[mfc] 이미지 편집기 만들기1 - 다이얼로그 상의 이미지에 마우스 움직임 이벤트 처리

쭌탱 2024. 3. 25. 19:54

목표 

마우스의 좌표를 추적하는 기능 개발 

- 마우스 움직임 추적은 이미지위에서(여기션 검정색 이미지) 로 제한한다.  

- 추적된 마우스의 좌표는 이미지가 시작하는 지점이 0,0 이 된다.

 

 

준비물

1. 미리 생성된 MFC  Dialog 프로젝트

2. 480x272 사이즈의 이미지(.bmp 파일)

 

순서 

1. 도구상자에서  Picture Control 을 드래그하여 다이얼로그위에 올려놓기

2. Picture Control 의 속성 변경하기

3. Picuture Cotrol 에 이미지 로딩하기 

4. 이미지의 좌표, 크기 구하기

5. 마우스 움직임 이벤트 핸들러 생성하기

6. 마우스 움직임 이벤트 처리하기

 

 

 

작업

1. 도구상자에서  Picture Control 을 드래그하여 다이얼로그위에 올려놓기

2. Picture Control 의 속성 변경하기

  • ID 값 지정 
  • 형식을 Bitmap 으로 변경

 

 Frame 에서 Bitmap 으로 변경하면 아이콘이 아래와 같이 변경됨.

 

3. Picuture Cotrol 에 이미지 로딩하기 

3. 1컨트롤 변수 추가하기 

 

 

 

 

void CDrawEditUtilDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_STATIC_screen, m_picture_screen);  // <== picture  control 에 대한 컨트롤 변수 맵핑
}

 

3.2 이미지 불러와서 화면에 표시 

BOOL CDrawEditUtilDlg::OnInitDialog()
{
    ....
    HBITMAP hBitmap = NULL;
	hBitmap = (HBITMAP)LoadImage(0, L"bg.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
	m_picture_screen.SetBitmap(hBitmap);
	if (!hBitmap)::CloseHandle(hBitmap);
}

 

4. 이미지의 좌표, 크기 구하기 - 이 정보를 이용하여, 마우스 움직임시 이미지 위에 위치할때만 마우스 위치 추적할것임.

 

CDrawEditUtilDlg.h

class CDrawEditUtilDlg : public CDialogEx
{
    ....
public:
	CStatic m_picture_screen;
	CRect offset_rect;	// offset value for mouse point
	int screen_w, screen_h;	// map screen real size	
	afx_msg void OnMouseMove(UINT nFlags, CPoint point);
};

 

CDrawEditUtilDlg.cpp

BOOL CDrawEditUtilDlg::OnInitDialog()
{
    ....

	// TODO: 여기에 추가 초기화 작업을 추가합니다.
	HBITMAP hBitmap = NULL;
	hBitmap = (HBITMAP)LoadImage(0, L"bg.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
	m_picture_screen.SetBitmap(hBitmap);
	if (!hBitmap)::CloseHandle(hBitmap);

	CString temp;
	CRect rect, screen;
	GetDlgItem(IDC_STATIC_screen)->GetWindowRect(&rect);
	this->GetWindowRect(&screen);
	rect.left -= screen.left;
	rect.top -= screen.top;
	offset_rect = rect;
	screen_w = rect.Width();
	screen_h = rect.Height();	
	printf("image offset : %d, %d\n", rect.left, rect.top);
	printf("image width : %d, height : %d\n", screen_w, screen_h);

	return TRUE;  // 포커스를 컨트롤에 설정하지 않으면 TRUE를 반환합니다.
}

 

5. 마우스 움직임 이벤트 핸들러 생성하기

 

 

 

 

 

아래와 같이 매세지 함수 생성.

void CDrawEditUtilDlg::OnMouseMove(UINT nFlags, CPoint point)
{
	// TODO: 여기에 메시지 처리기 코드를 추가 및/또는 기본값을 호출합니다.

	CDialogEx::OnMouseMove(nFlags, point);
}

 

6. 마우스 움직임 이벤트 처리하기

 

OnMouseMove 함수에 이미지 위에 마우스가 움직일때마다 해당 좌표를 표시해주는 소스 추가 

 

void CDrawEditUtilDlg::OnMouseMove(UINT nFlags, CPoint point)
{
	// TODO: 여기에 메시지 처리기 코드를 추가 및/또는 기본값을 호출합니다.

	CDialogEx::OnMouseMove(nFlags, point);

	CRect rect;
	POINT a;

	this->GetWindowRect(&rect);
	::GetCursorPos(&a);
	a.x -= offset_rect.left;
	a.y -= offset_rect.top;

	a.x -= rect.left;
	a.y -= rect.top;

	if (a.x < 0 || a.y < 0 || a.x >= map_screen_w || a.y >= map_screen_h) {
		return;
	}

	printf("%d,%d\n", a.x, a.y);
}