cs 1253 visual programming unit i topic 4. presentation outline the device context getting a device...
TRANSCRIPT
CS 1253 Visual ProgrammingUnit I Topic 4
Presentation Outline The Device Context
Getting a Device context Handle Getting Device Context Information The Device Context Attributes
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.
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.
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.
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) ;
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) ;
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) ;
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) ;
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.
DEVCAPS1 display for a 256-color,
640-by-480 VGA.
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
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) ;
The Device Context Attributes
Device Context Attribute Default Function(s) to Change Function to Obtain
Mapping Mode MM_TEXT SetMapMode GetMapMode
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
Pen BLACK_PEN SelectObject SelectObject
Brush WHITE_BRUSH SelectObject SelectObject
Font SYSTEM_FONT SelectObject SelectObject
Bitmap None SelectObject SelectObject
Current Position (0, 0) MoveToEx LineTo PolylineTo PolyBezierTo
GetCurrentPositionEx
Background Mode OPAQUE SetBkMode GetBkMode
Background Color White SetBkColor GetBkColor
Text Color Black SetTextColor GetTextColor
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:
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: wndclass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC ;
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.
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.
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
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
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.
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) ;
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.
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.
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.
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) ;}
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) ;
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.
Drawing Sinewavehdc = 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) ;
Drawing Sinewave
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.
Rectangle
Rectangle (hdc, xLeft, yTop, xRight, yBottom) ;
Ellipse
Ellipse (hdc, xLeft, yTop, xRight, yBottom) ;
Round Rectangle
RoundRect (hdc, xLeft, yTop, xRight, yBottom, xCornerEllipse, yCornerEllipse) ;
Arc, Chord, Pie
Arc (hdc, xLeft, yTop, xRight, yBottom, xStart, yStart, xEnd, yEnd) ;
Arc, Chord, Pie
Chord (hdc, xLeft, yTop, xRight, yBottom, xStart, yStart, xEnd, yEnd) ;
Arc, Chord, Pie
Pie (hdc, xLeft, yTop, xRight, yBottom, xStart, yStart, xEnd, yEnd) ;
Bezier Splines
PolyBezier (hdc, apt, 4) ;
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.
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) ;
Creating, Selecting, and Deleting Pens hPen = CreatePen (iPenStyle, iWidth, crColor) ;
Drawing Filled Areas
Function Figure
Rectangle Rectangle with square corners
Ellipse Ellipse
RoundRect Rectangle with rounded corners
Chord Arc on the circumference of an ellipse with endpoints connected by a chord
Pie Pie wedge defined by the circumference of an ellipse
Polygon Multisided figure
PolyPolygon Multiple multisided figures
Brushing the Interior
hBrush = CreateHatchBrush (iHatchStyle, crColor) ;
The GDI Mapping Mode
Increasing Value
Mapping Mode Logical Unit x-axis y-axis
MM_TEXT Pixel Right Down
MM_LOMETRIC 0.1 mm Right Up
MM_HIMETRIC 0.01 mm Right Up
MM_LOENGLISH 0.01 in. Right Up
MM_HIENGLISH 0.001 in. Right Up
MM_TWIPS 1/1440 in. Right Up
MM_ISOTROPIC Arbitrary (x = y) Selectable Selectable
MM_ANISOTROPIC Arbitrary (x !=y)
Selectable Selectable
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.
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).
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
Working with MM_TEXT
SetViewportOrgEx (hdc, cxClient / 2, cyClient / 2, NULL) ;
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.
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.
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
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.
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) ;
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 Value New Region
RGN_AND Overlapping area of the two source regions
RGN_OR All of the two source regions
RGN_XOR All of the two source regions, excluding the overlapping area
RGN_DIFF All of hSrcRgn1 not in hSrcRgn2
RGN_COPY All of hSrcRgn1 (ignores hSrcRgn2)
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) ;
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.