[ create a new paste ] login | about

Link: http://codepad.org/X00ZfMMr    [ raw code | fork ]

C++, pasted on Feb 5:
#include <stdafx.h>
#include <windows.h>

// 単純なスプライトクラス
class Sprite {
private:
	HDC _hdc;
	HBITMAP _hbmp;
	int _width, _height;

	HDC create(HDC base_hdc, int w, int h);
	void release();
public:
	Sprite();
	Sprite(int w, int h);
	~Sprite();
	bool copyFrom(HWND hWnd);
	bool copyFrom(HDC base_hdc);
	
	HDC getDC() { return _hdc; } __declspec(property(get=getDC)) HDC hdc;
	HBITMAP getBMP() { return _hbmp; } __declspec(property(get=getBMP)) HBITMAP bmp;
	
	int getWidth() { return _width; } __declspec(property(get=getWidth)) int width;
	int getHeight() { return _height; } __declspec(property(get=getHeight)) int height;

	Sprite& operator=(const Sprite& sp) { copyFrom(sp._hdc); return *this; }
};

Sprite::Sprite(): _hdc(NULL), _hbmp(NULL), _width(0), _height(0)
{
}

Sprite::Sprite(int w, int h): _hdc(NULL), _hbmp(NULL)
{
	create(GetDC(NULL), w, h);
}

Sprite::~Sprite() { release(); }

void Sprite::release()
{
	if(_hdc) { DeleteDC(_hdc); _hdc = NULL; }
	if(_hbmp) { DeleteObject(_hbmp); _hbmp = NULL; }
}

HDC Sprite::create(HDC base_hdc, int w, int h)
{
	release();

	_hdc = CreateCompatibleDC(base_hdc);
	_hbmp = CreateCompatibleBitmap(base_hdc, w, h);
	SelectObject(_hdc, _hbmp);
	_width = w;
	_height = h;

	return _hdc;
}

bool Sprite::copyFrom(HWND hWnd)
{
	HDC hdc_win = GetDC(hWnd);
	bool b = copyFrom(hdc_win);
	ReleaseDC(hWnd, hdc_win);
	return b;
}

bool Sprite::copyFrom(HDC base_hdc)
{
	HBITMAP hbmp_tmp = (HBITMAP)GetCurrentObject(base_hdc, OBJ_BITMAP);
	if(hbmp_tmp==NULL) return false;
	
	BITMAP bmp;
	GetObject(hbmp_tmp, sizeof(BITMAP), &bmp);
	if(bmp.bmWidth<1 || bmp.bmHeight<1) return false;
	
	BitBlt(
		create(base_hdc, bmp.bmWidth, bmp.bmHeight)
		, 0, 0
		, bmp.bmWidth, bmp.bmHeight
		, base_hdc
		, 0, 0, SRCCOPY
	);
	return true;
}


int main()
{
	// 使い方:中身がコピーされる
	Sprite sp1(100, 100);	// 100x100 の空っぽのスプライト
	Sprite sp2;				// NULLなスプライト
	sp2 = sp1;				// 画像のコピー
}


Create a new paste based on this one


Comments: