直接控制24位位图的象素(E)[1]

[入库:2005年8月18日] [更新:2007年3月25日]

本文简介:选择自 sanjiang 的 blog

directly accessing pixels in a 24-bit bitmap


this article was contributed by zvika ben-haim.

environment: vc5/6, win95+

this article describes how to display 24-bit (truecolor) bitmaps which are created during run-time by directly accessing the bitmap's bit image.

the code in this article uses the cdib class, developed by david j. kruglinski in his book inside visual c++, 4th edition. the cdib class is copyrighted by microsoft, and can be used in your programs as long as you mention their name. the cdib class is included at the end of this document.

1. create a cdib object, and allocate memory.

this will typically be done in cview::oninitialupdate, or some such. it's done in the following way:



	// create a compatible dc
	cdc* pdc = getdc();
	assert(pdc);
	cdc dccompat;
	dccompat.createcompatibledc(pdc);
	releasedc(pdc);

	// allocate memory for the bitmap
	m_pdib = new cdib(csize(xsize,ysize), // size of the bitmap
					  24);            // bits per pixel
	verify(m_pdib->createsection(&dccompat));	 // allocate memory for bitmap

2. fill the bitmap data.

you now have a memory region, allocated by windows, in which you can write the output information. this memory region is accessed from m_pdib->m_lpimage, and contains a series of three-byte (r,g,b) pixels. as an example, you can get a nice rainbow-color image using the following code:


	int x,y;
	byte* dibits = m_pdib->m_lpimage;
	for(x=0; x<xsize; x++)
		for(y=0; y<ysize; y++) {
			*(dibits++) = doc(x,y);               // red
			*(dibits++) = doc(doc.xsize()-x-1,y); // green
			*(dibits++) = doc(x,doc.ysize()-y-1); // blue
		}

where we used the function doc, defined as follows (intended for bitmaps of size 512x512 pixels, more or less):


byte doc(int x,int y) {
	return (byte)(sqrt(x*x+y*y)/4);
}

3. display the bitmap.

from within cview::ondraw, use the following to display the bitmap:


	m_pdib->draw(pdc,m_rectdraw.topleft(),m_rectdraw.size());

where m_rectdraw is a logical-coordinate rectangle defining the position in which we want to place the bitmap. the bitmap is shrunk or expanded using the stretchdibits function so that it will fit into this rectangle.

4. delete the dib.

don't forget to deallocate the cdib object when you're done. the constructor deallocates all memory associate with the dib, including the memory of the actual image.

本文关键:bitmap
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top