Game programming notes-start (2) drawing on Windows

Source: Internet
Author: User
Game programming notes-start (2)

2. Drawing in a window

After reading the analysis above, I think many of my friends can't wait to learn this part of knowledge because the above knowledge is too simple, as long as you are familiar with algorithms, you can understand them. The key is that everyone is suffering from a brave hero! After learning algorithms for N years, I did n to algorithm questions, but I couldn't write such a simple little game.

Well, let's start our real game programming journey!

1. Overview

Drawing on Windows is similar to drawing by an artist. Art painting must first have the following tools: canvas, canvas, paint brush, and paint brush. Also, there are related concepts in windows. The drawing device devicecontext (DC), bitmap, pen, and brush. They correspond to each other.

2. Canvas

In Windows, it is called device context (DC), which is often called a drawing device. However, Windows's "canvas" is different from the "canvas" in the hands of art masters. Windows's "canvas" is essentially a collection of tools, manage the canvas, paint brush, paint brush, and painting methods. Then, all painting operations will be performed on the canvas.

1) system plotting equipment. The system has a default drawing, which we can use directly for a series of drawing operations.

Obtain the system plotting device:

HDC getdc (hwnd // window handle. That is, specify the drawing device for the window .);

For example:

HDC = getdc (g_hwnd); rectangle (HDC, 100,100,); // draw a rectangle ....

Return it to the window after use:

int ReleaseDC(  HWND hWnd, // handle to window  HDC hDC     // handle to DC);


2) create a canvas. Generally, we do not directly use the system canvas. Because the system canvas is directly associated with the display, the system canvas will be displayed in the window while painting, there is a time difference in the middle (we may draw a map after several times), and the game needs to be erased and re-painted repeatedly, so the screen will often flash violently. To solve this problem, we will create an auxiliary canvas. After drawing the canvas, We will display it on the screen at one time. Because the display time is very fast, we will not see the flickering.

Create a secondary drawing device:

HDC createcompatibledc (HDC // points to an existing DC. If the value is 0, the system creates a storage DC .);

The storage DC (Auxiliary drawing device) has only one pixel after creation, so we can't directly draw on it. We also need to paste a canvas on it.

After use, remember to release the resource:

BOOL DeleteDC(  HDC hdc   // handle to DC);

Example:

HDC memdc = createcompatibledc (0); // create the secondary drawing device SelectObject (memdc, hbitmap); // paste the canvas to the drawing device rectangle (memdc, X1, Y1, X2, y2); // draw the rectangle HDC = getdc (g_hwnd); // obtain the system drawing device copy memdc to HDC // copy to the system device display releasedc (g_hwnd, HDC ); // return the system drawing device deletedc (memdc); // release the auxiliary Drawing Device

3. Canvas

The canvas is actually a bitmap. Bitmap is very powerful. Here I will only introduce its common usage-serving as a canvas. Other functions will be introduced later.

Create a mask Bitmap (canvas ):

Hbitmap createcompatiblebitmap (HDC, // points to the drawing device, preferably the system's drawing device int nwidth, // bitmap width int nheight // bitmap height );

Release resources:

BOOL DeleteObject(  HGDIOBJ hObject   // handle to graphic object);


4. Paint Brush

The paint brush does not need to be explained. The paint brush for Windows is similar to that for art masters.

Create a paint brush:

Hpen createpen (INT fnpenstyle, // brush style. Straight line: ps_solid, dot line: ps_dot int nwidth, // paint width. The colorref crcolor // specifies the paint brush color );

Release resources:

BOOL DeleteObject(  HGDIOBJ hObject   // handle to graphic object);

Color: It can be composed of three colors: Red, green, and blue.

For example, colorref Cr = RGB (255,), Cr is pink (Red + blue ). Colorref is actually an alias for an unsigned long integer. RGB combines three values, red, green, and blue, into one unsigned long integer.

Colorref RGB (byte byred, // red weight 0 ~ 255, the larger the value, the deeper the surface. Byte bygreen, // The green weight is 0 ~ 255 byte byblue // The Blue weight is 0 ~ 255 );


5. Painter

Create a paint brush: hbrush createsolidbrush (colorref crcolor/brush color value); release a resource: bool deleteobject (hgdiobj hobject // handle to graphic object );


6. Painting

After creating the canvas, paint brush, and paint brush, use the API to select them from the drawing device. Of course, the drawing device has its own default paint brush and paint brush.

Hgdiobj SelectObject (HDC, // linear drawing device hgdiobj // point to the GDI object. That is, painting brush, paint brush, bitmap, etc .);

The returned value is the old content.


Some common drawing APIs:

1) Draw a rectangle.

Bool rectangle (HDC, // drawing device int nleftrect, // X coordinate int ntoprect in the upper left corner of the rectangle area, // y coordinate int nrightrect in the upper left corner of the rectangle area, // X coordinate at the bottom right corner of the rectangle area int nbottomrect // y coordinate at the bottom right corner of the rectangle area );

2) fill area. Fill the area with a paint brush, which is often used to erase the entire window.

Int fillrect (HDC, // drawing device const rect * LPRC, // hbrush HBr in the rectangular area // fill painting brush );
Region structure: typedef struct _ rect {long left; // long top on the left side of the rectangle (x coordinate in the upper left corner); // long right on the top side of the rectangle (Y coordinate in the upper left corner; // long bottom on the right side of the rectangle (x coordinate in the lower right corner); // rectangular bottom edge (Y coordinate in the lower right corner)} rect, * prect;
Obtain the client region of the window: bool getclientrect (hwnd, // handle to window lprect // client coordinates );


3) Copying between drawing devices.

Bool bitblt (HDC hdcdest, // int nxdest, // X coordinate int nydest in the upper left corner of the target area, // y coordinate int nwidth in the upper left corner of the target area, // int nheight, // HDC hdcsrc, // int nxsrc, // int nysrc, X coordinate, in the upper left corner of the Source Area, // The Y coordinate DWORD dwdrop in the upper left corner of the source region // operation code. Common srccopy (replication ).);

You can simply understand this API: copy the source drawing device to the target drawing device. Copy the canvas from the background to the foreground canvas. Copy the drawing device from the background to the monitor. The copied area is specified above.

For example, bitblt (HDC, g_nwidth, g_nheight, memdc, srccopy );


4) Other common APIs

Text Processing

Create Font: createfont, createpointfont, SelectObject (., font ).

Display text: textout, drawtext

Set text color: settextcolor, gettextcolor

Set the background: setbkcolor and setbkmode (set the background mode and the transparent is transparent)

Draw

Point: setpixel, setpixelv, getpixel.

Line: movetoex-linto.

Circle: Ellipse

Polygon

Arc: Arc

Bitmap Processing

Load bitmap/icon/cursor from file: LoadImage

Load bitmap from a resource: loadbitmap

Get bitmap information: GetObject

Copy between drawing devices

Direct mode: bitblt

Stretch copy: stretchblt

Transparent processing: tranparentblt, which requires the msimg32.lib library.

Translucent processing (Alpha hybrid): alpablend

Others

Obtain system attributes: getsystemmetrics, which contains important information.

Get the mouse screen coordinate: getcursorpos, which must be converted to the window coordinate using the Coordinate Conversion Function

Coordinate Conversion: clienttoscreen and screentoclient

Get the keyboard key status: getasynckeystate

Get the entire keyboard information: getkeyboardstate

Message Box: MessageBox


7. Example: drawing a map grid

In the first chapter, the window creation code is slightly encapsulated in the C language format. The core code is as follows:

# Include "app. H "int g_nwidth = 600; // window width int g_nheight = 480; // window height void Init () // game initialization {} void Update () // logic update {} void render () // screen rendering {HDC = getdc (gethwnd (); // obtain the system drawing device HDC memdc = createcompatibledc (0 ); // create an auxiliary drawing device hbitmap BMP back = createcompatiblebitmap (HDC, g_nwidth, g_nheight); // create a mask Bitmap (canvas) SelectObject (memdc, BMP back ); // paste the canvas to the drawing device Hpen penback = createpen (ps_solid, 1, RGB (255,); // create the paint brush selectobjec T (memdc, penback); // select the paint brush to hbrush brushback = createsolidbrush (RGB (255,255,255); // create the paint brush SelectObject (memdc, brushback ); // select the paint brush to the drawing device // erase the background rect rcclient; // The region structure getclientrect (gethwnd (), & rcclient); // obtain the customer region hbrush brushtemp = (hbrush) getstockobject (white_brush); // obtain the inventory object with a white paint brush. Fillrect (memdc, & rcclient, brushtemp); // fill the customer region. //////////////////////////////////////// ///////////////////// Hbrush brushobj = createsolidbrush (RGB (0,255, 0); // create an object painting brush // draw a dimension grid and draw a rectangle. Int DW = 30; int rows = g_nheight/dw; int Cols = g_nwidth/dw; For (INT r = 0; r <rows; ++ R) {for (int c = 0; C <Cols; ++ c) {If (r = c) {SelectObject (memdc, brushobj);} else {SelectObject (memdc, brushback);} rectangle (memdc, C * DW, R * DW, (C + 1) * DW, (R + 1) * DW) ;}} deleteobject (brushobj ); //////////////////////////////////////// /// // bitblt (HDC, 0, 0, g_nwidth, g_nheight, memdc, 0, 0, Srccopy); // eobject (penback) displayed on the system device; // release the paint brush resource deleteobject (brushback); // release the paint brush resource deleteobject (BMP back ); // release the bitmap resource deletedc (memdc); // release the auxiliary drawing device releasedc (gethwnd (), HDC); // return the system drawing device sleep (1 );} void clear () // resource release {}// main function int winapi winmain (hinstance, hinstance, lpstr, INT) {If (! Initapp (hinstance, l "Snake Game", g_nwidth, g_nheight) {return 0 ;}// initialize game Init (); // game loop mainloop (); // release the resource clear (); Return 0 ;}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.