Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 1253 Visual Programming Unit I Topic 4. Presentation Outline The Device Context Getting a Device context Handle Getting Device Context Information.

Similar presentations

Presentation on theme: "CS 1253 Visual Programming Unit I Topic 4. Presentation Outline The Device Context Getting a Device context Handle Getting Device Context Information."— Presentation transcript:

1 CS 1253 Visual Programming Unit I Topic 4

2 Presentation Outline The Device Context Getting a Device context Handle Getting Device Context Information The Device Context Attributes

3 Introduction The subsystem of Microsoft Windows responsible for displaying graphics on video displays and printers is known as the Graphics Device Interface (GDI). GDI is an extremely important part of Windows. Not only do the applications you write for Windows use GDI for the display of visual information, but Windows itself uses GDI for the visual display of user interface items such as menus, scroll bars, icons, and mouse cursors.

4 The Device Context When you want to draw on a graphics output device such as the screen or printer, you must first obtain a handle to a device context (or DC). In giving your program this handle, Windows is giving you permission to use the device. You then include the handle as an argument to the GDI functions to identify to Windows the device on which you wish to draw. The device context contains many "attributes" that determine how the GDI functions work on the device. These attributes allow GDI functions to have just a few arguments, such as starting coordinates. The GDI functions do not need arguments for everything else that Windows needs to display the object on the device.

5 The Device Context For example, when you call TextOut, you need specify in the function only the device context handle, the starting coordinates, the text, and the length of the text. You don't need to specify the font, the color of the text, the color of the background behind the text, or the intercharacter spacing. These are all attributes that are part of the device context. When you want to change one of these attributes, you call a function that does so. Subsequent TextOut calls to that device context use the new attribute.

6 Getting a Device Context Handle Windows provides several methods for obtaining a device context handle. If you obtain a video display device context handle while processing a message, you should release it before exiting the window procedure. After you release the handle, it is no longer valid. The most common method for obtaining a device context handle and then releasing it involves using the BeginPaint and EndPaint calls when processing the WM_PAINT message: hdc = BeginPaint (hwnd, &ps) ; [other program lines] EndPaint (hwnd, &ps) ;

7 Getting a Device Context Handle Windows programs can also obtain a handle to a device context while processing messages other than WM_PAINT: hdc = GetDC (hwnd) ; [other program lines] ReleaseDC (hwnd, hdc) ;

8 Getting a Device Context Handle (2) The BeginPaint, GetDC, and GetWindowDC calls obtain a device context associated with a particular window on the video display. A much more general function for obtaining a handle to a device context is CreateDC: hdc = CreateDC (pszDriver, pszDevice, pszOutput, pData) ; [other program lines] DeleteDC (hdc) ;

9 Getting Device Context Information A device context usually refers to a physical display device such as a video display or a printer. Often, you need to obtain information about this device, including the size of the display, in terms of both pixels and physical dimensions, and its color capabilities. You can get this information by calling the GetDeviceCap ("get device capabilities") function: iValue = GetDeviceCaps (hdc, iIndex) ;

10 Getting Device Context Information The iIndex argument is one of 29 identifiers defined in the WINGDI.H header file. For example, the iIndex value of HORZRES causes GetDeviceCaps to return the width of the device in pixels; a VERTRES argument returns the height of the device in pixels. If hdc is a handle to a screen device context, that's the same information you can get from GetSystemMetrics. If hdc is a handle to a printer device context, GetDeviceCaps returns the height and width of the printer display area in pixels. You can also use GetDeviceCaps to determine the device's capabilities of processing various types of graphics.

11 DEVCAPS1 display for a 256-color, 640-by- 480 VGA.

12 The Size of the Device The GetDeviceCaps function helps you obtain information regarding the physical size of the output device, be it the video display or printer. Within a Windows program you can use the GetDeviceCaps function to obtain the assumed resolution in dots per inch that the user selected in the Display applet of the Control Panel

13 Finding Out About Color A video display capable of displaying only black pixels and white pixels requires only one bit of memory per pixel. Color displays require multiple bits per pixels. The more bits, the more colors; or more specifically, the number of unique simultaneous colors is equal to 2 to the number of bits per pixel. iBitsPixel = GetDeviceCaps (hdc, BITSPIXEL) ; iColors = GetDeviceCaps (hdc, NUMCOLORS) ;

14 The Device Context Attributes Device Context AttributeDefaultFunction(s) to ChangeFunction to Obtain Mapping ModeMM_TEXTSetMapModeGetMapMode Window Origin(0, 0)SetWindowOrgEx OffsetWindowOrgEx GetWindowOrgEx Viewport Origin(0, 0)SetViewportOrgEx OffsetViewportOrgEx GetViewportOrgEx Window Extents(1, 1)SetWindowExtEx SetMapMode ScaleWindowExtEx GetWindowExtEx Viewport Extents(1, 1)SetViewportExtEx SetMapMode ScaleViewportExtEx GetViewportExtEx PenBLACK_PENSelectObject BrushWHITE_BRUSHSelectObject FontSYSTEM_FONTSelectObject BitmapNoneSelectObject Current Position(0, 0)MoveToEx LineTo PolylineTo PolyBezierTo GetCurrentPositionEx Background ModeOPAQUESetBkModeGetBkMode Background ColorWhiteSetBkColorGetBkColor Text ColorBlackSetTextColorGetTextColor

15 Saving Device Contexts Normally when you call GetDC or BeginPaint, Windows gives you a device context with default values for all the attributes. Any changes you make to the attributes are lost when the device context is released with the ReleaseDC or EndPaint call. If your program needs to use non-default device context attributes, you'll have to initialize the device context every time you obtain a new device context handle:

16 Saving Device Contexts Although this approach is generally satisfactory, you might prefer that changes you make to the attributes be saved when you release the device context so that they will be in effect the next time you call GetDC or BeginPaint. You can accomplish this by including the CS_OWNDC flag as part of the window class style when you register the window class: = CS_HREDRAW | CS_VREDRAW | CS_OWNDC ;

17 Saving Device Contexts Now each window that you create based on this window class will have its own private device context that continues to exist when the window is destroyed. When you use the CS_OWNDC style, you need to initialize the device context attributes only once, perhaps while processing the WM_CREATE message: case WM_CREATE: hdc = GetDC (hwnd) ; [initialize device context attributes] ReleaseDC (hwnd, hdc) ; The attributes continue to be valid until you change them.

18 Saving Device Contexts In some cases you might want to change certain device context attributes, do some painting using the changed attributes, and then revert to the original device context. To simplify this process, you save the state of a device context by calling idSaved = SaveDC (hdc) ; Now you can change some attributes. When you want to return to the device context as it existed before the SaveDC call, you use RestoreDC (hdc, idSaved) ; You can call SaveDC any number of times before you call RestoreDC.

19 Presentation Outline Drawing Dots and Lines Setting Pixels Straight Lines The Bounding Box Functions Bezier Splines Using Stock Pens Creating, Selecting, and Deleting Pens Filling in the Gaps Drawing Modes Drawing Filled Areas The Polygon Function and the Polygon-Filling Mode Brushing the Interior

20 Presentation Outline The GDI Mapping Mode Device Coordinates and Logical Coordinates The Device Coordinate Systems The Viewport and the Window Working with MM_TEXT The Metric Mapping Modes The "Roll Your Own" Mapping Modes The MM_ISOTROPIC Mapping Mode MM_ANISOTROPIC: Stretching the Image to Fit Rectangles, Regions, and Clipping Working with Rectangles Random Rectangles Creating and Painting Regions Clipping with Rectangles and Regions

21 Drawing Dots and Lines Windows Graphics Device Interface makes use of device drivers for the graphics output devices attached to your computer. In theory, all that a graphics device driver needs for drawing is a SetPixel function and a GetPixel function. The only problem is performance. A function that is several calls away from each SetPixel function will be painfully slow.

22 Setting Pixels The SetPixel function sets the pixel at a specified x- and y- coordinate to a particular color: SetPixel (hdc, x, y, crColor) ; The GetPixel function returns the color of the pixel at the specified coordinate position: crColor = GetPixel (hdc, x, y) ;

23 Straight Lines Windows can draw straight lines, elliptical lines (curved lines on the circumference of an ellipse), and Bezier splines. Windows 98 supports seven functions that draw lines: LineTo Draws a straight line. Polyline and PolylineTo Draw a series of connected straight lines. PolyPolyline Draws multiple polylines. Arc Draws elliptical lines. PolyBezier and PolyBezierTo Draw Bezier splines.

24 Straight Lines Five attributes of the device context affect the appearance of lines that you draw using these functions: current pen position (for LineTo, PolylineTo, PolyBezierTo, and ArcTo only), pen, background mode, background color, and drawing mode.

25 Straight Lines To draw a straight line, you must call two functions. The first function specifies the point at which the line begins, and the second function specifies the end point of the line MoveToEx (hdc, xBeg, yBeg, NULL) ; LineTo (hdc, xEnd, yEnd) ; MoveToEx doesn't actually draw anything; The LineTo function then draws a straight line from the current position to the point specified in the LineTo function. If you ever need the current position GetCurrentPositionEx (hdc, &pt) ; where pt is a POINT structure.

26 Straight Lines The following code draws a grid in the client area of a window, spacing the lines 100 pixels apart starting from the upper left corner. The variable hwnd is assumed to be a handle to the window, hdc is a handle to the device context, and x and y are integers: GetClientRect (hwnd, &rect) ; for (x = 0 ; x < rect.right ; x+= 100) { MoveToEx (hdc, x, 0, NULL) ; LineTo (hdc, x, rect.bottom) ; } for (y = 0 ; y < rect.bottom ; y += 100) { MoveToEx (hdc, 0, y, NULL) ; LineTo (hdc, rect.right, y) ; }

27 Straight Lines POINT apt[5] = { 100, 100, 200, 100, 200, 200, 100, 200, 100, 100 } ; MoveToEx (hdc, apt[0].x, apt[0].y, NULL) ; for (i = 1 ; i < 5 ; i++) LineTo (hdc, apt[i].x, apt[i].y) ; When you have an array of points that you want connected with lines, you can draw the lines more easily using the Polyline function. Polyline (hdc, apt, 5) ;

28 Straight Lines Although you can use Polyline and PolylineTo to draw just a few lines, the functions are most useful when you need to draw a complex curve. You do this by using hundreds or even thousands of very short lines. If they're short enough and there are enough of them, together they'll look like a curve. For example, suppose you need to draw a sine wave.

29 Drawing Sinewave hdc = BeginPaint (hwnd, &ps) ; MoveToEx (hdc, 0, cyClient / 2, NULL) ; LineTo (hdc, cxClient, cyClient / 2) ; for (i = 0 ; i < NUM ; i++) { apt[i].x = i * cxClient / NUM ; apt[i].y = (int) (cyClient / 2 * (1 - sin (TWOPI * i / NUM))) ; } Polyline (hdc, apt, NUM) ;

30 Drawing Sinewave

31 The Bounding Box Functions Rectangle, Ellipse, RoundRect, Chord, and Pie functions are not strictly line-drawing functions. The functions draw lines, but they also fill an enclosed area with the current area-filling brush. This brush is solid white by default.

32 Rectangle Rectangle (hdc, xLeft, yTop, xRight, yBottom) ;

33 Ellipse Ellipse (hdc, xLeft, yTop, xRight, yBottom) ;

34 Round Rectangle RoundRect (hdc, xLeft, yTop, xRight, yBottom, xCornerEllipse, yCornerEllipse) ;

35 Arc, Chord, Pie Arc (hdc, xLeft, yTop, xRight, yBottom, xStart, yStart, xEnd, yEnd) ;

36 Arc, Chord, Pie Chord (hdc, xLeft, yTop, xRight, yBottom, xStart, yStart, xEnd, yEnd) ;

37 Arc, Chord, Pie Pie (hdc, xLeft, yTop, xRight, yBottom, xStart, yStart, xEnd, yEnd) ;

38 Bezier Splines PolyBezier (hdc, apt, 4) ;

39 Using Stock Pens When you call any of the line-drawing functions, Windows uses the "pen" currently selected in the device context to draw the line. The pen determines the line's color, its width, and its style, which can be solid, dotted, or dashed. The pen in the default device context is called BLACK_PEN. BLACK_PEN is one of three "stock pens" that Windows provides. The other two are WHITE_PEN and NULL_PEN. NULL_PEN is a pen that doesn't draw. You can also create your own customized pens.

40 Using Stock Pens HPEN hPen ; You obtain the handle to one of the stock pens by a call to GetStockObject. hPen = GetStockObject (WHITE_PEN) ; Now you must "select" that pen into the device context: SelectObject (hdc, hPen) ;

41 Creating, Selecting, and Deleting Pens hPen = CreatePen (iPenStyle, iWidth, crColor) ;

42 Drawing Filled Areas FunctionFigure RectangleRectangle with square corners Ellipse RoundRectRectangle with rounded corners ChordArc on the circumference of an ellipse with endpoints connected by a chord PiePie wedge defined by the circumference of an ellipse PolygonMultisided figure PolyPolygonMultiple multisided figures

43 Brushing the Interior hBrush = CreateHatchBrush (iHatchStyle, crColor) ;

44 The GDI Mapping Mode Increasing Value Mapping ModeLogical Unitx-axisy-axis MM_TEXTPixelRightDown MM_LOMETRIC0.1 mmRightUp MM_HIMETRIC0.01 mmRightUp MM_LOENGLISH0.01 in.RightUp MM_HIENGLISH0.001 in.RightUp MM_TWIPS1/1440 in.RightUp MM_ISOTROPICArbitrary (x = y)Selectable MM_ANISOTROPICArbitrary (x !=y)Selectable

45 The GDI Mapping Mode SetMapMode (hdc, iMapMode) ; where iMapMode is one of the eight mapping mode identifiers. You can obtain the current mapping mode by calling iMapMode = GetMapMode (hdc) ; The default mapping mode is MM_TEXT. In this mapping mode, logical units are the same as physical units, which allows us (or, depending on your perspective, forces us) to work directly in units of pixels.

46 The Viewport and the Window The mapping mode defines how Windows maps logical coordinates that are specified in GDI functions to device coordinates, where the particular device coordinate system depends on the function you use to obtain the device context. The mapping mode is said to define the mapping of the "window" (logical coordinates) to the "viewport" (device coordinates).

47 Working with MM_TEXT For the MM_TEXT mapping mode, the default origins and extents are shown below. Window origin:(0, 0)Can be changed Viewport origin:(0, 0)Can be changed Window extent:(1, 1)Cannot be changed Viewport extent:(1, 1)Cannot be changed xViewport = xWindow - xWinOrg + xViewOrg yViewport = yWindow - yWinOrg + yViewOrg

48 Working with MM_TEXT SetViewportOrgEx (hdc, cxClient / 2, cyClient / 2, NULL) ;

49 The MM_ISOTROPIC Mapping Mode The MM_ISOTROPIC mapping mode is ideal for using arbitrarily scaled axes while preserving equal logical units on the two axes. Rectangles with equal logical widths and heights are displayed as squares, and ellipses with equal logical widths and heights are displayed as circles.

50 MM_ANISOTROPIC: Stretching the Image to Fit In the MM_ANISOTROPIC mapping mode, Windows makes no adjustments to the values you set. This means that MM_ANISOTROPIC does not necessarily maintain the correct aspect ratio.

51 Rectangles, Regions, and Clipping Working with Rectangles FillRect (hdc, &rect, hBrush) ; FrameRect (hdc, &rect, hBrush) ; InvertRect (hdc, &rect) ; FillRect fills the rectangle with the specified brush. FrameRect uses the brush to draw a rectangular frame, but it does not fill in the rectangle. InvertRect inverts all the pixels in the rectangle, turning ones to zeros and zeros to ones. This function turns a white area to black, a black area to white, and a green area to magenta

52 Creating and Painting Regions A region is a description of an area of the display that is a combination of rectangles, polygons, and ellipses. Used for drawing or clipping. Like pens and brushes, regions are GDI objects. can delete any regions that you create by calling DeleteObject.

53 Creating and Painting Regions When you create a region, Windows returns a handle to the region of type HRGN. The simplest type of region describes a rectangle. You can create a rectangular region in one of two ways: hRgn = CreateRectRgn (xLeft, yTop, xRight, yBottom) ; or hRgn = CreateRectRgnIndirect (&rect) ; You can also create elliptical regions using hRgn = CreateEllipticRgn (xLeft, yTop, xRight, yBottom) ; or hRgn = CreateEllipticRgnIndirect (&rect) ;

54 Creating and Painting Regions iRgnType = CombineRgn (hDestRgn, hSrcRgn1, hSrcRgn2, iCombine) ; This function combines two source regions (hSrcRgn1 and hSrcRgn2) and causes the destination region handle (hDestRgn) to refer to that combined region. iCombine ValueNew Region RGN_ANDOverlapping area of the two source regions RGN_ORAll of the two source regions RGN_XORAll of the two source regions, excluding the overlapping area RGN_DIFFAll of hSrcRgn1 not in hSrcRgn2 RGN_COPYAll of hSrcRgn1 (ignores hSrcRgn2)

55 Creating and Painting Regions Once you have a handle to a region, you can use it with four drawing functions: FillRgn (hdc, hRgn, hBrush) ; FrameRgn (hdc, hRgn, hBrush, xFrame, yFrame) ; InvertRgn (hdc, hRgn) ; PaintRgn (hdc, hRgn) ;

56 Clipping with Rectangles and Regions SelectClipRgn (hdc, hRgn) ; Windows also includes several functions to manipulate this clipping region, such as ExcludeClipRect to exclude a rectangle from the clipping region, IntersectClipRect to create a new clipping region that is the intersection of the previous clipping region and a rectangle, and OffsetClipRgn to move a clipping region to another part of the client area.

Download ppt "CS 1253 Visual Programming Unit I Topic 4. Presentation Outline The Device Context Getting a Device context Handle Getting Device Context Information."

Similar presentations

Ads by Google