GDI+

Purpose

GDI+ is a class-based application programming interface (API) for C/C++ programmers. It enables applications to use graphics and formatted text on both the video display and the printer. Applications based on the Microsoft® Win32® API do not access graphics hardware directly. Instead, GDI+ interacts with device drivers on behalf of applications. GDI+ is also supported by the 64-bit Windows® operating system.

Where Applicable

GDI+ can be used in all Windows-based applications. GDI+ is new technology that is included in the Microsoft® Windows® XP and Windows .NET Server operating systems. It is required as a redistributable for applications that run on the Windows NT® 4.0 SP6, Windows 2000, Windows 98, and Windows Millennium Edition operating systems.

Developer Audience

The GDI+ C++ class-based interface is designed for use by C/C++ programmers. Familiarity with the Windows graphical user interface and message-driven architecture is required.

Run-time Requirements

The Gdiplus.dll must be copied to the system directory of the user's computer. For information about which operating systems are required to use a particular class or method, see the Requirements section of the documentation for the class or method. GDI+ is available as a redistributable for Windows NT 4.0 SP6, Windows 2000, Windows 98, and Windows Me. To download the latest redistributable, go to http://www.microsoft.com/msdownload/platformsdk/sdkupdate/psdkredist.htm.

See Also

Windows GDI

DirectX

Image Color Management (ICM)

OpenGL

Windows Multimedia

Overview

General information about GDI+.

Using

Tasks and examples using GDI+.

Reference

Documentation of GDI+ C++ class-based API.

Feedback

Make error reports and feature requests directly to Microsoft.

Platform SDK Release: August 2001
What did you think of this topic?
Let us know. 		Order a Platform SDK CD Online
(U.S/Canada) (International)


Legal Information

GDI+

Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

© 2001 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ClearType, DirectDraw, DirectX, and Win32 are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

Portions © Japan Electronic Industry Development Association (JEIDA) from the Exchangeable Image File (Exif) Format Specification. Reprinted with permission of JEIDA.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.


About GDI+

GDI+ is the portion of the Microsoft® Windows® XP operating system or Microsoft Windows .NET Server operating system that provides two-dimensional vector graphics, imaging, and typography. GDI+ improves on GDI (the graphics device interface included with earlier versions of Windows) by adding new features and by optimizing existing features.

The following topics provide information about the GDI+ API with the C++ programming language:

  • Introduction to GDI+
  • What's New in GDI+?
  • Lines, Curves, and Shapes
  • Images, Bitmaps, and Metafiles
  • Coordinate Systems and Transformations
  • Graphics Containers


Introduction to GDI+

GDI+ is a graphics device interface that allows programmers to write device-independent applications. The services of GDI+ are exposed through a set of C++ classes.

  • Overview of GDI+
  • The Three Parts of GDI+
  • The Structure of the Class-Based Interface


Overview of GDI+

GDI+ is the subsystem of the Microsoft Windows XP operating system or Microsoft Windows .NET Server operating system that is responsible for displaying information on screens and printers. GDI+ is an application programming interface (API) that is exposed through a set of C++ classes.

As its name suggests, GDI+ is the successor to GDI, the graphics device interface included with earlier versions of Windows. Windows XP or Windows .NET Server supports GDI for compatibility with existing applications, but programmers of new applications should use GDI+ for all their graphics needs because GDI+ optimizes many of the capabilities of GDI and also provides additional features.

A graphics device interface, such as GDI+, allows application programmers to display information on a screen or printer without having to be concerned about the details of a particular display device. The application programmer makes calls to methods provided by GDI+ classes and those methods in turn make the appropriate calls to specific device drivers. GDI+ insulates the application from the graphics hardware, and it is this insulation that allows developers to create device-independent applications.


The Three Parts of GDI+

The services of GDI+ fall into the following three broad categories:

  • 2-D vector graphics
  • Imaging
  • Typography

2-D vector graphics

Vector graphics involves drawing primitives (such as lines, curves, and figures) that are specified by sets of points on a coordinate system. For example, a straight line can be specified by its two endpoints, and a rectangle can be specified by a point giving the location of its upper-left corner and a pair of numbers giving its width and height. A simple path can be specified by an array of points to be connected by straight lines. A Bézier spline is a sophisticated curve specified by four control points.

GDI+ provides classes that store information about the primitives themselves, classes that store information about how the primitives are to be drawn, and classes that actually do the drawing. For example, the Rect class stores the location and size of a rectangle; the Pen class stores information about line color, line width, and line style; and the Graphics class has methods for drawing lines, rectangles, paths, and other figures. There are also several Brush classes that store information about how closed figures and paths are to be filled with colors or patterns.

Imaging

Certain kinds of pictures are difficult or impossible to display with the techniques of vector graphics. For example, the pictures on toolbar buttons and the pictures that appear as icons would be difficult to specify as collections of lines and curves. A high-resolution digital photograph of a crowded baseball stadium would be even more difficult to create with vector techniques. Images of this type are stored as bitmaps, arrays of numbers that represent the colors of individual dots on the screen. Data structures that store information about bitmaps tend to be more complex than those required for vector graphics, so there are several classes in GDI+ devoted to this purpose. An example of such a class is CachedBitmap, which is used to store a bitmap in memory for fast access and display.

Typography

Typography is concerned with the display of text in a variety of fonts, sizes, and styles. GDI+ provides an impressive amount of support for this complex task. One of the new features in GDI+ is subpixel antialiasing, which gives text rendered on an LCD screen a smoother appearance.


The Structure of the Class-Based Interface

The C++ interface to GDI+ contains about 40 classes, 50 enumerations, and 6 structures. There are also a few functions that are not members of any class. The Graphics class is the core of the GDI+ interface; it is the class that actually draws lines, curves, figures, images, and text.

Many classes work together with the Graphics class. For example, the Graphics::DrawLine method receives a pointer to a Pen object, which holds attributes (color, width, dash style, and the like) of the line to be drawn. The Graphics::FillRectangle method can receive a pointer to a LinearGradientBrush object, which works with the Graphics object to fill a rectangle with a gradually changing color. Font and StringFormat objects influence the way a Graphics object draws text. A Matrix object stores and manipulates the world transformation of a Graphics object, which is used to rotate, scale, and flip images.

Certain classes serve primarily as structured data types. Some of those classes (for example, Rect, Point, and Size) are for general purposes. Others are for specialized purposes and are considered helper classes. For example, the BitmapData class is a helper for the Bitmap class, and the PathData class is a helper for the GraphicsPath class. GDI+ also defines a few structures that are used for organizing data. For example, the ColorMap structure holds a pair of Color objects that form one entry in a color conversion table.

GDI+ defines several enumerations, which are collections of related constants. For example, the LineJoin enumeration contains the elements Bevel, Miter, and Round, which specify styles that can be used to join two lines.

GDI+ provides a few functions that are not part of any class. Two of those functions are GdiplusStartup and GdiplusShutdown. You must call GdiplusStartup before you make any other GDI+ calls, and you must call GdiplusShutdown when you have finished using GDI+.


What's New In GDI+?

GDI+ is different from GDI in a couple of ways. First, GDI+ expands on the features of GDI by providing new capabilities, such as gradient brushes and alpha blending. Second, the programming model has been revised to make graphics programming easier and more flexible.

  • New Features
  • Changes in the Programming Model


New Features

The following sections describe several of the new features in GDI+.

Gradient Brushes

GDI+ expands on GDI by providing linear gradient and path gradient brushes for filling shapes, paths, and regions. Gradient brushes can also be used to draw lines, curves, and paths. When you fill a shape with a linear gradient brush, the color gradually changes as you move across the shape. For example, suppose you create a horizontal gradient brush by specifying blue at the left edge of a shape and green at the right edge. When you fill that shape with the horizontal gradient brush, it will gradually change from blue to green as you move from its left edge to its right edge. Similarly, a shape filled with a vertical gradient brush will change color as you move from top to bottom. The following illustration shows an ellipse filled with a horizontal gradient brush and a region filled with a diagonal gradient brush.

When you fill a shape with a path gradient brush, you have a variety of options for specifying how the colors change as you move from one portion of the shape to another. One option is to have a center color and a boundary color so that the pixels change gradually from one color to the other as you move from the middle of the shape towards the outer edges. The following illustration shows a path (created from a pair of Bézier splines) filled with a path gradient brush.

Cardinal Splines

GDI+ supports cardinal splines, which are not supported in GDI. A cardinal spline is a sequence of individual curves joined to form a larger curve. The spline is specified by an array of points and passes through each point in that array. A cardinal spline passes smoothly (no sharp corners) through each point in the array and thus is more refined than a path created by connecting straight lines. The following illustration shows two paths, one created by connecting straight lines and one created as a cardinal spline.

Independent Path Objects

In GDI, a path belongs to a device context, and the path is destroyed as it is drawn. With GDI+, drawing is performed by a Graphics object, and you can create and maintain several GraphicsPath objects that are separate from the Graphics object. A GraphicsPath object is not destroyed by the drawing action, so you can use the same GraphicsPath object to draw a path several times.

Transformations and the Matrix Object

GDI+ provides the Matrix object, a powerful tool that makes transformations (rotations, translations, and so on) easy and flexible. A matrix object works in conjunction with the objects that are transformed. For example, a GraphicsPath object has a Transform method that receives the address of a Matrix object as an argument. A single 3×3 matrix can store one transformation or a sequence of transformations. The following illustration shows a path before and after a sequence of two transformations (first scale, then rotate).

Scalable Regions

GDI+ expands greatly on GDI with its support for regions. In GDI, regions are stored in device coordinates, and the only transformation that can be applied to a region is a translation. GDI+ stores regions in world coordinates and allows a region to undergo any transformation (scaling, for example) that can be stored in a transformation matrix. The following illustration shows a region before and after a sequence of three transformations: scale, rotate, and translate.

Alpha Blending

Note that in the previous figure, you can see the untransformed region (filled with red) through the transformed region (filled with a hatch brush). This is made possible by alpha blending, which is supported by GDI+. With alpha blending, you can specify the transparency of a fill color. A transparent color is blended with the background color — the more transparent you make a fill color, the more the background shows through. The following illustration shows four ellipses that are filled with the same color (red) at different transparency levels.

Support for Multiple Image Formats

GDI+ provides the Image, Bitmap, and Metafile classes, which allow you to load, save and manipulate images in a variety of formats. The following formats are supported:

  • BMP
  • GIF
  • JPEG
  • Exif
  • PNG
  • TIFF
  • ICON
  • WMF
  • EMF


Changes in the Programming Model

The following sections describe several ways that programming with GDI+ is different from programming with GDI.

Device Contexts, Handles, and Graphics Objects

If you have written programs using GDI (the graphics device interface included in previous versions of Windows), you are familiar with the idea of a device context (DC). A device context is a structure used by Windows to store information about the capabilities of a particular display device and attributes that specify how items will be drawn on that device. A device context for a video display is also associated with a particular window on the display. First you obtain a handle to a device context (HDC), and then you pass that handle as an argument to GDI functions that actually do the drawing. You also pass the handle as an argument to GDI functions that obtain or set the attributes of the device context.

When you use GDI+, you don't have to be as concerned with handles and device contexts as you do when you use GDI. You simply create a Graphics object and then invoke its methods in the familiar object-oriented style — myGraphicsObject.DrawLine(parameters). The Graphics object is at the core of GDI+ just as the device context is at the core of GDI. The device context and the Graphics object play similar roles, but there are some fundamental differences between the handle-based programming model used with device contexts (GDI) and the object-oriented model used with Graphics objects (GDI+).

The Graphics object, like the device context, is associated with a particular window on the screen and contains attributes (for example, smoothing mode and text rendering hint) that specify how items are to be drawn. However, the Graphics object is not tied to a pen, brush, path, image, or font as a device context is. For example, in GDI, before you can use a device context to draw a line, you must call SelectObject to associate a pen object with the device context. This is referred to as selecting the pen into the device context. All lines drawn in the device context will use that pen until you select a different pen. With GDI+, you pass a Pen object as an argument to the DrawLine method of the Graphics class. You can use a different Pen object in each of a series of DrawLine calls without having to associate a given Pen object with a Graphics object.

Two Ways to Draw a Line

The following two examples each draw a red line of width 3 from location (20, 10) to location (200,100). The first example calls GDI, and the second calls GDI+ through the C++ class interface.

Drawing a line with GDI

To draw a line with GDI, you need two objects: a device context and a pen. You get a handle to a device context by calling BeginPaint, and you get a handle to a pen by calling CreatePen. Next, you call SelectObject to select the pen into the device context. You set the pen position to (20, 10) by calling MoveToEx and then draw a line from that pen position to (200, 100) by calling LineTo. Note that MoveToEx and LineTo both receive hdc (the handle to the device context) as an argument.

HDC          hdc;
PAINTSTRUCT  ps;
HPEN         hPen;
HPEN         hPenOld;

hdc = BeginPaint(hWnd, &ps);
   hPen = CreatePen(PS_SOLID, 3, RGB(255, 0, 0));
   hPenOld = (HPEN)SelectObject(hdc, hPen);
   MoveToEx(hdc, 20, 10, NULL);
   LineTo(hdc, 200, 100);
   SelectObject(hdc, hPenOld);
   DeleteObject(hPen);
EndPaint(hWnd, &ps);

Drawing a line with GDI+ and the C++ class interface

To draw a line with GDI+ and the C++ class interface, you need a Graphics object and a Pen object. Note that you don't ask Windows for handles to these objects. Instead, you use constructors to create an instance of the Graphics class (a Graphics object) and an instance of the Pen class (a Pen object). Drawing a line involves calling the DrawLine method of the Graphics class. The first parameter of the DrawLine method is a pointer to your Pen object. This is a simpler and more flexible scheme than selecting a pen into a device context as shown in the preceding GDI example.

HDC          hdc;
PAINTSTRUCT  ps;
Pen*         myPen;
Graphics*    myGraphics;

hdc = BeginPaint(hWnd, &ps);
   myPen = new Pen(Color(255, 255, 0, 0), 3);
   myGraphics = new Graphics(hdc);
   myGraphics->DrawLine(myPen, 20, 10, 200, 100);
   delete myGraphics;
   delete myPen;
EndPaint(hWnd, &ps);

Pens, Brushes, Paths, Images, and Fonts as Parameters

The preceding examples show that Pen objects can be created and maintained separately from the Graphics object, which supplies the drawing methods. Brush, GraphicsPath, Image, and Font objects can also be created and maintained separately from the Graphics object. Many of the drawing methods provided by the Graphics class receive a Brush, GraphicsPath, Image, or Font object as an argument. For example, the address of a Brush object is passed as an argument to the FillRectangle method, and the address of a GraphicsPath object is passed as an argument to the DrawPath method. Similarly, addresses of Image and Font objects are passed to the DrawImage and DrawString methods. This is in contrast to GDI where you select a brush, path, image, or font into the device context and then pass a handle to the device context as an argument to a drawing function.

Method Overloading

Many of the GDI+ methods are overloaded; that is, several methods share the same name but have different parameter lists. For example, the DrawLine method of the Graphics class comes in the following forms:

Status DrawLine(IN const Pen* pen,
                IN REAL x1,
                IN REAL y1,
                IN REAL x2,
                IN REAL y2);

Status DrawLine(IN const Pen* pen,
                IN const PointF& pt1,
                IN const PointF& pt2);

Status DrawLine(IN const Pen* pen,
                IN INT x1,
                IN INT y1,
                IN INT x2,
                IN INT y2);

Status DrawLine(IN const Pen* pen,
                IN const Point& pt1,
                IN const Point& pt2);

All four of the DrawLine variations above receive a pointer to a Pen object, the coordinates of the starting point, and the coordinates of the ending point. The first two variations receive the coordinates as floating point numbers, and the last two variations receive the coordinates as integers. The first and third variations receive the coordinates as a list of four separate numbers, while the second and fourth variations receive the coordinates as a pair of Point (or PointF) objects.

No More Current Position

Note that in the DrawLine methods shown previously both the starting point and the ending point of the line are received as arguments. This is a departure from the GDI scheme where you call MoveToEx(hdc, x1, y1, NULL) to set the current pen position followed by LineTo(hdc, x2, y2) to draw a line starting at (x1, y1) and ending at (x2, y2). GDI+ as a whole has abandoned the notion of current position.

Separate Methods for Draw and Fill

GDI+ is more flexible than GDI when it comes to drawing the outlines and filling the interiors of shapes like rectangles. GDI has a Rectangle function that draws the outline and fills the interior of a rectangle all in one step. The outline is drawn with the currently selected pen, and the interior is filled with the currently selected brush.

hBrush = CreateHatchBrush(HS_CROSS, RGB(0, 0, 255));
hPen = CreatePen(PS_SOLID, 3, RGB(255, 0, 0));
SelectObject(hdc, hBrush);
SelectObject(hdc, hPen);
Rectangle(hdc, 100, 50, 200, 80);

GDI+ has separate methods for drawing the outline and filling the interior of a rectangle. The DrawRectangle method of the Graphics class has the address of a Pen object as one of its parameters, and the FillRectangle method has the address of a Brush object as one of its parameters.

HatchBrush* myHatchBrush = new HatchBrush(
   HatchStyleCross,
   Color(255, 0, 255, 0),
   Color(255, 0, 0, 255));
Pen* myPen = new Pen(Color(255, 255, 0, 0), 3);
myGraphics.FillRectangle(myHatchBrush, 100, 50, 100, 30);
myGraphics.DrawRectangle(myPen, 100, 50, 100, 30);

Note that the FillRectangle and DrawRectangle methods in GDI+ receive arguments that specify the rectangle's left edge, top, width, and height. This is in contrast to the GDI Rectangle function, which takes arguments that specify the rectangle's left edge, right edge, top, and bottom. Also note that the constructor for the Color class in GDI+ has four parameters. The last three parameters are the usual red, green, and blue values; the first parameter is the alpha value, which specifies the extent to which the color being drawn is blended with the background color.

Constructing Regions

GDI provides several functions for creating regions: CreateRectRgn, CreateEllpticRgn, CreateRoundRectRgn, CreatePolygonRgn, and CreatePolyPolygonRgn. You might expect the Region class in GDI+ to have analogous constructors that take rectangles, ellipses, rounded rectangles, and polygons as arguments, but that is not the case. The Region class in GDI+ provides a constructor that receives a Rect object reference and another constructor that receives the address of a GraphicsPath object. If you want to construct a region based on an ellipse, rounded rectangle, or polygon, you can easily do so by creating a GraphicsPath object (that contains an ellipse, for example) and then passing the address of that GraphicsPath object to a Region constructor.

GDI+ makes it easy to form complex regions by combining shapes and paths. The Region class has Union and Intersect methods that you can use to augment an existing region with a path or another region. One nice feature of the GDI+ scheme is that a GraphicsPath object is not destroyed when it is passed as an argument to a Region constructor. In GDI, you can convert a path to a region with the PathToRegion function, but the path is destroyed in the process. Also, a GraphicsPath object is not destroyed when its address is passed as an argument to a Union or Intersect method, so you can use a given path as a building block for several separate regions. This is shown in the following example. Assume that onePath is a pointer to a GraphicsPath object (simple or complex) that has already been initialized.

Region  region1(rect1);
Region  region2(rect2);

region1.Union(onePath);
region2.Intersect(onePath);


Lines, Curves, and Shapes

The vector graphics portion of GDI+ is used to draw lines, to draw curves, and to draw and fill shapes.

  • Overview of Vector Graphics
  • Pens, Lines, and Rectangles
  • Ellipses and Arcs
  • Polygons
  • Cardinal Splines
  • Bézier Splines
  • Paths
  • Brushes and Filled Shapes
  • Open and Closed Curves
  • Regions
  • Clipping
  • Flattening Paths
  • Antialiasing with Lines and Curves


Overview of Vector Graphics

GDI+ draws lines, rectangles, and other figures on a coordinate system. You can choose from a variety of coordinate systems, but the default coordinate system has the origin in the upper left corner with the x-axis pointing to the right and the y-axis pointing down. The unit of measure in the default coordinate system is the pixel.

A computer monitor creates its display on a rectangular array of dots called picture elements or pixels. The number of pixels appearing on the screen varies from one monitor to the next, and the number of pixels appearing on an individual monitor can usually be configured to some extent by the user.

When you use GDI+ to draw a line, rectangle, or curve, you provide certain key information about the item to be drawn. For example, you can specify a line by providing two points, and you can specify a rectangle by providing a point, a height, and a width. GDI+ works in conjunction with the display driver software to determine which pixels must be turned on to show the line, rectangle, or curve. The following illustration shows the pixels that are turned on to display a line from the point (4, 2) to the point (12, 8).

Over time, certain basic building blocks have proven to be the most useful for creating two-dimensional pictures. These building blocks, which are all supported by GDI+, are given in the following list:

  • Lines
  • Rectangles
  • Ellipses
  • Arcs
  • Polygons
  • Cardinal splines
  • Bézier splines

The Graphics class in GDI+ provides the following methods for drawing the items in the previous list: DrawLine, DrawRectangle, DrawEllipse, DrawPolygon, DrawArc, DrawCurve (for cardinal splines), and DrawBezier. Each of these methods is overloaded; that is, each method comes in several variations with different parameter lists. For example, one variation of the DrawLine method receives the address of a Pen object and four integers, while another variation of the DrawLine method receives the address of a Pen object and two Point object references.

The methods for drawing lines, rectangles, and Bézier splines have plural companion methods that draw several items in a single call: DrawLines, DrawRectangles, and DrawBeziers. Also, the DrawCurve method has a companion method, DrawClosedCurve, that closes a curve by connecting the ending point of the curve to the starting point.

All the drawing methods of the Graphics class work in conjunction with a Pen object. Thus, in order to draw anything, you must create at least two objects: a Graphics object and a Pen object. The Pen object stores attributes of the item to be drawn, such as line width and color. The address of the Pen object is passed as one of the arguments to the drawing method. For example, one variation of the DrawRectangle method receives the address of a Pen object and four integers as shown in the following code, which draws a rectangle with a width of 100, a height of 50 and an upper-left corner of (20, 10).

myGraphics.DrawRectangle(&myPen, 20, 10, 100, 50);


Pens, Lines, and Rectangles

To draw lines with GDI+ you need to create a Graphics object and a Pen object. The Graphics object provides the methods that actually do the drawing, and the Pen object stores attributes of the line, such as color, width, and style. Drawing a line is simply a matter of calling the DrawLine method of the Graphics object. The address of the Pen object is passed as one of the arguments to the DrawLine method. The following example draws a line from the point (4, 2) to the point (12, 6).

myGraphics.DrawLine(&myPen, 4, 2, 12, 6);

DrawLine is an overloaded method of the Graphics class, so there are several ways you can supply it with arguments. For example, you can construct two Point objects and pass references to the Point objects as arguments to the DrawLine method.

Point myStartPoint(4, 2);
Point myEndPoint(12, 6);
myGraphics.DrawLine(&myPen, myStartPoint, myEndPoint);

You can specify certain attributes when you construct a Pen object. For example, one Pen constructor allows you to specify color and width. The following example draws a blue line of width 2 from (0, 0) to (60, 30).

Pen myPen(Color(255, 0, 0, 255), 2);
myGraphics.DrawLine(&myPen, 0, 0, 60, 30);

The Pen object also has attributes, such as dash style, that you can use to specify features of the line. For example, the following example draws a dashed line from (100, 50) to (300, 80).

myPen.SetDashStyle(DashStyleDash);
myGraphics.DrawLine(&myPen, 100, 50, 300, 80);

You can use various methods of the Pen object to set many more attributes of the line. The SetStartCap and SetEndCap methods specify the appearance of the ends of the line; the ends can be flat, square, rounded, triangular, or a custom shape. The SetLineJoin method lets you specify whether connected lines are mitered (joined with sharp corners), beveled, rounded, or clipped. The following illustration shows lines with various cap and join styles.

Drawing rectangles with GDI+ is similar to drawing lines. To draw a rectangle, you need a Graphics object and a Pen object. The Graphics object provides a DrawRectangle method, and the Pen object stores attributes, such as line width and color. The address of the Pen object is passed as one of the arguments to the DrawRectangle method. The following example draws a rectangle with its upper-left corner at (100, 50), a width of 80, and a height of 40.

myGraphics.DrawRectangle(&myPen, 100, 50, 80, 40);

DrawRectangle is an overloaded method of the Graphics class, so there are several ways you can supply it with arguments. For example, you can construct a Rectangle object and pass a reference to the Rectangle object as an argument to the DrawRectangle method.

Rect myRect(100, 50, 80, 40);
myGraphics.DrawRectangle(&myPen, myRect);

A Rectangle object has methods for manipulating and gathering information about the rectangle. For example, the Inflate and Offset methods change the size and position of the rectangle. The IntersectsWith method tells you whether the rectangle intersects another given rectangle, and the Contains method tells you whether a given point is inside the rectangle.


Ellipses and Arcs

An ellipse is specified by its bounding rectangle. The following illustration shows an ellipse along with its bounding rectangle.

To draw an ellipse, you need a Graphics object and a Pen object. The Graphics object provides the DrawEllipse method, and the Pen object stores attributes of the ellipse, such as line width and color. The address of the Pen object is passed as one of the arguments to the DrawEllipse method. The remaining arguments passed to the DrawEllipse method specify the bounding rectangle for the ellipse. The following example draws an ellipse; the bounding rectangle has a width of 160, a height of 80, and an upper-left corner of (100, 50).

myGraphics.DrawEllipse(&myPen, 100, 50, 160, 80);

DrawEllipse is an overloaded method of the Graphics class, so there are several ways you can supply it with arguments. For example, you can construct a Rectangle object and pass a reference to the Rectangle object as an argument to the DrawEllipse method.

Rect myRect(100, 50, 160, 80);
myGraphics.DrawEllipse(&myPen, myRect);

An arc is a portion of an ellipse. To draw an arc, you call the DrawArc method of the Graphics class. The parameters of the DrawArc method are the same as the parameters of the DrawEllipse method, except that DrawArc requires a starting angle and sweep angle. The following example draws an arc with a starting angle of 30 degrees and a sweep angle of 180 degrees.

myGraphics.DrawArc(&myPen, 100, 50, 160, 80, 30, 180);

The following illustration shows the arc, the ellipse, and the bounding rectangle.


Polygons

A polygon is a closed figure with three or more straight sides. For example, a triangle is a polygon with three sides, a rectangle is a polygon with four sides, and a pentagon is a polygon with five sides. The following illustration shows several polygons.

To draw a polygon, you need a Graphics object, a Pen object, and an array of Point (or PointF) objects. The Graphics object provides the DrawPolygon method. The Pen object stores attributes of the polygon, such as line width and color, and the array of Point objects stores the points to be connected by straight lines. The addresses of the Pen object and the array of Point objects are passed as arguments to the DrawPolygon method. The following example draws a three-sided polygon. Note that there are only three points in myPointArray: (0, 0), (50, 30), and (30, 60). The DrawPolygon method automatically closes the polygon by drawing a line from (30, 60) back to the starting point (0, 0);

Point myPointArray[] =
   {Point(0, 0), Point(50, 30), Point(30, 60)};
myGraphics.DrawPolygon(&myPen, myPointArray, 3);

The following illustration shows the polygon.


Cardinal Splines

A cardinal spline is a sequence of individual curves joined to form a larger curve. The spline is specified by an array of points and a tension parameter. A cardinal spline passes smoothly through each point in the array; there are no sharp corners and no abrupt changes in the tightness of the curve. The following illustration shows a set of points and a cardinal spline that passes through each point in the set.

A physical spline is a thin piece of wood or other flexible material. Before the advent of mathematical splines, designers used physical splines to draw curves. A designer would place the spline on a piece of paper and anchor it to a given set of points. The designer could then create a curve by drawing along the spline with a pencil. A given set of points could yield a variety of curves, depending on the properties of the physical spline. For example, a spline with a high resistance to bending would produce a different curve than an extremely flexible spline.

The formulas for mathematical splines are based on the properties of flexible rods, so the curves produced by mathematical splines are similar to the curves that were once produced by physical splines. Just as physical splines of different tension will produce different curves through a given set of points, mathematical splines with different values for the tension parameter will produce different curves through a given set of points. The following illustration shows four cardinal splines passing through the same set of points. The tension is shown for each spline. Note that a tension of 0 corresponds to infinite physical tension, forcing the curve to take the shortest way (straight lines) between points. A tension of 1 corresponds to no physical tension, allowing the spline to take the path of least total bend. With tension values greater than 1, the curve behaves like a compressed spring, pushed to take a longer path.

Note that the four splines in the preceding figure share the same tangent line at the starting point. The tangent is the line drawn from the starting point to the next point along the curve. Likewise, the shared tangent at the ending point is the line drawn from the ending point to the previous point on the curve.

To draw a cardinal spline, you need a Graphics object, a Pen object, and an array of Point objects. The Graphics object provides the DrawCurve method, which draws the spline, and the Pen object stores attributes of the spline, such as line width and color. The array of Point objects stores the points that the curve will pass through. The following example draws a cardinal spline that passes through the points in myPointArray. The third parameter is the tension.

myGraphics.DrawCurve(&myPen, myPointArray, 3, 1.5f);


Bézier Splines

A Bézier spline is a curve specified by four points: two end points (p1 and p2) and two control points (c1 and c2). The curve begins at p1 and ends at p2. The curve doesn't pass through the control points, but the control points act as magnets, pulling the curve in certain directions and influencing the way the curve bends. The following illustration shows a Bézier curve along with its endpoints and control points.

Note that the curve starts at p1 and moves toward the control point c1. The tangent line to the curve at p1 is the line drawn from p1 to c1. Also note that the tangent line at the endpoint p2 is the line drawn from c2 to p2.

To draw a Bézier spline, you need a Graphics object and a Pen object. The Graphics object provides the DrawBezier method, and the Pen object stores attributes of the curve, such as line width and color. The address of the Pen object is passed as one of the arguments to the DrawBezier method. The remaining arguments passed to the DrawBezier method are the endpoints and the control points. The following example draws a Bézier spline with starting point (0, 0), control points (40, 20) and (80, 150), and ending point (100, 10).

myGraphics.DrawBezier(&myPen, 0, 0, 40, 20, 80, 150, 100, 10);

The following illustration shows the curve, the control points, and two tangent lines.

Bézier splines were originally developed by Pierre Bézier for design in the automotive industry. They have since proven to be very useful in many types of computer-aided design and are also used to define the outlines of fonts. Bézier splines can yield a wide variety of shapes, some of which are shown in the following illustration.


Paths

Paths are formed by combining lines, rectangles, and simple curves. Recall from the Overview of Vector Graphics that the following basic building blocks have proven to be the most useful for drawing pictures.

  • Lines
  • Rectangles
  • Ellipses
  • Arcs
  • Polygons
  • Cardinal splines
  • Bézier splines

In GDI+, the GraphicsPath object allows you to collect a sequence of these building blocks into a single unit. The entire sequence of lines, rectangles, polygons, and curves can then be drawn with one call to the DrawPath method of the Graphics class. The following illustration shows a path created by combining a line, an arc, a Bézier spline, and a cardinal spline.

The GraphicsPath class provides the following methods for creating a sequence of items to be drawn: AddLine, AddRectangle, AddEllipse, AddArc, AddPolygon, AddCurve (for cardinal splines), and AddBezier. Each of these methods is overloaded; that is, each method comes in several variations with different parameter lists. For example, one variation of the AddLine method receives four integers, and another variation of the AddLine method receives two Point objects.

The methods for adding lines, rectangles, and Bézier splines to a path have plural companion methods that add several items to the path in a single call: AddLines, AddRectangles, and AddBeziers. Also, the AddCurve method has a companion method, AddClosedCurve, that adds a closed curve to the path.

To draw a path, you need a Graphics object, a Pen object, and a GraphicsPath object. The Graphics object provides the DrawPath method, and the Pen object stores attributes of the path, such as line width and color. The GraphicsPath object stores the sequence of lines, rectangles, and curves that make up the path. The addresses of the Pen object and the GraphicsPath object are passed as arguments to the DrawPath method. The following example draws a path that consists of a line, an ellipse, and a Bézier spline.

myGraphicsPath.AddLine(0, 0, 30, 20);
myGraphicsPath.AddEllipse(20, 20, 20, 40);
myGraphicsPath.AddBezier(30, 60, 70, 60, 50, 30, 100, 10);
myGraphics.DrawPath(&myPen, &myGraphicsPath);

The following illustration shows the path.

In addition to adding lines, rectangles, and curves to a path, you can add paths to a path. This allows you to combine existing paths to form large, complex paths. The following code adds graphicsPath1 and graphicsPath2 to myGraphicsPath. The second parameter of the AddPath method specifies whether the added path is connected to the existing path.

myGraphicsPath.AddPath(&graphicsPath1, FALSE);
myGraphicsPath.AddPath(&graphicsPath2, TRUE);

There are two other items you can add to a path: strings and pies. A pie is a portion of the interior of an ellipse. The following example creates a path from an arc, a cardinal spline, a string, and a pie.

myGraphicsPath.AddArc(0, 0, 30, 20, -90, 180);
myGraphicsPath.AddCurve(myPointArray, 3);
myGraphicsPath.AddString(L"a string in a path", 18, &myFontFamily,
   0, 24, myPointF, &myStringFormat);
myGraphicsPath.AddPie(230, 10, 40, 40, 40, 110);
myGraphics.DrawPath(&myPen, &myGraphicsPath);

The following illustration shows the path. Note that a path does not have to be connected; the arc, cardinal spline, string, and pie are separated.


Brushes and Filled Shapes

A closed figure such as a rectangle or an ellipse consists of an outline and an interior. The outline is drawn with a Pen object and the interior is filled with a Brush object. GDI+ provides several brush classes for filling the interiors of closed figures: SolidBrush, HatchBrush, TextureBrush, LinearGradientBrush, and PathGradientBrush. All these classes inherit from the Brush class. The following illustration shows a rectangle filled with a solid brush and an ellipse filled with a hatch brush.

Solid Brushes

To fill a closed shape, you need a Graphics object and a Brush object. The Graphics object provides methods, such as FillRectangle and FillEllipse, and the Brush object stores attributes of the fill, such as color and pattern. The address of Brush object is passed as one of the arguments to the fill method. The following example fills an ellipse with a solid red color.

SolidBrush mySolidBrush(Color(255, 255, 0, 0));
myGraphics.FillEllipse(&mySolidBrush, 0, 0, 60, 40);

Note that in the preceding example, the brush is of type SolidBrush, which inherits from Brush.

Hatch Brushes

When you fill a shape with a hatch brush, you specify a foreground color, a background color, and a hatch style. The foreground color is the color of the hatching.

HatchBrush myHatchBrush(
   HatchStyleVertical,
   Color(255, 0, 0, 255),
   Color(255, 0, 255, 0));

GDI+ provides more than 50 hatch styles; the three styles shown in the following illustration are Horizontal, ForwardDiagonal, and Cross.

Texture Brushes

With a texture brush, you can fill a shape with a pattern stored in a bitmap. For example, suppose the following picture is stored in a disk file named MyTexture.bmp.

The following example fills an ellipse by repeating the picture stored in MyTexture.bmp.

Image myImage(L"MyTexture.bmp");
TextureBrush myTextureBrush(&myImage);
myGraphics.FillEllipse(&myTextureBrush, 0, 0, 100, 50);

The following illustration shows the filled ellipse.

Gradient Brushes

You can use a gradient brush to fill a shape with a color that changes gradually from one part of the shape to another. For example, a horizontal gradient brush will change color as you move from the left side of a figure to the right side. The following example fills an ellipse with a horizontal gradient brush that changes from blue to green as you move from the left side of the ellipse to the right side.

LinearGradientBrush myLinearGradientBrush(
   myRect,
   Color(255, 0, 0, 255),
   Color(255, 0, 255, 0),
   LinearGradientModeHorizontal);
myGraphics.FillEllipse(&myLinearGradientBrush, myRect);

The following illustration shows the filled ellipse.

A path gradient brush can be configured to change color as you move from the center of a figure toward the boundary.

Path gradient brushes are quite flexible. The gradient brush used to fill the triangle in the following illustration changes gradually from red at the center to each of three different colors at the vertices.


Open and Closed Curves

The following illustration shows two curves: one open and one closed.

Closed curves have an interior and therefore can be filled with a brush. The Graphics class in GDI+ provides the following methods for filling closed figures and curves: FillRectangle, FillEllipse, FillPie, FillPolygon, FillClosedCurve, FillPath, and FillRegion. Whenever you call one of these methods, you must pass the address of one of the specific brush types (SolidBrush, HatchBrush, TextureBrush, LinearGradientBrush, or PathGradientBrush) as an argument.

The FillPie method is a companion to the DrawArc method. Just as the DrawArc method draws a portion of the outline of an ellipse, the FillPie method fills a portion of the interior of an ellipse. The following example draws an arc and fills the corresponding portion of the interior of the ellipse.

myGraphics.FillPie(&mySolidBrush, 0, 0, 140, 70, 0, 120);
myGraphics.DrawArc(&myPen, 0, 0, 140, 70, 0, 120);

The following illustration shows the arc and the filled pie.

The FillClosedCurve method is a companion to the DrawClosedCurve method. Both methods automatically close the curve by connecting the ending point to the starting point. The following example draws a curve that passes through (0, 0), (60, 20), and (40, 50). Then, the curve is automatically closed by connecting (40, 50) to the starting point (0, 0), and the interior is filled with a solid color.

Point myPointArray[] =
   {Point(10, 10), Point(60, 20),Point(40, 50)};
myGraphics.DrawClosedCurve(&myPen, myPointArray, 3);
myGraphics.FillClosedCurve(&mySolidBrush, myPointArray, 3, FillModeAlternate)

A path can consist of several figures (subpaths). The FillPath method fills the interior of each figure. If a figure is not closed, the FillPath method fills the area that would be enclosed if the figure were closed. The following example draws and fills a path that consists of an arc, a cardinal spline, a string, and a pie.

myGraphics.FillPath(&mySolidBrush, &myGraphicsPath);
myGraphics.DrawPath(&myPen, &myGraphicsPath);

The following illustration shows the path before and after it is filled with a solid brush. Note that the text in the string is outlined, but not filled, by the DrawPath method. It is the FillPath method that paints the interiors of the characters in the string.


Regions

A region is a portion of the display surface. Regions can be simple (a single rectangle) or complex (a combination of polygons and closed curves). The following illustration shows two regions: one constructed from a rectangle, and the other constructed from a path.

Regions are often used for clipping and hit testing. Clipping involves restricting drawing to a certain region of the screen, usually the portion of the screen that needs to be updated. Hit testing involves checking to see whether the cursor is in a certain region of the screen when a mouse button is pressed.

You can construct a region from a rectangle or from a path. You can also create complex regions by combining existing regions. The Region class provides the following methods for combining regions: Intersect, Union, Xor, Exclude, and Complement.

The intersection of two regions is the set of all points belonging to both regions. The union is the set of all points belonging to one or the other or both regions. The complement of a region is the set of all points that are not in the region. The following illustration shows the intersection and union of the two regions in the previous figure.

The Xor method, applied to a pair of regions, produces a region that contains all points that belong to one region or the other, but not both. The Exclude method, applied to a pair of regions, produces a region that contains all points in the first region that are not in the second region. The following illustration shows the regions that result from applying the Xor and Exclude methods to the two regions shown at the beginning of this topic.

To fill a region, you need a Graphics object, a Brush object, and a Region object. The Graphics object provides the FillRegion method, and the Brush object stores attributes of the fill, such as color or pattern. The following example fills a region with a solid color.

myGraphics.FillRegion(&mySolidBrush, &myRegion);


Clipping

Clipping involves restricting drawing to a certain region. The following illustration shows the string "Hello" clipped to a heart-shaped region.

Regions can be constructed from paths, and paths can contain the outlines of strings, so you can use outlined text for clipping. The following illustration shows a set of concentric ellipses clipped to the interior of a string of text.

To draw with clipping, create a Graphics object, call its SetClip method, and then call the drawing methods of that same Graphics object. The following example draws a line that is clipped to a rectangular region.

Region myRegion(Rect(20, 30, 100, 50));
myGraphics.DrawRectangle(&myPen, 20, 30, 100, 50);
myGraphics.SetClip(&myRegion, CombineModeReplace);
myGraphics.DrawLine(&myPen, 0, 0, 200, 200);

The following illustration shows the rectangular region along with the clipped line.


Flattening Paths

A GraphicsPath object stores a sequence of lines and Bézier splines. You can add several types of curves (ellipses, arcs, cardinal splines) to a path, but each curve is converted to a Bézier spline before it is stored in the path. Flattening a path consists of converting each Bézier spline in the path to a sequence of straight lines.

To flatten a path, call the Flatten method of a GraphicsPath object. The Flatten method receives a flatness argument that specifies the maximum distance between the flattened path and the original path. The following illustration shows a path before and after flattening.


Antialiasing with Lines and Curves

When you use GDI+ to draw a line, you provide the starting point and ending point of the line, but you don't have to provide any information about the individual pixels on the line. GDI+ works in conjunction with the display driver software to determine which pixels will be turned on to show the line on a particular display device.

Consider a straight red line that goes from the point (4, 2) to the point (16, 10). Assume the coordinate system has its origin in the upper-left corner and that the unit of measure is the pixel. Also assume that the x-axis points to the right and the y-axis points down. The following illustration shows an enlarged view of the red line drawn on a multicolored background.

Note that the red pixels used to render the line are opaque. There are no partially transparent pixels involved in displaying the line. This type of line rendering gives the line a jagged appearance, and the line looks a bit like a staircase. This technique of representing a line with a staircase is called aliasing; the staircase is an alias for the theoretical line.

A more sophisticated technique for rendering a line involves using partially transparent pixels along with pure red pixels. Pixels are set to pure red or to some blend of red and the background color depending on how close they are to the line. This type of rendering is called antialiasing and results in a line that the human eye perceives as more smooth. The following illustration shows how certain pixels are blended with the background to produce an antialiased line.

Antialiasing (smoothing) can also be applied to curves. The following illustration shows an enlarged view of a smoothed ellipse.

The following illustration shows the same ellipse in its actual size, once without antialiasing and once with antialiasing.

To draw lines and curves that use antialiasing, create a Graphics object and pass SmoothingModeAntiAlias to its SetSmoothingMode method. Then call one of the drawing methods of that same Graphics object.

myGraphics.SetSmoothingMode(SmoothingModeAntiAlias);
myGraphics.DrawLine(&myPen, 0, 0, 12, 8);

SmoothingModeAntiAlias is an element of the SmoothingMode enumeration.


Images, Bitmaps, and Metafiles

GDI+ provides the Image class for working with raster images (bitmaps) and vector images (metafiles). The Bitmap class and the Metafile class both inherit from the Image class. The Bitmap class expands on the capabilities of the Image class by providing additional methods for loading, saving, and manipulating raster images. The Metafile class expands on the capabilities of the Image class by providing additional methods for recording and examining vector images.

  • Types of Bitmaps
  • Metafiles
  • Drawing, Positioning, and Cloning Images
  • Cropping and Scaling Images


Types of Bitmaps

A bitmap is an array of bits that specifies the color of each pixel in a rectangular array of pixels. The number of bits devoted to an individual pixel determines the number of colors that can be assigned to that pixel. For example, if each pixel is represented by 4 bits, then a given pixel can be assigned one of 16 different colors (2^4 = 16). The following table shows a few examples of the number of colors that can be assigned to a pixel represented by a given number of bits.

Bits per pixel | Number of colors that can be assigned to a pixel
1 | 2^1 = 2
2 | 2^2 = 4
4 | 2^4 = 16
8 | 2^8 = 256
16 | 2^16 = 65,536
24 | 2^24 = 16, 777, 216

Disk files that store bitmaps usually contain one or more information blocks that store information such as number of bits per pixel, number of pixels in each row, and number of rows in the array. Such a file might also contain a color table (sometimes called a color palette). A color table maps numbers in the bitmap to specific colors. The following illustration shows an enlarged image along with its bitmap and color table. Each pixel is represented by a 4-bit number, so there are 2^4 = 16 colors in the color table. Each color in the table is represented by a 24-bit number: 8 bits for red, 8 bits for green, and 8 bits for blue. The numbers are shown in hexadecimal (base 16) form: A = 10, B = 11, C = 12, D = 13, E = 14, F = 15.

Look at the pixel in row 3, column 5 of the image. The corresponding number in the bitmap is 1. The color table tells us that 1 represents the color red, so the pixel is red. All the entries in the top row of the bitmap are 3. The color table tells us that 3 represents blue, so all the pixels in the top row of the image are blue.

Note Some bitmaps are stored in bottom-up format; the numbers in the first row of the bitmap correspond to the pixels in the bottom row of the image.

A bitmap that stores indexes into a color table is called a palette-indexed bitmap. Some bitmaps have no need for a color table. For example, if a bitmap uses 24 bits per pixel, that bitmap can store the colors themselves rather than indexes into a color table. The following illustration shows a bitmap that stores colors directly (24 bits per pixel) rather than using a color table. The illustration also shows an enlarged view of the corresponding image. In the bitmap, FFFFFF represents white, FF0000 represents red, 00FF00 represents green, and 0000FF represents blue.

Graphics File Formats

There are many standard formats for saving bitmaps in files. GDI+ supports the graphics file formats described in the following paragraphs.

BMP

BMP is a standard format used by Windows to store device-independent and application-independent images. The number of bits per pixel (1, 4, 8, 15, 24, 32, or 64) for a given BMP file is specified in a file header. BMP files with 24 bits per pixel are common.

Graphics Interchange Format (GIF)

GIF is a common format for images that appear on Web pages. GIFs work well for line drawings, pictures with blocks of solid color, and pictures with sharp boundaries between colors. GIFs are compressed, but no information is lost in the compression process; a decompressed image is exactly the same as the original. One color in a GIF can be designated as transparent, so that the image will have the background color of any Web page that displays it. A sequence of GIF images can be stored in a single file to form an animated GIF. GIFs store at most 8 bits per pixel, so they are limited to 256 colors.

Joint Photographic Experts Group (JPEG)

JPEG is a compression scheme that works well for natural scenes, such as scanned photographs. Some information is lost in the compression process, but often the loss is imperceptible to the human eye. Color JPEG images store 24 bits per pixel, so they are capable of displaying more than 16 million colors. There is also a grayscale JPEG format that stores 8 bits per pixel. JPEGs do not support transparency or animation.

The level of compression in JPEG images is configurable, but higher compression levels (smaller files) result in more loss of information. A 20:1 compression ratio often produces an image that the human eye finds difficult to distinguish from the original. The following illustration shows a BMP image and two JPEG images that were compressed from that BMP image. The first JPEG has a compression ratio of 4:1 and the second JPEG has a compression ratio of about 8:1.

JPEG compression does not work well for line drawings, blocks of solid color, and sharp boundaries. The following illustration shows a BMP along with two JPEGs and a GIF. The JPEGs and the GIF were compressed from the BMP. The compression ratio is 4:1 for the GIF, 4:1 for the smaller JPEG, and 8:3 for the larger JPEG. Note that the GIF maintains the sharp boundaries along the lines, but the JPEGs tends to blur the boundaries.

JPEG is a compression scheme, not a file format. JPEG File Interchange Format (JFIF) is a file format commonly used for storing and transferring images that have been compressed according to the JPEG scheme. JFIF files displayed by Web browsers use the .jpg extension.

Exchangeable Image File (Exif)

Exif is a file format used for photographs captured by digital cameras. An Exif file contains an image that is compressed according to the JPEG specification. An Exif file also contains information about the photograph (date taken, shutter speed, exposure time, and so on) and information about the camera (manufacturer, model, and so on).

Portable Network Graphics (PNG)

The PNG format retains many of the advantages of the GIF format but also provides capabilities beyond those of GIF. Like GIF files, PNG files are compressed with no loss of information. PNG files can store colors with 8, 24, or 48 bits per pixel and gray scales with 1, 2, 4, 8, or 16 bits per pixel. In contrast, GIF files can use only 1, 2, 4, or 8 bits per pixel. A PNG file can also store an alpha value for each pixel, which specifies the degree to which the color of that pixel is blended with the background color.

PNG improves on GIF in its ability to progressively display an image; that is, to display better and better approximations of the image as it arrives over a network connection. PNG files can contain gamma correction and color correction information so that the images can be accurately rendered on a variety of display devices.

Tag Image File Format (TIFF)

TIFF is a flexible and extendable format that is supported by a wide variety of platforms and image-processing applications. TIFF files can store images with an arbitrary number of bits per pixel and can employ a variety of compression algorithms. Several images can be stored in a single, multiple-page TIFF file. Information related to the image (scanner make, host computer, type of compression, orientation, samples per pixel, and so on) can be stored in the file and arranged through the use of tags. The TIFF format can be extended as needed by the approval and addition of new tags.


Metafiles

GDI+ provides the Metafile class so that you can record and display metafiles. A metafile, also called a vector image, is an image that is stored as a sequence of drawing commands and settings. The commands and settings recorded in a Metafile object can be stored in memory or saved to a file or stream.

GDI+ can display metafiles that have been stored in the following formats:

  • Windows Metafile (WMF)
  • Enhanced Metafile (EMF)
  • EMF+

GDI+ can record metafiles in the EMF and EMF+ formats, but not in the WMF format.

EMF+ is an extension to EMF that allows GDI+ records to be stored. There are two variations on the EMF+ format: EMF+ Only and EMF+ Dual. EMF+ Only metafiles contain only GDI+ records. Such metafiles can be displayed by GDI+ but not by GDI. EMF+ Dual metafiles contain GDI+ and GDI records. Each GDI+ record in an EMF+ Dual metafile is paired with an alternate GDI record. Such metafiles can be displayed by GDI+ or by GDI.

The following example records one setting and one drawing command in a disk file. Note that the example creates a Graphics object and that the constructor for the Graphics object receives the address of a Metafile object as an argument.

myMetafile = new Metafile(L"MyDiskFile.emf", hdc);
myGraphics = new Graphics(myMetafile);
   myPen = new Pen(Color(255, 0, 0, 200));
   myGraphics->SetSmoothingMode(SmoothingModeAntiAlias);
   myGraphics->DrawLine(myPen, 0, 0, 60, 40);
delete myGraphics;
delete myPen;
delete myMetafile;

As the preceding example shows, the Graphics class is the key to recording instructions and settings in a Metafile object. Any call made to a method of a Graphics object can be recorded in a Metafile object. Likewise, you can set any property of a Graphics object and record that setting in a Metafile object. The recording ends when the Graphics object is deleted or goes out of scope.

The following example displays the metafile created in the preceding example. The metafile is displayed with its upper-left corner at (100, 100).

Graphics myGraphics(hdc);
Image myImage(L"MyDiskFile.emf");
myGraphics.DrawImage(&myImage, 100, 100);

The following example records several property settings (clipping region, world transformation, and smoothing mode) in a Metafile object. Then the code records several drawing instructions. The instructions and settings are saved in a disk file.

myMetafile = new Metafile(L"MyDiskFile2.emf", hdc);
myGraphics = new Graphics(myMetafile);
   myGraphics->SetSmoothingMode(SmoothingModeAntiAlias);
   myGraphics->RotateTransform(30);

   // Create an elliptical clipping region.
   GraphicsPath myPath;
   myPath.AddEllipse(0, 0, 200, 100);
   Region myRegion(&myPath);
   myGraphics->SetClip(&myRegion);

   Pen myPen(Color(255, 0, 0, 255));
   myGraphics->DrawPath(&myPen, &myPath);

   for(INT j = 0; j <= 300; j += 10)
   {
      myGraphics->DrawLine(&myPen, 0, 0, 300 - j, j);
   }
delete myGraphics;
delete myMetafile;

The following example displays the metafile image created in the preceding example.

myGraphics = new Graphics(hdc);
myMetafile = new Metafile(L"MyDiskFile.emf");
myGraphics->DrawImage(myMetafile, 10, 10);

The following illustration shows the output of the preceding code. Note the antialiasing, the elliptical clipping region, and the 30-degree rotation.


Drawing, Positioning, and Cloning Images

You can use the Image class to load and display raster images (bitmaps) and vector images (metafiles). To display an image, you need a Graphics object and an Image object. The Graphics object provides the DrawImage method, which receives the address of the Image object as an argument.

The following example constructs an Image object from the file Climber.jpg and then displays the image. The destination point for the upper-left corner of the image, (10, 10), is specified in the second and third parameters of the DrawImage method..

Image myImage(L"Climber.jpg");
myGraphics.DrawImage(&myImage, 10, 10);

The preceding code, along with a particular file, Climber.jpg, produced the following output.

You can construct Image objects from a variety of graphics file formats: BMP, GIF, JPEG, Exif, PNG, TIFF, WMF, EMF, and ICON.

The following example constructs Image objects from a variety of file types and then displays the images.

Image myBMP(L"SpaceCadet.bmp");
Image myEMF(L"Metafile1.emf");
Image myGIF(L"Soda.gif");
Image myJPEG(L"Mango.jpg");
Image myPNG(L"Flowers.png");
Image myTIFF(L"MS.tif");

myGraphics.DrawImage(&myBMP, 10, 10);
myGraphics.DrawImage(&myEMF, 220, 10);
myGraphics.DrawImage(&myGIF, 320, 10);
myGraphics.DrawImage(&myJPEG, 380, 10);
myGraphics.DrawImage(&myPNG, 150, 200);
myGraphics.DrawImage(&myTIFF, 300, 200);

The Image class provides a Clone method that you can use to make a copy of an existing Image, Metafile, or Bitmap object. The Clone method is overloaded in the Bitmap class, and one of the variations has a source-rectangle parameter that you can use to specify the portion of the original image that you want to copy. The following example creates a Bitmap object by cloning the top half of an existing Bitmap object. Then both images are displayed.

Bitmap* originalBitmap = new Bitmap(L"Spiral.png");
RectF sourceRect(
   0.0f,
   0.0f,
   (REAL)(originalBitmap->GetWidth()),
   (REAL)(originalBitmap->GetHeight())/2.0f);

Bitmap* secondBitmap = originalBitmap->Clone(sourceRect, PixelFormatDontCare);

myGraphics.DrawImage(originalBitmap, 10, 10);
myGraphics.DrawImage(secondBitmap, 100, 10);

The preceding code, along with a particular file, Spiral.png, produced the following output.


Cropping and Scaling Images

You can use the DrawImage method of the Graphics class to draw and position images. DrawImage is an overloaded method, so there are several ways you can supply it with arguments. One variation of the DrawImage method receives the address of an Image object and a reference to a Rectangle object. The rectangle specifies the destination for the drawing operation; that is, it specifies the rectangle in which the image will be drawn. If the size of the destination rectangle is different from the size of the original image, the image is scaled to fit the destination rectangle. The following example draws the same image three times: once with no scaling, once with an expansion, and once with a compression.

Bitmap myBitmap(L"Spiral.png");
Rect expansionRect(80, 10, 2 * myBitmap.GetWidth(), myBitmap.GetHeight());
Rect compressionRect(210, 10, myBitmap.GetWidth() / 2,
   myBitmap.GetHeight() / 2);

myGraphics.DrawImage(&myBitmap, 10, 10);
myGraphics.DrawImage(&myBitmap, expansionRect);
myGraphics.DrawImage(&myBitmap, compressionRect);

The preceding code, along with a particular file, Spiral.png, produced the following output.

Some variations of the DrawImage method have a source-rectangle parameter as well as a destination-rectangle parameter. The source rectangle specifies the portion of the original image that will be drawn. The destination rectangle specifies where that portion of the image will be drawn. If the size of the destination rectangle is different from the size of the source rectangle, the image is scaled to fit the destination rectangle.

The following example constructs a Bitmap object from the file Runner.jpg. The entire image is drawn with no scaling at (0, 0). Then a small portion of the image is drawn twice: once with a compression and once with an expansion.

Bitmap myBitmap(L"Runner.jpg");

// The rectangle (in myBitmap) with upper-left corner (80, 70),
// width 80, and height 45, encloses one of the runner's hands.

// Small destination rectangle for compressed hand.
Rect destRect1(200, 10, 20, 16);

// Large destination rectangle for expanded hand.
Rect destRect2(200, 40, 200, 160);

// Draw the original image at (0, 0).
myGraphics.DrawImage(&myBitmap, 0, 0);

// Draw the compressed hand.
myGraphics.DrawImage(
   &myBitmap, destRect1, 80, 70, 80, 45, UnitPixel);

// Draw the expanded hand.
myGraphics.DrawImage(
   &myBitmap, destRect2, 80, 70, 80, 45, UnitPixel);

The following illustration shows the unscaled image, and the compressed and expanded image portions.


Coordinate Systems and Transformations

GDI+ provides a world transformation and a page transformation so that you can transform (rotate, scale, translate, and so on) the items you draw. The two transformations also allow you to work in a variety of coordinate systems.

  • Types of Coordinate Systems
  • Matrix Representation of Transformations
  • Global and Local Transformations


Types of Coordinate Systems

GDI+ uses three coordinate spaces: world, page, and device. When you make the call myGraphics.DrawLine(myPen, 0, 0, 160, 80), the points that you pass to the DrawLine method — (0, 0) and (160, 80) — are in the world coordinate space. Before GDI+ can draw the line on the screen, the coordinates pass through a sequence of transformations. One transformation converts world coordinates to page coordinates, and another transformation converts page coordinates to device coordinates.

Suppose you want to work with a coordinate system that has its origin in the body of the client area rather than the upper-left corner. Say, for example, that you want the origin to be 100 pixels from the left edge of the client area and 50 pixels from the top of the client area. The following illustration shows such a coordinate system.

When you make the call myGraphics.DrawLine(&myPen, 0, 0, 160, 80), you get the line shown in the following illustration.

The coordinates of the endpoints of your line in the three coordinate spaces are as follows:

World | (0, 0) to (160, 80)
Page | (100, 50) to (260, 130)
Device | (100, 50) to (260, 130)

Note that the page coordinate space has its origin at the upper-left corner of the client area; this will always be the case. Also note that because the unit of measure is the pixel, the device coordinates are the same as the page coordinates. If you set the unit of measure to something other than pixels (for example, inches), then the device coordinates will be different from the page coordinates.

The transformation that maps world coordinates to page coordinates is called the world transformation and is maintained by a Graphics object. In the previous example, the world transformation is a translation 100 units in the x direction and 50 units in the y direction. The following example sets the world transformation of a Graphics object and then uses that Graphics object to draw the line shown in the previous figure.

myGraphics.TranslateTransform(100.0f, 50.0f);
myGraphics.DrawLine(&myPen, 0, 0, 160, 80);

The transformation that maps page coordinates to device coordinates is called the page transformation. The Graphics class provides four methods for manipulating and inspecting the page transformation: SetPageUnit, GetPageUnit, SetPageScale, and GetPageScale. The Graphics class also provides two methods, GetDpiX and GetDpiY, for examining the horizontal and vertical dots per inch of the display device.

You can use the SetPageUnit method of the Graphics class to specify a unit of measure. The following example draws a line from (0, 0) to (2, 1) where the point (2, 1) is 2 inches to the right and 1 inch down from the point (0, 0).

myGraphics.SetPageUnit(UnitInch);
myGraphics.DrawLine(&myPen, 0, 0, 2, 1);

Note If you don't specify a pen width when you construct your pen, the previous example will draw a line that is one inch wide. You can specify the pen width in the second argument to the Pen constructor:

Pen myPen(Color(255, 0, 0, 0), 1/myGraphics.GetDpiX()).

If we assume that the display device has 96 dots per inch in the horizontal direction and 96 dots per inch in the vertical direction, the endpoints of the line in the previous example have the following coordinates in the three coordinate spaces:

World | (0, 0) to (2, 1)
Page | (0, 0) to (2, 1)
Device | (0, 0, to (192, 96)

You can combine the world and page transformations to achieve a variety of effects. For example, suppose you want to use inches as the unit of measure and you want the origin of your coordinate system to be 2 inches from the left edge of the client area and 1/2 inch from the top of the client area. The following example sets the world and page transformations of a Graphics object and then draws a line from (0, 0) to (2, 1).

myGraphics.TranslateTransform(2.0f, 0.5f);
myGraphics.SetPageUnit(UnitInch);
myGraphics.DrawLine(&myPen, 0, 0, 2, 1);

The following illustration shows the line and coordinate system.

If we assume that the display device has 96 dots per inch in the horizontal direction and 96 dots per inch in the vertical direction, the endpoints of the line in the previous example have the following coordinates in the three coordinate spaces:

World | (0, 0) to (2, 1)
Page | (2, 0.5) to (4, 1.5)
Device | (192, 48) to (384, 144)


Matrix Representation of Transformations

An m×n matrix is a set of numbers arranged in m rows and n columns. The following illustration shows several matrices.

You can add two matrices of the same size by adding individual elements. The following illustration shows two examples of matrix addition.

An m×n matrix can be multiplied by an n×p matrix, and the result is an m×p matrix. The number of columns in the first matrix must be the same as the number of rows in the second matrix. For example, a 4×2 matrix can be multiplied by a 2×3 matrix to produce a 4×3 matrix.

Points in the plane and rows and columns of a matrix can be thought of as vectors. For example, (2, 5) is a vector with two components, and (3, 7, 1) is a vector with three components. The dot product of two vectors is defined as follows:

(a, b) • (c, d) = ac + bd

(a, b, c) • (d, e, f) = ad + be + cf

For example, the dot product of (2, 3) and (5, 4) is (2)(5) + (3)(4) = 22. The dot product of (2, 5, 1) and (4, 3, 1) is (2)(4) + (5)(3) + (1)(1) = 24. Note that the dot product of two vectors is a number, not another vector. Also note that you can calculate the dot product only if the two vectors have the same number of components.

Let A(i, j) be the entry in matrix A in the ith row and the jth column. For example A(3, 2) is the entry in matrix A in the 3rd row and the 2nd column. Suppose A, B, and C are matrices, and AB = C. The entries of C are calculated as follows:

C(i, j) = (row i of A) • (column j of B)

The following illustration shows several examples of matrix multiplication.

If you think of a point in the plane as a 1×2 matrix, you can transform that point by multiplying it by a 2×2 matrix. The following illustration shows several transformations applied to the point (2, 1).

All the transformations shown in the previous figure are linear transformations. Certain other transformations, such as translation, are not linear, and cannot be expressed as multiplication by a 2×2 matrix. Suppose you want to start with the point (2, 1), rotate it 90 degrees, translate it 3 units in the x direction, and translate it 4 units in the y direction. You can accomplish this by performing a matrix multiplication followed by a matrix addition.

A linear transformation (multiplication by a 2×2 matrix) followed by a translation (addition of a 1×2 matrix) is called an affine transformation. An alternative to storing an affine transformation in a pair of matrices (one for the linear part and one for the translation) is to store the entire transformation in a 3×3 matrix. To make this work, a point in the plane must be stored in a 1×3 matrix with a dummy 3rd coordinate. The usual technique is to make all 3rd coordinates equal to 1. For example, the point (2, 1) is represented by the matrix [2 1 1]. The following illustration shows an affine transformation (rotate 90 degrees; translate 3 units in the x direction, 4 units in the y direction) expressed as multiplication by a single 3×3 matrix.

In the previous example, the point (2, 1) is mapped to the point (2, 6). Note that the third column of the 3×3 matrix contains the numbers 0, 0, 1. This will always be the case for the 3×3 matrix of an affine transformation. The important numbers are the six numbers in columns 1 and 2. The upper-left 2×2 portion of the matrix represents the linear part of the transformation, and the first two entries in the 3rd row represent the translation.

In GDI+ you can store an affine transformation in a Matrix object. Because the third column of a matrix that represents an affine transformation is always (0, 0, 1), you specify only the six numbers in the first two columns when you construct a Matrix object. The statement Matrix myMatrix(0.0f, 1.0f, -1.0f, 0.0f, 3.0f, 4.0f); constructs the matrix shown in the previous figure.

Composite Transformations

A composite transformation is a sequence of transformations, one followed by the other. Consider the matrices and transformations in the following list:

Matrix A Rotate 90 degrees

Matrix B Scale by a factor of 2 in the x direction

Matrix C Translate 3 units in the y direction

If we start with the point (2, 1) — represented by the matrix [2 1 1] — and multiply by A, then B, then C, the point (2,1) will undergo the three transformations in the order listed.

[2 1 1]ABC = [–2 5 1]

Rather than store the three parts of the composite transformation in three separate matrices, you can multiply A, B, and C together to get a single 3×3 matrix that stores the entire composite transformation. Suppose ABC = D. Then a point multiplied by D gives the same result as a point multiplied by A, then B, then C.

[2 1 1]D = [–2 5 1]

The following illustration shows the matrices A, B, C, and D.

The fact that the matrix of a composite transformation can be formed by multiplying the individual transformation matrices means that any sequence of affine transformations can be stored in a single Matrix object.

Caution The order of a composite transformation is important. In general, rotate, then scale, then translate is not the same as scale, then rotate, then translate. Similarly, the order of matrix multiplication is important. In general, ABC is not the same as BAC.

The Matrix class provides several methods for building a composite transformation: Multiply, Rotate, RotateAt, Scale, Shear, and Translate. The following example creates the matrix of a composite transformation that first rotates 30 degrees, then scales by a factor of 2 in the y direction, and then translates 5 units in the x direction.

Matrix myMatrix;
myMatrix.Rotate(30.0f);
myMatrix.Scale(1.0f, 2.0f, MatrixOrderAppend);
myMatrix.Translate(5.0f, 0.0f, MatrixOrderAppend);

The following illustration shows the matrix.


Global and Local Transformations

A global transformation is a transformation that applies to every item drawn by a given Graphics object. To create a global transformation, construct a Graphics object, and then call its SetTransform method. The SetTransform method manipulates a Matrix object that is associated with the Graphics object. The transformation stored in that Matrix object is called the world transformation. The world transformation can be a simple affine transformation or a complex sequence of affine transformations, but regardless of its complexity, the world transformation is stored in a single Matrix object.

The Graphics class provides several methods for building up a composite world transformation: MultiplyTransform, RotateTransform, ScaleTransform, and TranslateTransform. The following example draws an ellipse twice: once before creating a world transformation and once after. The transformation first scales by a factor of 0.5 in the y direction, then translates 50 units in the x direction, and then rotates 30 degrees.

myGraphics.DrawEllipse(&myPen, 0, 0, 100, 50);
myGraphics.ScaleTransform(1.0f, 0.5f);
myGraphics.TranslateTransform(50.0f, 0.0f, MatrixOrderAppend);
myGraphics.RotateTransform(30.0f, MatrixOrderAppend);
myGraphics.DrawEllipse(&myPen, 0, 0, 100, 50);

The following illustration shows the original ellipse and the transformed ellipse.

The following illustration shows the matrices involved in the transformation.

Note In the previous example, the ellipse is rotated about the origin of the coordinate system, which is at the upper-left corner of the client area. This produces a different result than rotating the ellipse about its own center.

A local transformation is a transformation that applies to a specific item to be drawn. For example, a GraphicsPath object has a Transform method that allows you transform the data points of that path. The following example draws a rectangle with no transformation and a path with a rotation transformation. (Assume that there is no world transformation.)

Matrix myMatrix;
myMatrix.Rotate(45.0f);
myGraphicsPath.Transform(&myMatrix);
myGraphics.DrawRectangle(&myPen, 10, 10, 100, 50);
myGraphics.DrawPath(&myPen, &myGraphicsPath);

You can combine the world transformation with local transformations to achieve a variety of results. For example, you can use the world transformation to revise the coordinate system and use local transformations to rotate and scale objects drawn on the new coordinate system.

Suppose you want a coordinate system that has its origin 200 pixels from the left edge of the client area and 150 pixels from the top of the client area. Furthermore, assume that you want the unit of measure to be the pixel, with the x-axis pointing to the right and the y-axis pointing up. The default coordinate system has the y-axis pointing down, so you need to perform a reflection across the horizontal axis. The following illustration shows the matrix of such a reflection.

Next, assume you need to perform a translation 200 units to the right and 150 units down.

The following example establishes the coordinate system just described by setting the world transformation of a Graphics object.

Matrix myMatrix(1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f);
myGraphics.SetTransform(&myMatrix);
myGraphics.TranslateTransform(200.0f, 150.0f, MatrixOrderAppend);

The following code (placed after the code in the preceding example) creates a path that consists of a single rectangle with its lower-left corner at the origin of the new coordinate system. The rectangle is filled once with no local transformation and once with a local transformation. The local transformation consists of a horizontal scaling by a factor of 2 followed by a 30-degree rotation.

// Create the path.
GraphicsPath myGraphicsPath;
Rect myRect(0, 0, 60, 60);
myGraphicsPath.AddRectangle(myRect);

// Fill the path on the new coordinate system.
// No local transformation
myGraphics.FillPath(&mySolidBrush1, &myGraphicsPath);

// Transform the path.
Matrix myPathMatrix;
myPathMatrix.Scale(2, 1);
myPathMatrix.Rotate(30, MatrixOrderAppend);
myGraphicsPath.Transform(&myPathMatrix);

// Fill the transformed path on the new coordinate system.
myGraphics.FillPath(&mySolidBrush2, &myGraphicsPath);

The following illustration shows the new coordinate system and the two rectangles.


Graphics Containers

Graphics state — clipping region, transformations, and quality settings — is stored in a Graphics object. GDI+ allows you to temporarily replace or augment part of the state in a Graphics object by using a container. You start a container by calling the BeginContainer method of a Graphics object, and you end a container by calling the EndContainer method. In between BeginContainer and EndContainer, any state changes you make to the Graphics object belong to the container and do not overwrite the existing state of the Graphics object.

The following example creates a container within a Graphics object. The world transformation of the Graphics object is a translation 200 units to the right, and the world transformation of the container is a translation 100 units down.

myGraphics.TranslateTransform(200.0f, 0.0f);

myGraphicsContainer = myGraphics.BeginContainer();
   myGraphics.TranslateTransform(0.0f, 100.0f);
   myGraphics.DrawRectangle(&myPen, 0, 0, 50, 50);
myGraphics.EndContainer(myGraphicsContainer);

myGraphics.DrawRectangle(&myPen, 0, 0, 50, 50);

Note that in the previous example, the statement myGraphics.DrawRectangle(&myPen, 0, 0, 50, 50) made in between the calls to BeginContainer and EndContainer produces a different rectangle than the same statement made after the call to EndContainer. Only the horizontal translation applies to the DrawRectangle call made outside of the container. Both transformations — the horizontal translation of 200 units and the vertical translation of 100 units — apply to the DrawRectangle call made inside the container. The following illustration shows the two rectangles.

Containers can be nested within containers. The following example creates a container within a Graphics object and another container within the first container. The world transformation of the Graphics object is a translation 100 units in the x direction and 80 units in the y direction. The world transformation of the first container is a 30-degree rotation. The world transformation of the second container is a scaling by a factor of 2 in the x direction. A call to the DrawEllipse method is made inside the second container.

myGraphics.TranslateTransform(100.0f, 80.0f, MatrixOrderAppend);

container1 = myGraphics.BeginContainer();
   myGraphics.RotateTransform(30.0f, MatrixOrderAppend);

   container2 = myGraphics.BeginContainer();
      myGraphics.ScaleTransform(2.0f, 1.0f);
      myGraphics.DrawEllipse(&myPen, -30, -20, 60, 40);
   myGraphics.EndContainer(container2);

myGraphics.EndContainer(container1);

The following illustration shows the ellipse.

Note that all three transformations apply to the DrawEllipse call made in the second (innermost) container. Also note the order of the transformations: first scale, then rotate, then translate. The innermost transformation is applied first, and the outermost transformation is applied last.

Any property of a Graphics object can be set inside a container (in between calls to BeginContainer and EndContainer). For example, a clipping region can be set inside a container. Any drawing done inside the container will be restricted to the clipping region of that container and will also be restricted to the clipping regions of any outer containers and the clipping region of the Graphics object itself.

The properties discussed so far — the world transformation and the clipping region — are combined by nested containers. Other properties are temporarily replaced by a nested container. For example, if you set the SmoothingMode property to SmoothingModeAntiAlias within a container, any drawing methods called inside that container will use the AntiAlias smoothing mode, but drawing methods called after EndContainer will use the smoothing mode that was in place before the call to BeginContainer.

For another example of combining the world transformations of a Graphics object and a container, suppose you want to draw an eye and place it at various locations on a sequence of faces. The following example draws an eye centered at the origin of the coordinate system.

void DrawEye(Graphics* pGraphics)
{
   GraphicsContainer eyeContainer;

   eyeContainer = pGraphics->BeginContainer();

      Pen myBlackPen(Color(255, 0, 0, 0));
      SolidBrush myGreenBrush(Color(255, 0, 128, 0));
      SolidBrush myBlackBrush(Color(255, 0, 0, 0));

      GraphicsPath myTopPath;
      myTopPath.AddEllipse(-30, -50, 60, 60);

      GraphicsPath myBottomPath;
      myBottomPath.AddEllipse(-30, -10, 60, 60);

      Region myTopRegion(&myTopPath);
      Region myBottomRegion(&myBottomPath);

      // Draw the outline of the eye.
      // The outline of the eye consists of two ellipses.
      // The top ellipse is clipped by the bottom ellipse, and
      // the bottom ellipse is clipped by the top ellipse.
      pGraphics->SetClip(&myTopRegion);
      pGraphics->DrawPath(&myBlackPen, &myBottomPath);
      pGraphics->SetClip(&myBottomRegion);
      pGraphics->DrawPath(&myBlackPen, &myTopPath);

      // Fill the iris.
      // The iris is clipped by the bottom ellipse.
      pGraphics->FillEllipse(&myGreenBrush, -10, -15, 20, 22);

      // Fill the pupil.
      pGraphics->FillEllipse(&myBlackBrush, -3, -7, 6, 9);

   pGraphics->EndContainer(eyeContainer);
}

The following illustration shows the eye and the coordinate axes.

The DrawEye function, defined in the previous example receives the address of a Graphics object and immediately creates a container within that Graphics object. This container insulates any code that calls the DrawEye function from property settings made during the execution of the DrawEye function. For example, code in the DrawEye function sets the clipping region of the Graphics object, but when DrawEye returns control to the calling routine, the clipping region will be as it was before the call to DrawEye.

The following example draws three ellipses (faces), each with an eye inside.

// Draw an ellipse with center at (100, 100).
myGraphics.TranslateTransform(100.0f, 100.0f);
myGraphics.DrawEllipse(&myBlackPen, -40, -60, 80, 120);

// Draw the eye at the center of the ellipse.
DrawEye(&myGraphics);

// Draw an ellipse with center at 200, 100.
myGraphics.TranslateTransform(100.0f, 0.0f, MatrixOrderAppend);
myGraphics.DrawEllipse(&myBlackPen, -40, -60, 80, 120);

// Rotate the eye 40 degrees, and draw it 30 units above
// the center of the ellipse.
myGraphicsContainer = myGraphics.BeginContainer();
   myGraphics.RotateTransform(-40.0f);
   myGraphics.TranslateTransform(0.0f, -30.0f, MatrixOrderAppend);
   DrawEye(&myGraphics);
myGraphics.EndContainer(myGraphicsContainer);

// Draw a ellipse with center at (300.0f, 100.0f).
myGraphics.TranslateTransform(100.0f, 0.0f, MatrixOrderAppend);
myGraphics.DrawEllipse(&myBlackPen, -40, -60, 80, 120);

// Stretch and rotate the eye, and draw it at the
// center of the ellipse.
myGraphicsContainer = myGraphics.BeginContainer();
   myGraphics.ScaleTransform(2.0f, 1.5f);
   myGraphics.RotateTransform(45.0f, MatrixOrderAppend);
   DrawEye(&myGraphics);
myGraphics.EndContainer(myGraphicsContainer);

The following illustration shows the three ellipses.

In the previous example, all ellipses are drawn with the call DrawEllipse(&myBlackPen, -40, -60, 80, 120), which draws an ellipse centered at the origin of the coordinate system. The ellipses are moved away from the upper-left corner of the client area by setting the world transformation of the Graphics object. The statement myGraphics.TranslateTransform(100, 100) causes the first ellipse to be centered at (100, 100). The statement myGraphics.TranslateTransform(100, 0) causes the center of the second ellipse to be 100 units to the right of the center of the first ellipse. Likewise, the center of the third ellipse is 100 units to the right of the center of the second ellipse.

The containers in the previous example are used to transform the eye relative to the center of a given ellipse. The first eye is drawn at the center of the ellipse with no transformation, so the DrawEye call is not inside a container. The second eye is rotated 40 degrees and drawn 30 units above the center of the ellipse, so the DrawEye function and the methods that set the transformation are called inside a container. The third eye is stretched and rotated and drawn at the center of the ellipse. As with the second eye, the DrawEye function and the methods that set the transformation are called inside a container.


Using GDI+

The following topics describe how to use the GDI+ API with the C++ programming language:

  • Getting Started
  • Using a Pen to Draw Lines and Shapes
  • Using a Brush to Fill Shapes
  • Using Images, Bitmaps, and Metafiles
  • Using Image Encoders and Decoders
  • Alpha Blending Lines and Fills
  • Using Text and Fonts
  • Constructing and Drawing Curves
  • Filling Shapes with a Gradient Brush
  • Constructing and Drawing Paths
  • Using Graphics Containers
  • Transformations
  • Using Regions
  • Recoloring
  • Printing


Getting Started

This section shows how to get started using GDI+ in a standard C++ Windows application. Drawing lines and strings are two of the simplest tasks you can perform in GDI+. The following topics discuss these two tasks:

Drawing a Line

Drawing a String


Drawing a Line

To draw a line in GDI+, you need a Graphics object, a Pen object, and a Color object. The Graphics object provides the DrawLine method, and the Pen object holds attributes of the line, such as color and width. The address of the Pen object is passed as an argument to the DrawLine method.

The following program, which draws a line from (0, 0) to (200, 100), consists of three functions: WinMain, WndProc, and OnPaint. The WinMain and WndProc functions provide the fundamental code common to most Windows applications. There is no GDI+ code in the WndProc function. The WinMain function has a small amount of GDI+ code, namely the required calls to GdiplusStartup and GdiplusShutdown. The GDI+ code that actually creates a Graphics object and draws a line is in the OnPaint function.

The OnPaint function receives a handle to a device context and passes that handle to a Graphics constructor. The argument passed to the Pen constructor is a reference to a Color object The four numbers passed to the color constructor represent the alpha, red, green, and blue components of the color. The alpha component determines the transparency of the color; 0 is fully transparent and 255 is fully opaque. The four numbers passed to the DrawLine method represent the starting point (0, 0) and the ending point (200, 100) of the line.

#define UNICODE
#include <windows.h>
#include <gdiplus.h>
using namespace Gdiplus;

VOID OnPaint(HDC hdc)
{
   Graphics graphics(hdc);
   Pen      pen(Color(255, 0, 0, 255));

   graphics.DrawLine(&pen, 0, 0, 200, 100);
}

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

INT WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, PSTR, INT iCmdShow)
{
   HWND                hWnd;
   MSG                 msg;
   WNDCLASS            wndClass;
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR           gdiplusToken;

   // Initialize GDI+.
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   wndClass.style          = CS_HREDRAW | CS_VREDRAW;
   wndClass.lpfnWndProc    = WndProc;
   wndClass.cbClsExtra     = 0;
   wndClass.cbWndExtra     = 0;
   wndClass.hInstance      = hInstance;
   wndClass.hIcon          = LoadIcon(NULL, IDI_APPLICATION);
   wndClass.hCursor        = LoadCursor(NULL, IDC_ARROW);
   wndClass.hbrBackground  = (HBRUSH)GetStockObject(WHITE_BRUSH);
   wndClass.lpszMenuName   = NULL;
   wndClass.lpszClassName  = TEXT("GettingStarted");

   RegisterClass(&wndClass);

   hWnd = CreateWindow(
      TEXT("GettingStarted"),   // window class name
      TEXT("Getting Started"),  // window caption
      WS_OVERLAPPEDWINDOW,      // window style
      CW_USEDEFAULT,            // initial x position
      CW_USEDEFAULT,            // initial y position
      CW_USEDEFAULT,            // initial x size
      CW_USEDEFAULT,            // initial y size
      NULL,                     // parent window handle
      NULL,                     // window menu handle
      hInstance,                // program instance handle
      NULL);                    // creation parameters

   ShowWindow(hWnd, iCmdShow);
   UpdateWindow(hWnd);

   while(GetMessage(&msg, NULL, 0, 0))
   {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
   }

   GdiplusShutdown(gdiplusToken);
   return msg.wParam;
}  // WinMain

LRESULT CALLBACK WndProc(HWND hWnd, UINT message,
   WPARAM wParam, LPARAM lParam)
{
   HDC          hdc;
   PAINTSTRUCT  ps;

   switch(message)
   {
   case WM_PAINT:
      hdc = BeginPaint(hWnd, &ps);
      OnPaint(hdc);
      EndPaint(hWnd, &ps);
      return 0;

   case WM_DESTROY:
      PostQuitMessage(0);
      return 0;

   default:
      return DefWindowProc(hWnd, message, wParam, lParam);
   }
} // WndProc

Note the call to GdiplusStartup in the WinMain function. The first parameter of the GdiplusStartup function is the address of a ULONG_PTR. GdiplusStartup fills that variable with a token that is later passed to the GdiplusShutdown function. The second parameter of the GdiplusStartup function is the address of a GdiplusStartupInput structure. The preceding code relies on the default GdiplusStartupInput constructor to set the structure members appropriately.


Drawing a String

The topic Drawing a Line shows how to write a Windows application that uses GDI+ to draw a line. To draw a string, replace the OnPaint function shown in that topic with the following OnPaint function:

VOID OnPaint(HDC hdc)
{
   Graphics    graphics(hdc);
   SolidBrush  brush(Color(255, 0, 0, 255));
   FontFamily  fontFamily(L"Times New Roman");
   Font        font(&fontFamily, 24, FontStyleRegular, UnitPixel);
   PointF      pointF(10.0f, 20.0f);

   graphics.DrawString(L"Hello World!", -1, &font, pointF, &brush);
}

The previous code creates several GDI+ objects. The Graphics object provides the DrawString method, which does the actual drawing. The SolidBrush object specifies the color of the string.

The FontFamily constructor receives a single, string argument that identifies the font family. The address of the FontFamily object is the first argument passed to the Font constructor. The second argument passed to the Font constructor specifies the font size, and the third argument specifies the style. The value FontStyleRegular is a member of the FontStyle enumeration, which is declared in Gdiplusenums.h. The last argument to the Font constructor indicates that the size of the font (24 in this case) is measured in pixels. The value UnitPixel is a member of the Unit enumeration.

The first argument passed to the DrawString method is the address of a wide-character string. The second argument, –1, specifies that the string is null terminated. (If the string is not null terminated, the second argument should specify the number of wide characters in the string.) The third argument is the address of the Font object. The fourth argument is a reference to a PointF object that specifies the location where the string will be drawn. The last argument is the address of the Brush object, which specifies the color of the string.


Using a Pen to Draw Lines and Shapes

The Graphics class provides a variety of drawing methods including those shown in the following list:

  • DrawLine
  • DrawRectangle
  • DrawEllipse
  • DrawArc
  • DrawPath
  • DrawCurve
  • DrawBezier

One of the arguments that you pass to such a drawing method is the address of a Pen object.

The following topics cover the use of pens in more detail:

  • Using a Pen to Draw Lines and Rectangles
  • Setting Pen Width and Alignment
  • Drawing a Line with Line Caps
  • Joining Lines
  • Drawing a Custom Dashed Line
  • Drawing a Line Filled with a Texture


Using a Pen to Draw Lines and Rectangles

To draw lines and rectangles, you need a Graphics object and a Pen object. The Graphics object provides the DrawLine method, and the Pen object stores features of the line, such as color and width.

The following example draws a line from (20, 10) to (300, 100). Assume graphics is an existing Graphics object.

Pen pen(Color(255, 0, 0, 0));
graphics.DrawLine(&pen, 20, 10, 300, 100);

The first statement of code uses the Pen class constructor to create a black pen. The one argument passed to the Pen constructor is a Color object. The values used to construct the Color object — (255, 0, 0, 0) — correspond to the alpha, red, green, and blue components of the color. These values define an opaque black pen.

The following example draws a rectangle with its upper-left corner at (10, 10). The rectangle has a width of 100 and a height of 50. The second argument passed to the Pen constructor indicates that the pen width is 5 pixels.

Pen blackPen(Color(255, 0, 0, 0), 5);
stat = graphics.DrawRectangle(&blackPen, 10, 10, 100, 50);

When the rectangle is drawn, the pen is centered on the rectangle's boundary. Because the pen width is 5, the sides of the rectangle are drawn 5 pixels wide, such that 1 pixel is drawn on the boundary itself, 2 pixels are drawn on the inside, and 2 pixels are drawn on the outside. For more details on pen alignment, see Setting Pen Width and Alignment.

The following illustration shows the resulting rectangle. The dotted lines show where the rectangle would have been drawn if the pen width had been one pixel. The enlarged view of the upper-left corner of the rectangle shows that the thick black lines are centered on those dotted lines.


Setting Pen Width and Alignment

When you create a Pen object, you can supply the pen width as one of the arguments to the constructor. You can also change the pen width by using the SetWidth method.

A theoretical line has a width of zero. When you draw a line, the pixels are centered on the theoretical line. The following example draws a specified line twice: once with a black pen of width 1 and once with a green pen of width 10.

Pen blackPen(Color(255, 0, 0, 0), 1);
Pen greenPen(Color(255, 0, 255, 0), 10);
stat = greenPen.SetAlignment(PenAlignmentCenter);

// Draw the line with the wide green pen.
stat = graphics.DrawLine(&greenPen, 10, 100, 100, 50);

// Draw the same line with the thin black pen.
stat = graphics.DrawLine(&blackPen, 10, 100, 100, 50);

The following illustration shows the output of the preceding code. The green pixels and the black pixels are centered on the theoretical line.

The following example draws a specified rectangle twice: once with a black pen of width 1 and once with a green pen of width 10. The code passes the value PenAlignmentCenter (an element of the PenAlignment enumeration) to the SetAlignment method to specify that the pixels drawn with the green pen are centered on the boundary of the rectangle.

Pen blackPen(Color(255, 0, 0, 0), 1);
Pen greenPen(Color(255, 0, 255, 0), 10);
stat = greenPen.SetAlignment(PenAlignmentCenter);

// Draw the rectangle with the wide green pen.
stat = graphics.DrawRectangle(&greenPen, 10, 100, 50, 50);

// Draw the same rectangle with the thin black pen.
stat = graphics.DrawRectangle(&blackPen, 10, 100, 50, 50);

The following illustration shows the output of the preceding code. The green pixels are centered on the theoretical rectangle, which is represented by the black pixels.

You can change the green pen's alignment by modifying the third statement in the preceding example as follows:

stat = greenPen.SetAlignment(PenAlignmentInset);

Now the pixels in the wide green line appear on the inside of the rectangle as shown in the following illustration.


Drawing a Line with Line Caps

You can draw the start or end of a line in one of several shapes called line caps. GDI+ supports several line caps, such as round, square, diamond, and arrowhead.

You can specify line caps for the start of a line (start cap), the end of a line (end cap), or the dashes of a dashed line (dash cap).

The following example draws a line with an arrowhead at one end and a round cap at the other end:

Pen pen(Color(255, 0, 0, 255), 8);
stat = pen.SetStartCap(LineCapArrowAnchor);
stat = pen.SetEndCap(LineCapRoundAnchor);
stat = graphics.DrawLine(&pen, 20, 175, 300, 175);

The following illustration shows the resulting line.

LineCapArrowAnchor and LineCapRoundAnchor are elements of the LineCap enumeration.


Joining Lines

A line join is the common area that is formed by two lines whose ends meet or overlap. GDI+ provides four line join styles: miter, bevel, round, and miter clipped. Line join style is a property of the Pen class. When you specify a line join style for a pen and then use that pen to draw a path, the specified join style is applied to all the connected lines in the path.

You can specify the line join style by using the SetLineJoin method of the Pen class. The following example demonstrates a beveled line join between a horizontal line and a vertical line:

GraphicsPath path;
Pen penJoin(Color(255, 0, 0, 255), 8);

path.StartFigure();
path.AddLine(Point(50, 200), Point(100, 200));
path.AddLine(Point(100, 200), Point(100, 250));

penJoin.SetLineJoin(LineJoinBevel);
graphics.DrawPath(&penJoin, &path);

The following illustration shows the resulting beveled line join.

In the preceding example, the value (LineJoinBevel) passed to the SetLineJoin method is an element of the LineJoin enumeration.


Drawing a Custom Dashed Line

GDI+ provides several dash styles that are listed in the DashStyle enumeration. If those standard dash styles don't suit your needs, you can create a custom dash pattern.

To draw a custom dashed line, put the lengths of the dashes and spaces in an array and pass the address of the array as an argument to the SetDashPattern method of a Pen object. The following example draws a custom dashed line based on the array {5, 2, 15, 4}. If you multiply the elements of the array by the pen width of 5, you get {25, 10, 75, 20}. The displayed dashes alternate in length between 25 and 75, and the spaces alternate in length between 10 and 20.

REAL dashValues[4] = {5, 2, 15, 4};
Pen blackPen(Color(255, 0, 0, 0), 5);
blackPen.SetDashPattern(dashValues, 4);
stat = graphics.DrawLine(&blackPen, Point(5, 5), Point(405, 5));

The following illustration shows the resulting dashed line. Note that the final dash has to be shorter than 25 units so that the line can end at (405, 5).


Drawing a Line Filled with a Texture

Instead of drawing a line or curve with a solid color, you can draw with a texture. To draw lines and curves with a texture, create a TextureBrush object, and pass the address of that TextureBrush object to a Pen constructor. The image associated with the texture brush is used to tile the plane (invisibly), and when the pen draws a line or curve, the stroke of the pen uncovers certain pixels of the tiled texture.

The following example creates an Image object from the file Texture1.jpg. That image is used to construct a TextureBrush object, and the TextureBrush object is used to construct a Pen object. The call to Graphics::DrawImage draws the image with its upper-left corner at (0, 0). The call to Graphics::DrawEllipse uses the Pen object to draw a textured ellipse.

Image         image(L"Texture1.jpg");
TextureBrush  tBrush(&image);
Pen           texturedPen(&tBrush, 30);

graphics.DrawImage(&image, 0, 0, image.GetWidth(), image.GetHeight());
graphics.DrawEllipse(&texturedPen, 100, 20, 200, 100);

The following illustration shows the image and the textured ellipse.


Using a Brush to Fill Shapes

A GDI+ Brush object is used to fill the interior of a closed shape. GDI+ defines several fill styles: solid color, hatch pattern, image texture, and color gradient.

The following topics cover the use of brushes in more detail:

  • Filling a Shape with a Solid Color
  • Filling a Shape with a Hatch Pattern
  • Filling a Shape with an Image Texture
  • Tiling a Shape with an Image
  • Filling a Shape with a Color Gradient


Filling a Shape with a Solid Color

To fill a shape with a solid color, create a SolidBrush object, and then pass the address of that SolidBrush object as an argument to one of the fill methods of the Graphics class. The following example shows how to fill an ellipse with the color red:

SolidBrush solidBrush(Color(255, 255, 0, 0));
stat = graphics.FillEllipse(&solidBrush, 0, 0, 100, 60);

In the preceding example, the SolidBrush constructor takes a Color object reference as its only argument. The values used by the Color constructor represent the alpha, red, green, and blue components of the color. Each of these values must be in the range 0 through 255. The first 255 indicates that the color is fully opaque, and the second 255 indicates that the red component is at full intensity. The two zeros indicate that the green and blue components both have an intensity of 0.

The four numbers (0, 0, 100, 60) passed to the FillEllipse method specify the location and size of the bounding rectangle for the ellipse. The rectangle has an upper-left corner of (0, 0), a width of 100, and a height of 60.


Filling a Shape with a Hatch Pattern

A hatch pattern is made from two colors: one for the background and one for the lines that form the pattern over the background. To fill a closed shape with a hatch pattern, use a HatchBrush object. The following example demonstrates how to fill an ellipse with a hatch pattern:

HatchBrush hBrush(HatchStyleHorizontal, Color(255, 255, 0, 0),
   Color(255, 128, 255, 255));
stat = graphics.FillEllipse(&hBrush, 0, 0, 100, 60);

The following illustration shows the filled ellipse.

The HatchBrush constructor takes three arguments: the hatch style, the color of the hatch line, and the color of the background. The hatch style argument can be any element of the HatchStyle enumeration. There are more than fifty elements in the HatchStyle enumeration; a few of those elements are shown in the following list:

  • HatchStyleHorizontal
  • HatchStyleVertical
  • HatchStyleForwardDiagonal
  • HatchStyleBackwardDiagonal
  • HatchStyleCross
  • HatchStyleDiagonalCross


Filling a Shape with an Image Texture

You can fill a closed shape with a texture by using the Image class and the TextureBrush class.

The following example fills an ellipse with an image. The code constructs an Image object, and then passes the address of that Image object as an argument to a TextureBrush constructor. The third code statement scales the image, and the fourth statement fills the ellipse with repeated copies of the scaled image:

Image image(L"ImageFile.jpg");
TextureBrush tBrush(&image);
stat = tBrush.SetTransform(&Matrix(75.0/640.0, 0.0f, 0.0f,
   75.0/480.0, 0.0f, 0.0f));
stat = graphics.FillEllipse(&tBrush,Rect(0, 150, 150, 250));

In the preceding code example, the SetTransform method sets the transformation that is applied to the image before it is drawn. Assume that the original image has a width of 640 pixels and a height of 480 pixels. The transform shrinks the image to 75×75, by setting the horizontal and vertical scaling values.

Note In the preceding example, the image size is 75×75, and the ellipse size is 150×250. Because the image is smaller than the ellipse it is filling, the ellipse is tiled with the image. Tiling means that the image is repeated horizontally and vertically until the boundary of the shape is reached. For more information on tiling, see Tiling a Shape with an Image.


Tiling a Shape with an Image

Just as tiles can be placed next to each other to cover a floor, rectangular images can be placed next to each other to fill (tile) a shape. To tile the interior of a shape, use a texture brush. When you construct a TextureBrush object, one of the arguments you pass to the constructor is the address of an Image object. When you use the texture brush to paint the interior of a shape, the shape is filled with repeated copies of this image.

The wrap mode property of the TextureBrush object determines how the image is oriented as it is repeated in a rectangular grid. You can make all the tiles in the grid have the same orientation, or you can make the image flip from one grid position to the next. The flipping can be horizontal, vertical, or both. The following examples demonstrate tiling with different types of flipping.

Tiling an Image

This example uses the following 75×75 image to tile a 200×200 rectangle:

Image image(L"HouseAndTree.gif");
TextureBrush tBrush(&image);
Pen blackPen(Color(255, 0, 0, 0));
stat = graphics.FillRectangle(&tBrush, Rect(0, 0, 200, 200));
stat = graphics.DrawRectangle(&blackPen, Rect(0, 0, 200, 200));

The following illustration shows how the rectangle is tiled with the image. Note that all tiles have the same orientation; there is no flipping.

Flipping an Image Horizontally While Tiling

This example uses a 75×75 image to fill a 200×200 rectangle. The wrap mode is set to flip the image horizontally.

Image image(L"HouseAndTree.gif");
TextureBrush tBrush(&image);
Pen blackPen(Color(255, 0, 0, 0));
stat = tBrush.SetWrapMode(WrapModeTileFlipX);
stat = graphics.FillRectangle(&tBrush, Rect(0, 0, 200, 200));
stat = graphics.DrawRectangle(&blackPen, Rect(0, 0, 200, 200));

The following illustration shows how the rectangle is tiled with the image. Note that as you move from one tile to the next in a given row, the image is flipped horizontally.

Flipping an Image Vertically While Tiling

This example uses a 75×75 image to fill a 200×200 rectangle. The wrap mode is set to flip the image vertically.

Image image(L"HouseAndTree.gif");
TextureBrush tBrush(&image);
Pen blackPen(Color(255, 0, 0, 0));
stat = tBrush.SetWrapMode(WrapModeTileFlipY);
stat = graphics.FillRectangle(&tBrush, Rect(0, 0, 200, 200));
stat = graphics.DrawRectangle(&blackPen, Rect(0, 0, 200, 200));

The following illustration shows how the rectangle is tiled with the image. Note that as you move from one tile to the next in a given column, the image is flipped vertically.

Flipping an Image Horizontally and Vertically While Tiling

This example uses a 75×75 image to tile a 200×200 rectangle. The wrap mode is set to flip the image both horizontally and vertically.

Image image(L"HouseAndTree.gif");
TextureBrush tBrush(&image);
Pen blackPen(Color(255, 0, 0, 0));
stat = tBrush.SetWrapMode(WrapModeTileFlipXY);
stat = graphics.FillRectangle(&tBrush, Rect(0, 0, 200, 200));
stat = graphics.DrawRectangle(&blackPen, Rect(0, 0, 200, 200));

The following illustration shows how the rectangle is tiled by the image. Note that as you move from one tile to the next in a given row, the image is flipped horizontally, and as you move from one tile to the next in a given column, the image is flipped vertically.


Filling a Shape with a Color Gradient

You can fill a shape with a gradually changing color by using a gradient brush. GDI+ provides linear gradient brushes and path gradient brushes. The following illustration shows a rectangle filled with a linear gradient brush and an ellipse filled with a path gradient brush.

For more information about gradient brushes, see Filling Shapes With a Gradient Brush.


Using Images, Bitmaps, and Metafiles

GDI+ provides the Image class for working with raster images (bitmaps) and vector images (metafiles). The Bitmap class and the Metafile class both inherit from the Image class. The Bitmap class expands on the capabilities of the Image class by providing additional methods for loading, saving, and manipulating raster images. The Metafile class expands on the capabilities of the Image class by providing additional methods for recording and examining vector images.

The following topics cover the Image, Bitmap, and Metafile classes in more detail:

  • Loading and Displaying Bitmaps
  • Loading and Displaying Metafiles
  • Recording Metafiles
  • Cropping and Scaling Images
  • Rotating, Reflecting, and Skewing Images
  • Using Interpolation Mode to Control Image Quality During Scaling
  • Creating Thumbnail Images
  • Using a Cached Bitmap to Improve Performance
  • Improving Performance by Avoiding Automatic Scaling
  • Reading and Writing Metadata


Loading and Displaying Bitmaps

To display a raster image (bitmap) on the screen, you need an Image object and a Graphics object. Pass the name of a file (or a pointer to a stream) to an Image constructor. After you have created an Image object, pass the address of that Image object to the DrawImage method of a Graphics object.

The following example creates an Image object from a JPEG file and then draws the image with its upper-left corner at (60, 10):

Image image(L"Grapes.jpg");
graphics.DrawImage(&image, 60, 10);

The following illustration shows the image drawn at the specified location.

The Image class provides basic methods for loading and displaying raster images and vector images. The Bitmap class, which inherits from the Image class, provides more specialized methods for loading, displaying, and manipulating raster images. For example, you can construct a Bitmap object from an icon handle (HICON).

The following example obtains a handle to an icon and then uses that handle to construct a Bitmap object. The code displays the icon by passing the address of the Bitmap object to the DrawImage method of a Graphics object.

HICON hIcon = LoadIcon(NULL, IDI_APPLICATION);
Bitmap bitmap(hIcon);
graphics.DrawImage(&bitmap, 10, 10);


Loading and Displaying Metafiles

The Image class provides basic methods for loading and displaying raster images and vector images. The Metafile class, which inherits from the Image class, provides more specialized methods for recording, displaying, and examining vector images.

To display a vector image (metafile) on the screen, you need an Image object and a Graphics object. Pass the name of a file (or a pointer to a stream) to an Image constructor. After you have created an Image object, pass the address of that Image object to the DrawImage method of a Graphics object.

The following example creates an Image object from an EMF (enhanced metafile) file and then draws the image with its upper-left corner at (60, 10):

Image image(L"SampleMetafile.emf");
graphics.DrawImage(&image, 60, 10);

The following illustration shows the image drawn at the specified location.


Recording Metafiles

The Metafile class, which inherits from the Image class, allows you to record a sequence of drawing commands. The recorded commands can be stored in memory, saved to a file, or saved to a stream. Metafiles can contain vector graphics, raster images, and text.

The following example creates a Metafile object. The code uses the Metafile object to record a sequence of graphics commands and then saves the recorded commands in a file named SampleMetafile.emf. Note that the Metafile constructor receives a device context handle, and the Graphics constructor receives the address of the Metafile object. The recording stops (and the recorded commands are saved to the file) when the Graphics object goes out of scope. The last two lines of code display the metafile by creating a new Graphics object and passing the address of the Metafile object to the DrawImage method of that Graphics object. Note that the code uses the same Metafile object to record and to display (play back) the metafile.

Metafile metafile(L"SampleMetafile.emf", hdc);
{
   Graphics graphics(&metafile);
   Pen greenPen(Color(255, 0, 255, 0));
   SolidBrush solidBrush(Color(255, 0, 0, 255));

   // Add a rectangle and an ellipse to the metafile.
   graphics.DrawRectangle(&greenPen, Rect(50, 10, 25, 75));
   graphics.DrawEllipse(&greenPen, Rect(100, 10, 25, 75));

   // Add an ellipse (drawn with antialiasing) to the metafile.
   graphics.SetSmoothingMode(SmoothingModeHighQuality);
   graphics.DrawEllipse(&greenPen, Rect(150, 10, 25, 75));

   // Add some text (drawn with antialiasing) to the metafile.
   FontFamily fontFamily(L"Arial");
   Font font(&fontFamily, 24, FontStyleRegular, UnitPixel);

   graphics.SetTextRenderingHint(TextRenderingHintAntiAlias);
   graphics.RotateTransform(30.0f);
   graphics.DrawString(L"Smooth Text", 11, &font,
      PointF(50.0f, 50.0f), &solidBrush);
} // End of recording metafile.

// Play back the metafile.
Graphics playbackGraphics(hdc);
playbackGraphics.DrawImage(&metafile, 200, 100);

Note To record a metafile, you must construct a Graphics object based on a Metafile object. The recording of the metafile ends when that Graphics object is deleted or goes out of scope.

A metafile contains its own graphics state, which is defined by the Graphics object used to record the metafile. Any properties of the Graphics object (clip region, world transformation, smoothing mode, and the like) that you set while recording the metafile will be stored in the metafile. When you display the metafile, the drawing will be done according to those stored properties.

In the following example, assume that the smoothing mode was set to SmoothingModeNormal during the recording of the metafile. Even though the smoothing mode of the Graphics object used for playback is set to SmoothingModeHighQuality, the metafile will be played according to the SmoothingModeNormal setting. It is the smoothing mode set during the recording that is important, not the smoothing mode set prior to playback.

graphics.SetSmoothingMode(SmoothingModeHighQuality);
graphics.DrawImage(&meta, 0, 0);


Cropping and Scaling Images

The Graphics class provides several DrawImage methods, some of which have source and destination rectangle parameters that you can use to crop and scale images.

The following example constructs an Image object from the file Apple.gif. The code draws the entire apple image in its original size. The code then calls the DrawImage method of a Graphics object to draw a portion of the apple image in a destination rectangle that is larger than the original apple image.

The DrawImage method determines which portion of the apple to draw by looking at the source rectangle, which is specified by the third, fourth, fifth, and sixth arguments. In this case, the apple is cropped to 75 percent of its width and 75 percent of its height.

The DrawImage method determines where to draw the cropped apple and how big to make the cropped apple by looking at the destination rectangle, which is specified by the second argument. In this case, the destination rectangle is 30 percent wider and 30 percent taller than the original image.

Image image(L"Apple.gif");
UINT width = image.GetWidth();
UINT height = image.GetHeight();

// Make the destination rectangle 30 percent wider and
// 30 percent taller than the original image.
// Put the upper-left corner of the destination
// rectangle at (150, 20).
Rect destinationRect(150, 20, 1.3 * width, 1.3 * height);

// Draw the image unaltered with its upper-left corner at (0, 0).
graphics.DrawImage(&image, 0, 0);

// Draw a portion of the image. Scale that portion of the image
// so that it fills the destination rectangle.
graphics.DrawImage(
   &image,
   destinationRect,
   0, 0,              // upper-left corner of source rectangle
   0.75 * width,      // width of source rectangle
   0.75 * height,     // height of source rectangle
   UnitPixel);

The following illustration shows the original apple and the scaled, cropped apple.


Rotating, Reflecting, and Skewing Images

You can rotate, reflect, and skew an image by specifying destination points for the upper-left, upper-right, and lower-left corners of the original image. The three destination points determine an affine transformation that maps the original rectangular image to a parallelogram. (The lower-right corner of the original image is mapped to the fourth corner of the parallelogram, which is calculated from the three specified destination points.)

For example, suppose the original image is a rectangle with upper-left corner at (0, 0), upper-right corner at (100, 0), and lower-left corner at (0, 50). Now suppose we map those three points to destination points as follows.

Original point | Destination point
Upper-left (0, 0) | (200, 20)
Upper-right (100, 0) | (110, 100)
Lower-left (0, 50) | (250, 30)

The following illustration shows the original image and the image mapped to the parallelogram. The original image has been skewed, reflected, rotated, and translated. The x-axis along the top edge of the original image is mapped to the line that runs through (200, 20) and (110, 100). The y-axis along the left edge of the original image is mapped to the line that runs through (200, 20) and (250, 30).

The following example produces the images shown in the preceding illustration.

Point destinationPoints[] = {
   Point(200, 20),   // destination for upper-left point of original
   Point(110, 100),  // destination for upper-right point of original
   Point(250, 30)};  // destination for lower-left point of original

Image image(L"Stripes.bmp");

// Draw the image unaltered with its upper-left corner at (0, 0).
graphics.DrawImage(&image, 0, 0);

// Draw the image mapped to the parallelogram.
graphics.DrawImage(&image, destinationPoints, 3);

The following illustration shows a similar transformation applied to a photographic image.

The following illustration shows a similar transformation applied to a metafile.


Using Interpolation Mode to Control Image Quality During Scaling

The interpolation mode of a Graphics object influences the way GDI+ scales (stretches and shrinks) images. The InterpolationMode enumeration in Gdiplusenums.h defines several interpolation modes, some of which are shown in the following list:

  • InterpolationModeNearestNeighbor
  • InterpolationModeBilinear
  • InterpolationModeHighQualityBilinear
  • InterpolationModeBicubic
  • InterpolationModeHighQualityBicubic

To stretch an image, each pixel in the original image must be mapped to a group of pixels in the larger image. To shrink an image, groups of pixels in the original image must be mapped to single pixels in the smaller image. The effectiveness of the algorithms that perform these mappings determines the quality of a scaled image. Algorithms that produce higher-quality scaled images tend to require more processing time. In the preceding list, InterpolationModeNearestNeighbor is the lowest-quality mode and InterpolationModeHighQualityBicubic is the highest-quality mode.

To set the interpolation mode, pass one of the members of the InterpolationMode enumeration to the SetInterpolationMode method of a Graphics object.

The following example draws an image and then shrinks the image with three different interpolation modes:

Image image(L"GrapeBunch.bmp");
UINT width = image.GetWidth();
UINT height = image.GetHeight();

// Draw the image with no shrinking or stretching.
graphics.DrawImage(
   &image,
   Rect(10, 10, width, height),  // destination rectangle
   0, 0,        // upper-left corner of source rectangle
   width,       // width of source rectangle
   height,      // height of source rectangle
   UnitPixel);

// Shrink the image using low-quality interpolation.
graphics.SetInterpolationMode(InterpolationModeNearestNeighbor);
graphics.DrawImage(
   &image,
   Rect(10, 250, 0.6*width, 0.6*height),  // destination rectangle
   0, 0,        // upper-left corner of source rectangle
   width,       // width of source rectangle
   height,      // height of source rectangle
   UnitPixel);

// Shrink the image using medium-quality interpolation.
graphics.SetInterpolationMode(InterpolationModeHighQualityBilinear);
graphics.DrawImage(
   &image,
   Rect(150, 250, 0.6 * width, 0.6 * height),  // destination rectangle
   0, 0,        // upper-left corner of source rectangle
   width,       // width of source rectangle
   height,      // height of source rectangle
   UnitPixel);

// Shrink the image using high-quality interpolation.
graphics.SetInterpolationMode(InterpolationModeHighQualityBicubic);
graphics.DrawImage(
   &image,
   Rect(290, 250, 0.6 * width, 0.6 * height),  // destination rectangle
   0, 0,        // upper-left corner of source rectangle
   width,       // width of source rectangle
   height,      // height of source rectangle
   UnitPixel);

The following illustration shows the original image and the three smaller images.


Creating Thumbnail Images

A thumbnail image is a small version of an image. You can create a thumbnail image by calling the GetThumbnailImage method of an Image object.

The following example constructs an Image object from the file Compass.bmp. The original image has a width of 640 pixels and a height of 479 pixels. The code creates a thumbnail image that has a width of 100 pixels and a height of 100 pixels.

Image image(L"Compass.bmp");
Image* pThumbnail = image.GetThumbnailImage(100, 100, NULL, NULL);
graphics.DrawImage(pThumbnail, 10, 10,
   pThumbnail->GetWidth(), pThumbnail->GetHeight());

The following illustration shows the thumbnail image.


Using a Cached Bitmap to Improve Performance

Image and Bitmap objects store images in a device-independent format. A CachedBitmap object stores an image in the format of the current display device. Rendering an image stored in a CachedBitmap object is fast because no processing time is spent converting the image to the format required by the display device.

The following example creates a Bitmap object and a CachedBitmap object from the file Texture.jpg. The Bitmap and the CachedBitmap are each drawn 30,000 times. If you run the code, you will see that the CachedBitmap images are drawn substantially faster than the Bitmap images.

Bitmap        bitmap(L"Texture.jpg");
UINT          width = bitmap.GetWidth();
UINT          height = bitmap.GetHeight();
CachedBitmap  cBitmap(&bitmap, &graphics);
int           j, k;

for(j = 0; j < 300; j += 10)
   for(k = 0; k < 1000; ++k)
     graphics.DrawImage(&bitmap, j, j / 2, width, height);

for(j = 0; j < 300; j += 10)
   for(k = 0; k < 1000; ++k)
      graphics.DrawCachedBitmap(&cBitmap, j, 150 + j / 2 );

Note A CachedBitmap object matches the format of the display device at the time the CachedBitmap object was constructed. If the user of your program changes the display settings, your code should construct a new CachedBitmap object. The DrawImage method will fail if you pass it a CachedBitmap object that was created prior to a change in the display format.


Improving Performance by Avoiding Automatic Scaling

If you pass only the upper-left corner of an image to the DrawImage method, GDI+ might scale the image, which would decrease performance.

The following call to the DrawImage method specifies an upper-left corner of (50, 30) but does not specify a destination rectangle:

graphics.DrawImage(&image, 50, 30);  // upper-left corner at (50, 30)

Although this is the easiest version of the DrawImage method in terms of the number of required arguments, it is not necessarily the most efficient. If the number of dots per inch on the current display device is different than the number of dots per inch on the device where the image was created, GDI+ scales the image so that its physical size on the current display device is as close as possible to its physical size on the device where it was created.

If you want to prevent such scaling, pass the width and height of a destination rectangle to the DrawImage method. The following example draws the same image twice. In the first case, the width and height of the destination rectangle are not specified, and the image is automatically scaled. In the second case, the width and height (measured in pixels) of the destination rectangle are specified to be the same as the width and height of the original image.

Image image(L"Texture.jpg");
graphics.DrawImage(&image, 10, 10);
graphics.DrawImage(&image, 120, 10, image.GetWidth(), image.GetHeight());

The following illustration shows the image rendered twice.


Reading and Writing Metadata

Some image files contain metadata that you can read to determine features of the image. For example, a digital photograph might contain metadata that you can read to determine the make and model of the camera used to capture the image. With GDI+, you can read existing metadata, and you can also write new metadata to image files.

GDI+ provides a uniform way of storing and retrieving metadata from image files in various formats. In GDI+, a piece of metadata is called a property item. You can store and retrieve metadata by calling the SetPropertyItem and GetPropertyItem methods of the Image class, and you don't have to be concerned about the details of how a particular file format stores that metadata.

GDI+ currently supports metadata for the TIFF, JPEG, Exif, and PNG file formats. The Exif format, which specifies how to store images captured by digital still cameras, is built on top of the TIFF and JPEG formats. Exif uses the TIFF format for uncompressed pixel data and the JPEG format for compressed pixel data.

GDI+ defines a set of property tags that identify property items. Certain tags are general-purpose; that is, they are supported by all of the file formats mentioned in the preceding paragraph. Other tags are special-purpose and apply only to certain formats. If you try to save a property item to a file that does not support that property item, GDI+ ignores the request. More specifically, the Image::SetPropertyItem method returns PropertyNotSupported.

You can determine the property items that are stored in an image file by calling Image::GetPropertyIDList. If you try to retrieve a property item that is not in the file, GDI+ ignores the request. More specifically, the Image::GetPropertyItem method returns PropertyNotFound.

Reading Metadata from a File

The following console application calls the GetPropertySize method of an Image object to determine how many pieces of metadata are in the file FakePhoto.jpg.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   UINT    size = 0;
   UINT    count = 0;

   Bitmap* bitmap = new Bitmap(L"FakePhoto.jpg");

   bitmap->GetPropertySize(&size, &count);
   printf("There are %d pieces of metadata in the file.\n", count);
   printf("The total size of the metadata is %d bytes.\n", size);

   delete bitmap;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, FakePhoto.jpg, produced the following output:

There are 7 pieces of metadata in the file.
The total size of the metadata is 436 bytes.

GDI+ stores an individual piece of metadata in a PropertyItem object. You can call the GetAllPropertyItems method of the Image class to retrieve all the metadata from a file. The GetAllPropertyItems method returns an array of PropertyItem objects. Before you call GetAllPropertyItems, you must allocate a buffer large enough to receive that array. You can call the GetPropertySize method of the Image class to get the size (in bytes) of the required buffer.

A PropertyItem object has the following four public members:

id
A tag that identifies the metadata item. The values that can be assigned to id (PropertyTagImageTitle, PropertyTagEquipMake, PropertyTagExifExposureTime, and the like) are defined in Gdiplusimaging.h.
length
The length, in bytes, of the array of values pointed to by the value data member. Note that if the type data member is set to PropertyTagTypeASCII, then the length data member is the length of a null-terminated character string, including the NULL terminator.
type
The data type of the values in the array pointed to by the value data member. Constants (PropertyTagTypeByte, PropertyTagTypeASCII, and the like) that represent various data types are described in Image Property Tag Type Constants.
value
A pointer to an array of values.

The following console application reads and displays the seven pieces of metadata in the file FakePhoto.jpg. The main function relies on the helper function PropertyTypeFromWORD, which is shown following the main function.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   UINT  size = 0;
   UINT  count = 0;
   WCHAR strPropertyType[50] = L"";

   Bitmap* bitmap = new Bitmap(L"FakePhoto.jpg");

   bitmap->GetPropertySize(&size, &count);
   printf("There are %d pieces of metadata in the file.\n\n", count);

   // GetAllPropertyItems returns an array of PropertyItem objects.
   // Allocate a buffer large enough to receive that array.
   PropertyItem* pPropBuffer =(PropertyItem*)malloc(size);

   // Get the array of PropertyItem objects.
   bitmap->GetAllPropertyItems(size, count, pPropBuffer);

   // For each PropertyItem in the array, display the id, type, and length.
   for(UINT j = 0; j < count; ++j)
   {
      // Convert the property type from a WORD to a string.
      PropertyTypeFromWORD(pPropBuffer[j].type, strPropertyType);

      printf("Property Item %d\n", j);
      printf("  id: 0x%x\n", pPropBuffer[j].id);
      wprintf(L"  type: %s\n", strPropertyType);
      printf("  length: %d bytes\n\n", pPropBuffer[j].length);
   }

   free(pPropBuffer);
   delete bitmap;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

// Helper function
void PropertyTypeFromWORD(WORD index, WCHAR* string)
{
   WCHAR* propertyTypes[] = {
      L"Nothing",                   // 0
      L"PropertyTagTypeByte",       // 1
      L"PropertyTagTypeASCII",      // 2
      L"PropertyTagTypeShort",      // 3
      L"PropertyTagTypeLong",       // 4
      L"PropertyTagTypeRational",   // 5
      L"Nothing",                   // 6
      L"PropertyTagTypeUndefined",  // 7
      L"Nothing",                   // 8
      L"PropertyTagTypeSLONG",      // 9
      L"PropertyTagTypeSRational"}; // 10

   wcscpy(string, propertyTypes[index]);
}

The preceding console application produces the following output:

Property Item 0
  id: 0x320
  type: PropertyTagTypeASCII
  length: 16 bytes

Property Item 1
  id: 0x10f
  type: PropertyTagTypeASCII
  length: 17 bytes

Property Item 2
  id: 0x110
  type: PropertyTagTypeASCII
  length: 7 bytes

Property Item 3
  id: 0x9003
  type: PropertyTagTypeASCII
  length: 20 bytes

Property Item 4
  id: 0x829a
  type: PropertyTagTypeRational
  length: 8 bytes

Property Item 5
  id: 0x5090
  type: PropertyTagTypeShort
  length: 128 bytes

Property Item 6
  id: 0x5091
  type: PropertyTagTypeShort
  length: 128 bytes

The preceding output shows a hexadecimal ID number for each property item. You can look up those ID numbers in Image Property Tag Constants and find out that they represent the following property tags.

Hexadecimal value | Property tag
0x0320 0x010f 0x0110 0x9003 0x829a 0x5090 0x5091 | PropertyTagImageTitle PropertyTagEquipMake PropertyTagEquipModel PropertyTagExifDTOriginal PropertyTagExifExposureTime PropertyTagLuminanceTable PropertyTagChrominanceTable

The second (index 1) property item in the list has id PropertyTagEquipMake and type PropertyTagTypeASCII. The following example, which is a continuation of the previous console application, displays the value of that property item:

printf("The equipment make is %s.\n", pPropBuffer[1].value);

The preceding line of code produces the following output:

The equipment make is Northwind Traders.

The fifth (index 4) property item in the list has id PropertyTagExifExposureTime and type PropertyTagTypeRational. That data type (PropertyTagTypeRational) is a pair of LONGs. The following example, which is a continuation of the previous console application, displays those two LONG values as a fraction. That fraction, 1/125, is the exposure time measured in seconds.

long* ptrLong = (long*)(pPropBuffer[4].value);
printf("The exposure time is %d/%d.\n", ptrLong[0], ptrLong[1]);

The preceding code produces the following output:

The exposure time is 1/125.

Writing Metadata to a File

To write an item of metadata to an Image object, initialize a PropertyItem object and then pass the address of that PropertyItem object to the SetPropertyItem method of the Image object.

The following console application writes one item (the image title) of metadata to an Image object and then saves the image in the disk file FakePhoto2.jpg. The main function relies on the helper function GetEncoderClsid, which is shown in the topic Retrieving the Class Identifier for an Encoder.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Status stat;
   CLSID  clsid;
   char   propertyValue[] = "Fake Photograph";

   Bitmap* bitmap = new Bitmap(L"FakePhoto.jpg");
   PropertyItem* propertyItem = new PropertyItem;

   // Get the CLSID of the JPEG encoder.
   GetEncoderClsid(L"image/jpeg", &clsid);

   propertyItem->id = PropertyTagImageTitle;
   propertyItem->length = 16;  // string length including NULL terminator
   propertyItem->type = PropertyTagTypeASCII;
   propertyItem->value = propertyValue;

   bitmap->SetPropertyItem(propertyItem);

   stat = bitmap->Save(L"FakePhoto2.jpg", &clsid, NULL);
   if(stat == Ok)
      printf("FakePhoto2.jpg saved successfully.\n");

   delete propertyItem;
   delete bitmap;
   GdiplusShutdown(gdiplusToken);
   return 0;
}


Using Image Encoders and Decoders

GDI+ provides the Image class and the Bitmap class for storing images in memory and manipulating images in memory. GDI+ writes images to disk files with the help of image encoders and loads images from disk files with the help of image decoders. An encoder translates the data in an Image or Bitmap object into a designated disk file format. A decoder translates the data in a disk file to the format required by the Image and Bitmap objects. GDI+ has built-in encoders and decoders that support the following file types:

  • BMP
  • GIF
  • JPEG
  • PNG
  • TIFF

GDI+ also has built-in decoders that support the following file types:

  • WMF
  • EMF
  • ICON

The following topics discuss encoders and decoders in more detail:

  • Listing Installed Encoders
  • Listing Installed Decoders
  • Retrieving the Class Identifier for an Encoder
  • Determining the Parameters Supported by an Encoder
  • Converting a BMP Image to a PNG Image
  • Setting JPEG Compression Level
  • Transforming a JPEG Image Without Loss of Information
  • Creating and Saving a Multiple-Frame Image
  • Copying Individual Frames from a Multiple-Frame Image


Listing Installed Encoders

GDI+ provides the GetImageEncoders function so that you can determine which image encoders are available on your computer. GetImageEncoders returns an array of ImageCodecInfo objects. Before you call GetImageEncoders, you must allocate a buffer large enough to receive that array. You can call GetImageEncodersSize to determine the size of the required buffer.

The following console application lists the available image encoders:

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   UINT  num;        // number of image encoders
   UINT  size;       // size, in bytes, of the image encoder array

   ImageCodecInfo* pImageCodecInfo;

   // How many encoders are there?
   // How big (in bytes) is the array of all ImageCodecInfo objects?
   GetImageEncodersSize(&num, &size);

   // Create a buffer large enough to hold the array of ImageCodecInfo
   // objects that will be returned by GetImageEncoders.
   pImageCodecInfo = (ImageCodecInfo*)(malloc(size));

   // GetImageEncoders creates an array of ImageCodecInfo objects
   // and copies that array into a previously allocated buffer.
   // The third argument, imageCodecInfo, is a pointer to that buffer.
   GetImageEncoders(num, size, pImageCodecInfo);

   // Display the graphics file format (MimeType)
   // for each ImageCodecInfo object.
   for(UINT j = 0; j < num; ++j)
   {
      wprintf(L"%s\n", pImageCodecInfo[j].MimeType);
   }

   free(pImageCodecInfo);
   GdiplusShutdown(gdiplusToken);
   return 0;
}

When you run the preceding console application, the output will be similar to the following:

image/bmp
image/jpeg
image/gif
image/tiff
image/png


Listing Installed Decoders

GDI+ provides the GetImageDecoders function so that you can determine which image decoders are available on your computer. GetImageDecoders returns an array of ImageCodecInfo objects. Before you call GetImageDecoders, you must allocate a buffer large enough to receive that array. You can call GetImageDecodersSize to determine the size of the required buffer.

The following console application lists the available image decoders:

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   UINT  num;        // number of image decoders
   UINT  size;       // size, in bytes, of the image decoder array

   ImageCodecInfo* pImageCodecInfo;

   // How many decoders are there?
   // How big (in bytes) is the array of all ImageCodecInfo objects?
   GetImageDecodersSize(&num, &size);

   // Create a buffer large enough to hold the array of ImageCodecInfo
   // objects that will be returned by GetImageDecoders.
   pImageCodecInfo = (ImageCodecInfo*)(malloc(size));

   // GetImageDecoders creates an array of ImageCodecInfo objects
   // and copies that array into a previously allocated buffer.
   // The third argument, imageCodecInfo, is a pointer to that buffer.
   GetImageDecoders(num, size, pImageCodecInfo);

   // Display the graphics file format (MimeType)
   // for each ImageCodecInfo object.
   for(UINT j = 0; j < num; ++j)
   {
      wprintf(L"%s\n", pImageCodecInfo[j].MimeType);
   }

   free(pImageCodecInfo);
   GdiplusShutdown(gdiplusToken);
   return 0;
}

When you run the preceding console application, the output will be similar to the following:

image/bmp
image/jpeg
image/gif
image/x-emf
image/x-wmf
image/tiff
image/png
image/x-icon


Retrieving the Class Identifier for an Encoder

The function GetEncoderClsid in the following example receives the MIME type of an encoder and returns the class identifier (CLSID) of that encoder. The MIME types of the encoders built into GDI+ are as follows:

  • image/bmp
  • image/jpeg
  • image/gif
  • image/tiff
  • image/png

The function calls GetImageEncoders to get an array of ImageCodecInfo objects. If one of the ImageCodecInfo objects in that array represents the requested encoder, the function returns the index of the ImageCodecInfo object and copies the CLSID into the variable pointed to by pClsid. If the function fails, it returns –1.

int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
   UINT  num = 0;          // number of image encoders
   UINT  size = 0;         // size of the image encoder array in bytes

   ImageCodecInfo* pImageCodecInfo = NULL;

   GetImageEncodersSize(&num, &size);
   if(size == 0)
      return -1;  // Failure

   pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
   if(pImageCodecInfo == NULL)
      return -1;  // Failure

   GetImageEncoders(num, size, pImageCodecInfo);

   for(UINT j = 0; j < num; ++j)
   {
      if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 )
      {
         *pClsid = pImageCodecInfo[j].Clsid;
         free(pImageCodecInfo);
         return j;  // Success
      }
   }

   free(pImageCodecInfo);
   return -1;  // Failure
}

The following console application calls the GetEncoderClsid function to determine the CLSID of the PNG encoder:

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

#include "GdiplusHelperFunctions.h"

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   CLSID  encoderClsid;
   INT    result;
   WCHAR  strGuid[39];

   result = GetEncoderClsid(L"image/png", &encoderClsid);

   if(result < 0)
   {
      printf("The PNG encoder is not installed.\n");
   }
   else
   {
      StringFromGUID2(encoderClsid, strGuid, 39);
      printf("An ImageCodecInfo object representing the PNG encoder\n");
      printf("was found at position %d in the array.\n", result);
      wprintf(L"The CLSID of the PNG encoder is %s.\n", strGuid);
   }

   GdiplusShutdown(gdiplusToken);
   return 0;
}

When you run the preceding console application, you get an output similar to the following:

An ImageCodecInfo object representing the PNG encoder
was found at position 4 in the array.
The CLSID of the PNG encoder is {557CF406-1A04-11D3-9A73-0000F81EF32E}.


Determining the Parameters Supported by an Encoder

The Image class provides the GetEncoderParameterList method so that you can determine the parameters that are supported by a given image encoder. The GetEncoderParameterList method returns an array of EncoderParameter objects. You must allocate a buffer to receive that array before you call GetEncoderParameterList. You can call GetEncoderParameterListSize to determine the size of the required buffer.

The following console application obtains the parameter list for the JPEG encoder. The main function relies on the helper function GetEncoderClsid, which is shown in Retrieving the Class Identifier for an Encoder.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT GetEncoderClsid(const WCHAR* format, CLSID* pClsid);  // helper function

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   // Create Bitmap (inherited from Image) object so that we can call
   // GetParameterListSize and GetParameterList.
   Bitmap* bitmap = new Bitmap(1, 1);

   // Get the JPEG encoder CLSID.
   CLSID encoderClsid;
   GetEncoderClsid(L"image/jpeg", &encoderClsid);

   // How big (in bytes) is the JPEG encoder's parameter list?
   UINT listSize = 0;
   listSize = bitmap->GetEncoderParameterListSize(&encoderClsid);
   printf("The parameter list requires %d bytes.\n", listSize);

   // Allocate a buffer large enough to hold the parameter list.
   EncoderParameters* pEncoderParameters = NULL;
   pEncoderParameters = (EncoderParameters*)malloc(listSize);

   // Get the parameter list for the JPEG encoder.
   bitmap->GetEncoderParameterList(
      &encoderClsid, listSize, pEncoderParameters);

   // pEncoderParameters points to an EncoderParameters object, which
   // has a Count member and an array of EncoderParameter objects.
   // How many EncoderParameter objects are in the array?
   printf("There are %d EncoderParameter objects in the array.\n",
      pEncoderParameters->Count);

   free(pEncoderParameters);
   delete(bitmap);
   GdiplusShutdown(gdiplusToken);
   return 0;
}

When you run the preceding console application, you get an output similar to the following:

The parameter list requires 172 bytes.
There are 4 EncoderParameter objects in the array.

Each of the EncoderParameter objects in the array has the following four public data members:

Guid
Identifies the category of the EncoderParameter object. There are several standard categories (EncoderSaveFlag, EncoderCompression, EncoderQuality, and the like) defined in Gdiplusimaging.h.
NumberOfValues
The number of values in the Value array.
Type
The data type of the values in the Value array.
Value
Pointer to an array of values. GetEncoderParameterList puts values in this array to indicate possible values that can be passed to the encoder through this category (identified by the Guid member) of parameter.

The following code is a continuation of the console application shown in the preceding example. The code looks at the second EncoderParameter object in the array returned by GetEncoderParameterList. The code calls StringFromGUID2, which is a system function declared in Objbase.h, to convert the Guid member of the EncoderParameter object to a string.

// Look at the second (index 1) EncoderParameter object in the array.
printf("Parameter[1]\n");

WCHAR strGuid[39];
StringFromGUID2(pEncoderParameters->Parameter[1].Guid, strGuid, 39);
wprintf(L"   The GUID is %s.\n", strGuid);

printf("   The value type is %d.\n",
   pEncoderParameters->Parameter[1].Type);

printf("   The number of values is %d.\n",
   pEncoderParameters->Parameter[1].NumberOfValues);

The preceding code produces the following output:

Parameter[1]
   The GUID is {1D5BE4B5-FA4A-452D-9CDD-5DB35105E7EB}.
   The value type is 6.
   The number of values is 1.

You can look up the GUID in Gdiplusimaging.h and find out that the category of this EncoderParameter object is EncoderQuality. You can use this category (EncoderQuality) of parameter to set the compression level of a JPEG image.

In Gdiplusenums.h, the EncoderParameterValueType enumeration indicates that data type 6 is ValueLongRange. A long range is a pair of ULONGs.

The number of values is one, so we know that the Value member of the EncoderParameter object is a pointer to an array that has one element. That one element is a pair of ULONGs.

The following code is a continuation of the console application that is shown in the preceding two examples. The code defines a data type called PLONGRANGE (pointer to a long range). A variable of type PLONGRANGE is used to extract the minimum and maximum values that can be passed as a quality setting to the JPEG encoder.

typedef struct
   {
      long min;
      long max;
   }* PLONGRANGE;

   PLONGRANGE pLongRange =
      (PLONGRANGE)(pEncoderParameters->Parameter[1].Value);

   printf("   The minimum possible quality value is %d.\n",
      pLongRange->min);

   printf("   The maximum possible quality value is %d.\n",
      pLongRange->max);

The preceding code produces the following output:

The minimum possible quality value is 0.
The maximum possible quality value is 100.

In the preceding example, the value returned in the EncoderParameter object is a pair of ULONGs that indicate the minimum and maximum possible values for the quality parameter. In some cases, the values returned in an EncoderParameter object are members of the EncoderValue enumeration. The following topics discuss the EncoderValue enumeration and methods for listing possible parameter values in more detail:

  • Using the EncoderValue Enumeration
  • Listing Parameters and Values for All Encoders


Using the EncoderValue Enumeration

A given encoder supports certain parameter categories, and for each of those categories, that encoder allows certain values. For example, the JPEG encoder supports the EncoderValueQuality parameter category, and the allowable parameter values are the integers 0 through 100. Some of the allowable parameter values are the same across several encoders. These standard values are defined in the EncoderValue enumeration in Gdiplusenums.h:

enum EncoderValue
{
   EncoderValueColorTypeCMYK,             // 0
   EncoderValueColorTypeYCCK,             // 1
   EncoderValueCompressionLZW,            // 2
   EncoderValueCompressionCCITT3,         // 3
   EncoderValueCompressionCCITT4,         // 4
   EncoderValueCompressionRle,            // 5
   EncoderValueCompressionNone,           // 6
   EncoderValueScanMethodInterlaced,      // 7
   EncoderValueScanMethodNonInterlaced,   // 8
   EncoderValueVersionGif87,              // 9
   EncoderValueVersionGif89,              // 10
   EncoderValueRenderProgressive,         // 11
   EncoderValueRenderNonProgressive,      // 12
   EncoderValueTransformRotate90,         // 13
   EncoderValueTransformRotate180,        // 14
   EncoderValueTransformRotate270,        // 15
   EncoderValueTransformFlipHorizontal,   // 16
   EncoderValueTransformFlipVertical,     // 17
   EncoderValueMultiFrame,                // 18
   EncoderValueLastFrame,                 // 19
   EncoderValueFlush,                     // 20
   EncoderValueFrameDimensionTime,        // 21
   EncoderValueFrameDimensionResolution,  // 22
   EncoderValueFrameDimensionPage         // 23
};

One of the parameter categories supported by the JPEG encoder is the EncoderTransformation category. By examining the EncoderValue enumeration, you might speculate (and you would be correct) that the EncoderTransformation category allows the following five values:

EncoderValueTransformRotate90,          // 13
EncoderValueTransformRotate180,         // 14
EncoderValueTransformRotate270,         // 15
EncoderValueTransformFlipHorizontal,    // 16
EncoderValueTransformFlipVertical,      // 17

The following console application verifies that the JPEG encoder supports the EncoderTransformation parameter category and that there are five allowable values for such a parameter. The main function relies on the helper function GetEncoderClsid, which is shown in Retrieving the Class Identifier for an Encoder.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT GetEncoderClsid(const WCHAR* format, CLSID* pClsid);

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   // Create a Bitmap (inherited from Image) object so that we can call
   // GetParameterListSize and GetParameterList.
   Bitmap* bitmap = new Bitmap(1, 1);

   // Get the JPEG encoder CLSID.
   CLSID encoderClsid;
   GetEncoderClsid(L"image/jpeg", &encoderClsid);

   // How big (in bytes) is the JPEG encoder's parameter list?
   UINT listSize = 0;
   listSize = bitmap->GetEncoderParameterListSize(&encoderClsid);
   printf("The parameter list requires %d bytes.\n", listSize);

   // Allocate a buffer large enough to hold the parameter list.
   EncoderParameters* pEncoderParameters = NULL;
   pEncoderParameters = (EncoderParameters*)malloc(listSize);

   // Get the parameter list for the JPEG encoder.
   bitmap->GetEncoderParameterList(
      &encoderClsid, listSize, pEncoderParameters);

   // pEncoderParameters points to an EncoderParameters object, which
   // has a Count member and an array of EncoderParameter objects.
   // How many EncoderParameter objects are in the array?
   printf("There are %d EncoderParameter objects in the array.\n",
      pEncoderParameters->Count);

   // Look at the first (index 0) EncoderParameter object in the array.
   printf("Parameter[0]\n");

   WCHAR strGuid[39];
   StringFromGUID2(pEncoderParameters->Parameter[0].Guid, strGuid, 39);
   wprintf(L"   The guid is %s.\n", strGuid);

   printf("   The data type is %d.\n",
      pEncoderParameters->Parameter[0].Type);

   printf("   The number of values is %d.\n",
      pEncoderParameters->Parameter[0].NumberOfValues);

   free(pEncoderParameters);
   delete bitmap;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

When you run the preceding console application, you get an output similar to the following:

The parameter list requires 172 bytes.
There are 4 EncoderParameter objects in the array.
Parameter[0]
   The GUID is {8D0EB2D1-A58E-4EA8-AA14-108074B7B6F9}.
   The value type is 4.
   The number of values is 5.

You can look up the GUID in Gdiplusimaging.h and find out that the category of this EncoderParameter object is EncoderTransformation. In Gdiplusenums.h, the EncoderParameterValueType enumeration indicates that data type 4 is ValueLong (32-bit unsigned integer). The number of values is five, so we know that the Value member of the EncoderParameter object is a pointer to an array of five ULONGs.

The following code is a continuation of the console application that is shown in the preceding example. The code lists the allowable values for an EncoderTransformation parameter:

ULONG* pUlong = (ULONG*)(pEncoderParameters->Parameter[0].Value);
ULONG numVals = pEncoderParameters->Parameter[0].NumberOfValues;

printf("%s", "   The allowable values are");
for(ULONG j = 0; j < numVals; ++j)
{
   printf("  %d", pUlong[j]);
}

The preceding code produces the following output:

The allowable values are  13  14  15  16  17

The allowable values (13, 14, 15, 16, and 17) correspond to the following members of the EncoderValue enumeration:

EncoderValueTransformRotate90,        // 13
EncoderValueTransformRotate180,       // 14
EncoderValueTransformRotate270,       // 15
EncoderValueTransformFlipHorizontal,  // 16
EncoderValueTransformFlipVertical,    // 17


Listing Parameters and Values for All Encoders

The following console application lists all the parameters supported by the various encoders installed on the computer. The main function calls GetImageEncoders to discover which encoders are available. For each available encoder, the main function calls the helper function ShowAllEncoderParameters.

The ShowAllEncoderParameters function calls the GetEncoderParameterList method to discover which parameters are supported by a given encoder. For each supported parameter, the function lists the category, data type, and number of values. The ShowAllEncoderParameters function relies on two helper functions: EncoderParameterCategoryFromGUID and ValueTypeFromULONG.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

// Helper functions
void ShowAllEncoderParameters(ImageCodecInfo*);
void EncoderParameterCategoryFromGUID(GUID, WCHAR*);
void ValueTypeFromULONG(ULONG, WCHAR*);

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   UINT  num;        // number of image encoders
   UINT  size;       // size of the image encoder array in bytes

   ImageCodecInfo* pImageCodecInfo;

   // How many encoders are there?
   // How big (in bytes) is the array of all ImageCodecInfo objects?
   GetImageEncodersSize(&num, &size);

   // Create a buffer large enough to hold the array of ImageCodecInfo
   // objects that will be returned by GetImageEncoders.
   pImageCodecInfo = (ImageCodecInfo*)(malloc(size));

   // GetImageEncoders creates an array of ImageCodecInfo objects
   // and copies that array into a previously allocated buffer.
   // The third argument, imageCodecInfo, is a pointer to that buffer.
   GetImageEncoders(num, size, pImageCodecInfo);

   // For each ImageCodecInfo object in the array, show all parameters.
   for(UINT j = 0; j < num; ++j)
   {
      ShowAllEncoderParameters(&(pImageCodecInfo[j]));
   }

   free(pImageCodecInfo);
   GdiplusShutdown(gdiplusToken);
   return 0;
}

/////////////////////////////////////////////////
// Helper functions

void ShowAllEncoderParameters(ImageCodecInfo* pImageCodecInfo)
{
   WCHAR strParameterCategory[50] = L"";
   WCHAR strValueType[50] = L"";

   wprintf(L"\n\n%s\n", pImageCodecInfo->MimeType);

   // Create a Bitmap (inherited from Image) object so that we can call
   // GetParameterListSize and GetParameterList.
   Bitmap bitmap(1, 1);

   // How big (in bytes) is the encoder's parameter list?
   UINT listSize = 0;
   listSize = bitmap.GetEncoderParameterListSize(&pImageCodecInfo->Clsid);
   printf("  The parameter list requires %d bytes.\n", listSize);

   if(listSize == 0)
      return;

   // Allocate a buffer large enough to hold the parameter list.
   EncoderParameters* pEncoderParameters = NULL;
   pEncoderParameters = (EncoderParameters*)malloc(listSize);

   // Get the parameter list for the encoder.
   bitmap.GetEncoderParameterList(
      &pImageCodecInfo->Clsid, listSize, pEncoderParameters);

   // pEncoderParameters points to an EncoderParameters object, which
   // has a Count member and an array of EncoderParameter objects.
   // How many EncoderParameter objects are in the array?
   printf("  There are %d EncoderParameter objects in the array.\n",
      pEncoderParameters->Count);

   // For each EncoderParameter object in the array, list the
   // parameter category, data type, and number of values.
   for(UINT k = 0; k < pEncoderParameters->Count; ++k)
   {
      EncoderParameterCategoryFromGUID(
         pEncoderParameters->Parameter[k].Guid, strParameterCategory);

      ValueTypeFromULONG(
         pEncoderParameters->Parameter[k].Type, strValueType);

      printf("    Parameter[%d]\n", k);
      wprintf(L"      The category is %s.\n", strParameterCategory);
      wprintf(L"      The data type is %s.\n", strValueType);

      printf("      The number of values is %d.\n",
      pEncoderParameters->Parameter[k].NumberOfValues);
   } // for

   free(pEncoderParameters);
} // ShowAllEncoderParameters

void EncoderParameterCategoryFromGUID(GUID guid, WCHAR* category)
{
   if(guid == EncoderCompression)
      wcscpy(category, L"Compression");
   else if(guid == EncoderColorDepth)
      wcscpy(category, L"ColorDepth");
   else if(guid == EncoderScanMethod)
      wcscpy(category, L"ScanMethod");
   else if(guid == EncoderVersion)
      wcscpy(category, L"Version");
   else if(guid == EncoderRenderMethod)
      wcscpy(category, L"RenderMethod");
   else if(guid == EncoderQuality)
      wcscpy(category, L"Quality");
   else if(guid == EncoderTransformation)
      wcscpy(category, L"Transformation");
   else if(guid == EncoderLuminanceTable)
      wcscpy(category, L"LuminanceTable");
   else if(guid == EncoderChrominanceTable)
      wcscpy(category, L"ChrominanceTable");
   else if(guid == EncoderSaveFlag)
      wcscpy(category, L"SaveFlag");
   else
      wcscpy(category, L"Unknown category");
} // EncoderParameterCategoryFromGUID

void ValueTypeFromULONG(ULONG index, WCHAR* strValueType)
{
   WCHAR* valueTypes[] = {
      L"Nothing",                  // 0
      L"ValueTypeByte",            // 1
      L"ValueTypeASCII",           // 2
      L"ValueTypeShort",           // 3
      L"ValueTypeLong",            // 4
      L"ValueTypeRational",        // 5
      L"ValueTypeLongRange",       // 6
      L"ValueTypeUndefined",       // 7
      L"ValueTypeRationalRange"};  // 8

   wcscpy(strValueType, valueTypes[index]);

} // ValueTypeFromULONG

When you run the preceding console application, you get an output similar to the following:

image/bmp
  The parameter list requires 0 bytes.

image/jpeg
  The parameter list requires 172 bytes.
  There are 4 EncoderParameter objects in the array.
    Parameter[0]
      The category is Transformation.
      The data type is Long.
      The number of values is 5.
    Parameter[1]
      The category is Quality.
      The data type is LongRange.
      The number of values is 1.
    Parameter[2]
      The category is LuminanceTable.
      The data type is Short.
      The number of values is 0.
    Parameter[3]
      The category is ChrominanceTable.
      The data type is Short.
      The number of values is 0.

image/gif
  The parameter list requires 0 bytes.

image/tiff
  The parameter list requires 160 bytes.
  There are 3 EncoderParameter objects in the array.
    Parameter[0]
      The category is Compression.
      The data type is Long.
      The number of values is 5.
    Parameter[1]
      The category is ColorDepth.
      The data type is Long.
      The number of values is 5.
    Parameter[2]
      The category is SaveFlag.
      The data type is Long.
      The number of values is 1.

image/png
  The parameter list requires 0 bytes.

You can draw the following conclusions by examining the preceding program output:

  • The JPEG encoder supports the Transformation, Quality, LuminanceTable, and ChrominanceTable parameter categories.
  • The TIFF encoder supports the Compression, ColorDepth, and SaveFlag parameter categories.

You can also see the number of acceptable values for each parameter category. For example, you can see that the ColorDepth parameter category (TIFF codec) has five values of type ULONG. The following code lists those five values. Assume that pEncoderParameters is a pointer to an EncoderParameters object that represents the TIFF encoder.

ULONG* pUlong = (ULONG*)(pEncoderParameters->Parameter[1].Value);
ULONG numVals = pEncoderParameters->Parameter[1].NumberOfValues;
printf("\nThe allowable values for ColorDepth are\n");

for(ULONG k = 0; k < numVals; ++k)
{
   printf("  %u\n", pUlong[k]);
}

The preceding code produces the following output:

The allowable values for ColorDepth are
  1
  4
  8
  24
  32

Note In some cases, the values in an EncoderParameter object are the numeric values of elements of the EncoderValue enumeration. However, the numbers in the preceding list do not relate to the EncoderValue enumeration. The numbers mean 1 bit per pixel, 2 bits per pixel, and so on.

If you write code similar to the preceding example to investigate the allowable values for the other parameter categories, you will obtain a result similar to the following.

JPEG encoder parameter | Allowable values
Transformation | EncoderValueTransformRotate90 EncoderValueTransformRotate180 EncoderValueTransformRotate270 EncoderValueTransformFlipHorizontal EncoderValueTransformFlipVertical
Quality | 0 through 100

TIFF encoder parameter | Allowable values
Compression | EncoderValueCompressionLZW EncoderValueCompressionCCITT3 EncoderValueCompressionCCITT4 EncoderValueCompressionRle EncoderValueCompressionNone
ColorDepth | 1, 4, 8, 24, 32
SaveFlag | EncoderValueMultiFrame

Note If the width and height of a JPEG image are multiples of 16, you can apply any of the transformations allowed by the EncoderTransformation parameter category (for example, 90-degree rotation) without loss of information.


Converting a BMP Image to a PNG Image

To save an image to a disk file, call the Save method of the Image class. The following console application loads a BMP image from a disk file, converts the image to the PNG format, and saves the converted image to a new disk file. The main function relies on the helper function GetEncoderClsid, which is shown in Retrieving the Class Identifier for an Encoder.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT GetEncoderClsid(const WCHAR* format, CLSID* pClsid);  // helper function

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   CLSID   encoderClsid;
   Status  stat;
   Image*   image = new Image(L"Bird.bmp");

   // Get the CLSID of the PNG encoder.
   GetEncoderClsid(L"image/png", &encoderClsid);

   stat = image->Save(L"Bird.png", &encoderClsid, NULL);

   if(stat == Ok)
      printf("Bird.png was saved successfully\n");
   else
      printf("Failure: stat = %d\n", stat);

   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}


Setting JPEG Compression Level

To specify the compression level when you save a JPEG image, initialize an EncoderParameters object and pass the address of that object to the Save method of the Image class. Initialize the EncoderParameters object so that it has an array consisting of one EncoderParameter object. Initialize that one EncoderParameter object so that its Value member points to a ULONG value from 0 through 100. Set the Guid member of the EncoderParameter object to EncoderQuality.

The following console application saves three JPEG images, each with a different quality level. A quality level of 0 corresponds to the greatest compression, and a quality level of 100 corresponds to the least compression.

The main function relies on the helper function GetEncoderClsid, which is shown in Retrieving the Class Identifier for an Encoder:

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT GetEncoderClsid(const WCHAR* format, CLSID* pClsid);  // helper function

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   CLSID             encoderClsid;
   EncoderParameters encoderParameters;
   ULONG             quality;
   Status            stat;

   // Get an image from the disk.
   Image* image = new Image(L"Shapes.bmp");

   // Get the CLSID of the JPEG encoder.
   GetEncoderClsid(L"image/jpeg", &encoderClsid);

   // Before we call Image::Save, we must initialize an
   // EncoderParameters object. The EncoderParameters object
   // has an array of EncoderParameter objects. In this
   // case, there is only one EncoderParameter object in the array.
   // The one EncoderParameter object has an array of values.
   // In this case, there is only one value (of type ULONG)
   // in the array. We will let this value vary from 0 to 100.

   encoderParameters.Count = 1;
   encoderParameters.Parameter[0].Guid = EncoderQuality;
   encoderParameters.Parameter[0].Type = EncoderParameterValueTypeLong;
   encoderParameters.Parameter[0].NumberOfValues = 1;

   // Save the image as a JPEG with quality level 0.
   quality = 0;
   encoderParameters.Parameter[0].Value = &quality;
   stat = image->Save(L"Shapes001.jpg", &encoderClsid, &encoderParameters);

   if(stat == Ok)
      wprintf(L"%s saved successfully.\n", L"Shapes001.jpg");
   else
      wprintf(L"%d  Attempt to save %s failed.\n", stat, L"Shapes001.jpg");

   // Save the image as a JPEG with quality level 50.
   quality = 50;
   encoderParameters.Parameter[0].Value = &quality;
   stat = image->Save(L"Shapes050.jpg", &encoderClsid, &encoderParameters);

   if(stat == Ok)
      wprintf(L"%s saved successfully.\n", L"Shapes050.jpg");
   else
      wprintf(L"%d  Attempt to save %s failed.\n", stat, L"Shapes050.jpg");

      // Save the image as a JPEG with quality level 100.
   quality = 100;
   encoderParameters.Parameter[0].Value = &quality;
   stat = image->Save(L"Shapes100.jpg", &encoderClsid, &encoderParameters);

   if(stat == Ok)
      wprintf(L"%s saved successfully.\n", L"Shapes100.jpg");
   else
      wprintf(L"%d  Attempt to save %s failed.\n", stat, L"Shapes100.jpg");

   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}


Transforming a JPEG Image Without Loss of Information

When you compress a JPEG image, some of the information in the image is lost. If you open a JPEG file, alter the image, and save it to another JPEG file, the quality will decrease. If you repeat that process many times, you will see a substantial degradation in the image quality.

Because JPEG is one of the most popular image formats on the Web, and because people often like to modify JPEG images, GDI+ provides the following transformations that can be performed on JPEG images without loss of information:

  • Rotate 90 degrees
  • Rotate 180 degrees
  • Rotate 270 degrees
  • Flip horizontally
  • Flip vertically

You can apply one of the transformations shown in the preceding list when you call the Save method of an Image object. If the following conditions are met, then the transformation will proceed without loss of information:

  • The file used to construct the Image object is a JPEG file.
  • The width and height of the image are both multiples of 16.

If the width and height of the image are not both multiples of 16, GDI+ will do its best to preserve the image quality when you apply one of the rotation or flipping transformations shown in the preceding list.

To transform a JPEG image, initialize an EncoderParameters object and pass the address of that object to the Save method of the Image class. Initialize the EncoderParameters object so that it has an array that consists of one EncoderParameter object. Initialize that one EncoderParameter object so that its Value member points to a ULONG variable that holds one of the following elements of the EncoderValue enumeration:

  • EncoderValueTransformRotate90,
  • EncoderValueTransformRotate180,
  • EncoderValueTransformRotate270,
  • EncoderValueTransformFlipHorizontal,
  • EncoderValueTransformFlipVertical

Set the Guid member of the EncoderParameter object to EncoderTransformation.

The following console application creates an Image object from a JPEG file and then saves the image to a new file. During the save process, the image is rotated 90 degrees. If the width and height of the image are both multiples of 16, the process of rotating and saving the image causes no loss of information.

The main function relies on the helper function GetEncoderClsid, which is shown in Retrieving the Class Identifier for an Encoder.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT GetEncoderClsid(const WCHAR* format, CLSID* pClsid);  // helper function

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   CLSID             encoderClsid;
   EncoderParameters encoderParameters;
   ULONG             transformation;
   UINT              width;
   UINT              height;
   Status            stat;

   // Get a JPEG image from the disk.
   Image* image = new Image(L"Shapes.jpg");

   // Determine whether the width and height of the image
   // are multiples of 16.
   width = image->GetWidth();
   height = image->GetHeight();

   printf("The width of the image is %u", width);
   if(width / 16.0 - width / 16 == 0)
      printf(", which is a multiple of 16.\n");
   else
      printf(", which is not a multiple of 16.\n");

   printf("The height of the image is %u", height);
   if(height / 16.0 - height / 16 == 0)
      printf(", which is a multiple of 16.\n");
   else
      printf(", which is not a multiple of 16.\n");

   // Get the CLSID of the JPEG encoder.
   GetEncoderClsid(L"image/jpeg", &encoderClsid);

   // Before we call Image::Save, we must initialize an
   // EncoderParameters object. The EncoderParameters object
   // has an array of EncoderParameter objects. In this
   // case, there is only one EncoderParameter object in the array.
   // The one EncoderParameter object has an array of values.
   // In this case, there is only one value (of type ULONG)
   // in the array. We will set that value to EncoderValueTransformRotate90.

   encoderParameters.Count = 1;
   encoderParameters.Parameter[0].Guid = EncoderTransformation;
   encoderParameters.Parameter[0].Type = EncoderParameterValueTypeLong;
   encoderParameters.Parameter[0].NumberOfValues = 1;

   // Rotate and save the image.
   transformation = EncoderValueTransformRotate90;
   encoderParameters.Parameter[0].Value = &transformation;
   stat = image->Save(L"ShapesR90.jpg", &encoderClsid, &encoderParameters);

   if(stat == Ok)
      wprintf(L"%s saved successfully.\n", L"ShapesR90.jpg");
   else
      wprintf(L"%d  Attempt to save %s failed.\n", stat, L"ShapesR90.jpg");

   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}


Creating and Saving a Multiple-Frame Image

With certain file formats, you can save multiple images (frames) to a single file. For example, you can save several pages to a single TIFF file. To save the first page, call the Save method of the Image class. To save subsequent pages, call the SaveAdd method of the Image class.

The following console application creates a TIFF file with four pages. The images that become the pages of the TIFF file come from four disk files: Shapes.bmp, Cereal.gif, Iron.jpg, and House.png. The code first constructs four Image objects: multi, page2, page3, and page4. At first, multi contains only the image from Shapes.bmp, but eventually it contains all four images. As the individual pages are added to the multi Image object, they are also added to the disk file Multiframe.tif.

Note that the code calls Save (not SaveAdd) to save the first page. The first argument passed to the Save method is the name of the disk file that will eventually contain several frames. The second argument passed to the Save method specifies the encoder that will be used to convert the data in the multi Image object to the format (in this case TIFF) required by the disk file. That same encoder is used automatically by all subsequent calls to the SaveAdd method of the multi Image object.

The third argument passed to the Save method is the address of an EncoderParameters object. The EncoderParameters object has an array that contains a single EncoderParameter object. The Guid member of that EncoderParameter object is set to EncoderSaveFlag. The Value member of the EncoderParameter object points to a ULONG that contains the value EncoderValueMultiFrame.

The code saves the second, third, and fourth pages by calling the SaveAdd method of the multi Image object. The first argument passed to the SaveAdd method is the address of an Image object. The image in that Image object is added to the multi Image object and is also added to the Multiframe.tif disk file. The second argument passed to the SaveAdd method is the address of the same EncoderParameters object that was used by the Save method. The difference is that the ULONG pointed to by the Value member now contains the value EncoderValueFrameDimensionPage.

The main function relies on the helper function GetEncoderClsid, which is shown in Retrieving the Class Identifier for an Encoder.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT GetEncoderClsid(const WCHAR* format, CLSID* pClsid);  // helper function

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   EncoderParameters encoderParameters;
   ULONG             parameterValue;
   Status            stat;

   // An EncoderParameters object has an array of
   // EncoderParameter objects. In this case, there is only
   // one EncoderParameter object in the array.
   encoderParameters.Count = 1;

   // Initialize the one EncoderParameter object.
   encoderParameters.Parameter[0].Guid = EncoderSaveFlag;
   encoderParameters.Parameter[0].Type = EncoderParameterValueTypeLong;
   encoderParameters.Parameter[0].NumberOfValues = 1;
   encoderParameters.Parameter[0].Value = &parameterValue;

   // Get the CLSID of the TIFF encoder.
   CLSID encoderClsid;
   GetEncoderClsid(L"image/tiff", &encoderClsid);

   // Create four image objects.
   Image* multi = new Image(L"Shapes.bmp");
   Image* page2 = new Image(L"Cereal.gif");
   Image* page3 = new Image(L"Iron.jpg");
   Image* page4 = new Image(L"House.png");

   // Save the first page (frame).
   parameterValue = EncoderValueMultiFrame;
   stat = multi->Save(L"MultiFrame.tif", &encoderClsid, &encoderParameters);
   if(stat == Ok)
      printf("Page 1 saved successfully.\n");

   // Save the second page (frame).
   parameterValue = EncoderValueFrameDimensionPage;
   stat = multi->SaveAdd(page2, &encoderParameters);
   if(stat == Ok)
      printf("Page 2 saved successfully.\n");

   // Save the third page (frame).
   parameterValue = EncoderValueFrameDimensionPage;
   stat = multi->SaveAdd(page3, &encoderParameters);
   if(stat == Ok)
      printf("Page 3 saved successfully.\n");

   // Save the fourth page (frame).
   parameterValue = EncoderValueFrameDimensionPage;
   stat = multi->SaveAdd(page4, &encoderParameters);
   if(stat == Ok)
      printf("Page 4 saved successfully.\n");

   // Close the multiframe file.
   parameterValue = EncoderValueFlush;
   stat = multi->SaveAdd(&encoderParameters);
   if(stat == Ok)
      printf("File closed successfully.\n");

   delete multi;
   delete page2;
   delete page3;
   delete page4;
   GdiplusShutdown(gdiplusToken);
   return 0;
}


Copying Individual Frames from a Multiple-Frame Image

The following example retrieves the individual frames from a multiple-frame TIFF file. When the TIFF file was created, the individual frames were added to the Page dimension (see Creating and Saving a Multiple-Frame Image). The code displays each of the four pages and saves each page to a separate PNG disk file.

The code constructs an Image object from the multiple-frame TIFF file. To retrieve the individual frames (pages), the code calls the SelectActiveFrame method of that Image object. The first argument passed to the SelectActiveFrame method is the address of a GUID that specifies the dimension in which the frames were previously added to the multiple-frame TIFF file. The GUID FrameDimensionPage is defined in Gdiplusimaging.h. Other GUIDs defined in that header file are FrameDimensionTime and FrameDimensionResolution. The second argument passed to the SelectActiveFrame method is the zero-based index of the desired page.

The code relies on the helper function GetEncoderClsid, which is shown in Retrieving the Class Identifier for an Encoder.

GUID   pageGuid = FrameDimensionPage;
CLSID  encoderClsid;
Image  multi(L"Multiframe.tif");

// Get the CLSID of the PNG encoder.
GetEncoderClsid(L"image/png", &encoderClsid);

// Display and save the first page (index 0).
multi.SelectActiveFrame(&pageGuid, 0);
graphics.DrawImage(&multi, 10, 10);
multi.Save(L"Page0.png", &encoderClsid, NULL);

// Display and save the second page.
multi.SelectActiveFrame(&pageGuid, 1);
graphics.DrawImage(&multi, 200, 10);
multi.Save(L"Page1.png", &encoderClsid, NULL);

// Display and save the third page.
multi.SelectActiveFrame(&pageGuid, 2);
graphics.DrawImage(&multi, 10, 150);
multi.Save(L"Page2.png", &encoderClsid, NULL);

// Display and save the fourth page.
multi.SelectActiveFrame(&pageGuid, 3);
graphics.DrawImage(&multi, 200, 150);
multi.Save(L"Page3.png", &encoderClsid, NULL);

The following illustration shows the individual pages as displayed by the preceding code.


Alpha Blending Lines and Fills

In GDI+, a color is a 32-bit value with 8 bits each for alpha, red, green, and blue. The alpha value indicates the transparency of the color — the extent to which the color is blended with the background color. Alpha values range from 0 through 255, where 0 represents a fully transparent color, and 255 represents a fully opaque color.

Alpha blending is a pixel-by-pixel blending of source and background color data. Each of the three components (red, green, blue) of a given source color is blended with the corresponding component of the background color according to the following formula:

displayColor = sourceColor×alpha / 255 + backgroundColor×(255 – alpha) / 255

For example, suppose the red component of the source color is 150 and the red component of the background color is 100. If the alpha value is 200, the red component of the resultant color is calculated as follows:

150×200 / 255 + 100×(255 – 200) / 255 = 139

The following topics cover alpha blending in more detail:

  • Drawing Opaque and Semitransparent Lines
  • Drawing with Opaque and Semitransparent Brushes
  • Using Compositing Mode to Control Alpha Blending
  • Using a Color Matrix to Set Alpha Values in Images
  • Setting the Alpha Values of Individual Pixels


Drawing Opaque and Semitransparent Lines

When you draw a line, you must pass the address of a Pen object to the DrawLine method of the Graphics class. One of the parameters of the Pen constructor is a Color object. To draw an opaque line, set the alpha component of the color to 255. To draw a semitransparent line, set the alpha component to any value from 1 through 254.

When you draw a semitransparent line over a background, the color of the line is blended with the colors of the background. The alpha component specifies how the line and background colors are mixed; alpha values near 0 place more weight on the background colors, and alpha values near 255 place more weigh on the line color.

The following example draws an image and then draws three lines that use the image as a background. The first line uses an alpha component of 255, so it is opaque. The second and third lines use an alpha component of 128, so they are semitransparent; you can see the background image through the lines. The call to SetCompositingQuality causes the blending for the third line to be done in conjunction with gamma correction.

Image image(L"Texture1.jpg");
graphics.DrawImage(&image, 10, 5, image.GetWidth(), image.GetHeight());

Pen opaquePen(Color(255, 0, 0, 255), 15);
Pen semiTransPen(Color(128, 0, 0, 255), 15);

graphics.DrawLine(&opaquePen, 0, 20, 100, 20);
graphics.DrawLine(&semiTransPen, 0, 40, 100, 40);

graphics.SetCompositingQuality(CompositingQualityGammaCorrected);
graphics.DrawLine(&semiTransPen, 0, 60, 100, 60);

The following illustration shows the output of the preceding code.


Drawing with Opaque and Semitransparent Brushes

When you fill a shape, you must pass the address of a Brush object to one of the fill methods of the Graphics class. The one parameter of the SolidBrush constructor is a Color object. To fill an opaque shape, set the alpha component of the color to 255. To fill a semitransparent shape, set the alpha component to any value from 1 through 254.

When you fill a semitransparent shape, the color of the shape is blended with the colors of the background. The alpha component specifies how the shape and background colors are mixed; alpha values near 0 place more weight on the background colors, and alpha values near 255 place more weigh on the shape color.

The following example draws an image and then fills three ellipses that overlap the image. The first ellipse uses an alpha component of 255, so it is opaque. The second and third ellipses use an alpha component of 128, so they are semitransparent; you can see the background image through the ellipses. The call to SetCompositingQuality causes the blending for the third ellipse to be done in conjunction with gamma correction.

Image image(L"Texture1.jpg");
graphics.DrawImage(&image, 50, 50, image.GetWidth(), image.GetHeight());

SolidBrush opaqueBrush(Color(255, 0, 0, 255));
SolidBrush semiTransBrush(Color(128, 0, 0, 255));

graphics.FillEllipse(&opaqueBrush, 35, 45, 45, 30);
graphics.FillEllipse(&semiTransBrush, 86, 45, 45, 30);

graphics.SetCompositingQuality(CompositingQualityGammaCorrected);
graphics.FillEllipse(&semiTransBrush, 40, 90, 86, 30);

The following illustration shows the output of the preceding code.


Using Compositing Mode to Control Alpha Blending

There might be times when you want to create an off-screen bitmap that has the following characteristics:

  • Colors have alpha values that are less than 255.
  • Colors are not alpha blended with each other as you create the bitmap.
  • When you display the finished bitmap, colors in the bitmap are alpha blended with the background colors on the display device.

To create such a bitmap, construct a blank Bitmap object, and then construct a Graphics object based on that bitmap. Set the compositing mode of the Graphics object to CompositingModeSourceCopy.

The following example creates a Graphics object based on a Bitmap object. The code uses the Graphics object along with two semitransparent brushes (alpha = 160) to paint on the bitmap. The code fills a red ellipse and a green ellipse using the semitransparent brushes. The green ellipse overlaps the red ellipse, but the green is not blended with the red because the compositing mode of the Graphics object is set to CompositingModeSourceCopy.

Next the code prepares to draw on the screen by calling BeginPaint and creating a Graphics object based on a device context. The code draws the bitmap on the screen twice: once on a white background and once on a multicolored background. The pixels in the bitmap that are part of the two ellipses have an alpha component of 160, so the ellipses are blended with the background colors on the screen.

// Create a blank bitmap.
Bitmap bitmap(180, 100);

// Create a Graphics object that we can use to draw on the bitmap.
Graphics bitmapGraphics(&bitmap);

// Create a red brush and a green brush, each with an alpha value of 160.
SolidBrush redBrush(Color(210, 255, 0, 0));
SolidBrush greenBrush(Color(210, 0, 255, 0));

// Set the compositing mode so that when we draw overlapping ellipses,
// the colors of the ellipses are not blended.
bitmapGraphics.SetCompositingMode(CompositingModeSourceCopy);

// Fill an ellipse using a red brush that has an alpha value of 160.
bitmapGraphics.FillEllipse(&redBrush, 0, 0, 150, 70);

// Fill a second ellipse using green brush that has an alpha value of 160.
// The green ellipse overlaps the red ellipse, but the green is not
// blended with the red.
bitmapGraphics.FillEllipse(&greenBrush, 30, 30, 150, 70);

// Prepare to draw on the screen.
hdc = BeginPaint(hWnd, &ps);
Graphics* pGraphics = new Graphics(hdc);

pGraphics->SetCompositingQuality(CompositingQualityGammaCorrected);

// Draw a multicolored background.
SolidBrush brush(Color((ARGB)Color::Aqua));
pGraphics->FillRectangle(&brush, 200, 0, 60, 100);
brush.SetColor(Color((ARGB)Color::Yellow));
pGraphics->FillRectangle(&brush, 260, 0, 60, 100);
brush.SetColor(Color((ARGB)Color::Fuchsia));
pGraphics->FillRectangle(&brush, 320, 0, 60, 100);

// Display the bitmap on a white background.
pGraphics->DrawImage(&bitmap, 0, 0);

// Display the bitmap on a multicolored background.
pGraphics->DrawImage(&bitmap, 200, 0);

delete pGraphics;
EndPaint(hWnd, &ps);

The following illustration shows the output of the preceding code. Note that the ellipses are blended with the background, but they are not blended with each other.

The preceding code example has the following statement:

bitmapGraphics.SetCompositingMode(CompositingModeSourceCopy);

If you want the ellipses to be blended with each other as well as with the background, change that statement to the following:

bitmapGraphics.SetCompositingMode(CompositingModeSourceOver);

The following illustration shows the output of the revised code.


Using a Color Matrix to Set Alpha Values in Images

The Bitmap class (which inherits from the Image class) and the ImageAttributes class provide functionality for getting and setting pixel values. You can use the ImageAttributes class to modify the alpha values for an entire image, or you can call the SetPixel method of the Bitmap class to modify individual pixel values. For more information on setting individual pixel values, see Setting the Alpha Values of Individual Pixels.

The following example draws a wide black line and then displays an opaque image that covers part of that line.

Bitmap bitmap(L"Texture1.jpg");
Pen pen(Color(255, 0, 0, 0), 25);

// First draw a wide black line.
graphics.DrawLine(&pen, Point(10, 35), Point(200, 35));

// Now draw an image that covers part of the black line.
graphics.DrawImage(&bitmap,
   Rect(30, 0, bitmap.GetWidth(), bitmap.GetHeight()));

The following illustration shows the resulting image, which is drawn at (30, 0). Note that the wide black line doesn't show through the image.

The ImageAtributes class has many properties that you can use to modify images during rendering. In the following example, an ImageAttributes object is used to set all the alpha values to 80 percent of what they were. This is done by initializing a color matrix and setting the alpha scaling value in the matrix to 0.8. The address of the color matrix is passed to the SetColorMatrix method of the ImageAttributes object, and the address of the ImageAttributes object is passed to the DrawImage method of a Graphics object.

// Create a Bitmap object and load it with the texture image.
Bitmap bitmap(L"Texture1.jpg");
Pen pen(Color(255, 0, 0, 0), 25);

// Initialize the color matrix.
// Notice the value 0.8 in row 4, column 4.
ColorMatrix colorMatrix = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
                           0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
                           0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
                           0.0f, 0.0f, 0.0f, 0.8f, 0.0f,
                           0.0f, 0.0f, 0.0f, 0.0f, 1.0f};

// Create an ImageAttributes object and set its color matrix.
ImageAttributes imageAtt;
imageAtt.SetColorMatrix(&colorMatrix, ColorMatrixFlagsDefault,
   ColorAdjustTypeBitmap);

// First draw a wide black line.
graphics.DrawLine(&pen, Point(10, 35), Point(200, 35));

// Now draw the semitransparent bitmap image.
INT iWidth = bitmap.GetWidth();
INT iHeight = bitmap.GetHeight();
graphics.DrawImage(
   &bitmap,
   Rect(30, 0, iWidth, iHeight),  // Destination rectangle
   0,                             // Source rectangle X
   0,                             // Source rectangle Y
   iWidth,                        // Source rectangle width
   iHeight,                       // Source rectangle height
   UnitPixel,
   &imageAtt);

During rendering, the alpha values in the bitmap are converted to 80 percent of what they were. This results in an image that is blended with the background. As the following illustration shows, the bitmap image looks transparent; you can see the solid black line through it.

Where the image is over the white portion of the background, the image has been blended with the color white. Where the image crosses the black line, the image is blended with the color black.


Setting the Alpha Values of Individual Pixels

The topic Using a Color Matrix to Set Alpha Values in Images shows a nondestructive method for changing the alpha values of an image. The example in that topic renders an image semitransparently, but the pixel data in the bitmap is not changed. The alpha values are altered only during rendering.

The following example shows how to change the alpha values of individual pixels. The code in the example actually changes the alpha information in a Bitmap object. The approach is much slower than using a color matrix and an ImageAttributes object but gives you control over the individual pixels in the bitmap.

INT iWidth = bitmap.GetWidth();
INT iHeight = bitmap.GetHeight();
Color color, colorTemp;

for(INT iRow = 0; iRow < iHeight; iRow++)
{
   for(INT iColumn = 0; iColumn < iWidth; iColumn++)
   {
      bitmap.GetPixel(iColumn, iRow, &color);
      colorTemp.SetValue(color.MakeARGB(
         (BYTE)(255 * iColumn / iWidth),
         color.GetRed(),
         color.GetGreen(),
         color.GetBlue()));
      bitmap.SetPixel(iColumn, iRow, colorTemp);
   }
}

// First draw a wide black line.
Pen pen(Color(255, 0, 0, 0), 25);
graphics.DrawLine(&pen, 10, 35, 200, 35);

// Now draw the modified bitmap.
graphics.DrawImage(&bitmap, 30, 0, iWidth, iHeight);

The following illustration shows the resulting image.

The preceding code example uses nested loops to change the alpha value of each pixel in the bitmap. For each pixel, GetPixel gets the existing color, SetValue creates a temporary color that contains the new alpha value, and then SetPixel sets the new color. The alpha value is set based on the column of the bitmap. In the first column, alpha is set to 0. In the last column, alpha is set to 255. So the resulting image goes from fully transparent (on the left edge) to fully opaque (on the right edge).

GetPixel and SetPixel give you control of the individual pixel values. However, using GetPixel and SetPixel is not nearly as fast as using the ImageAttributes class and the ColorMatrix structure.


Using Text and Fonts

GDI+ provides several classes that form the foundation for drawing text. The Graphics class has several DrawString methods that allow you to specify various features of text, such as location, bounding rectangle, font, and format. Other classes that contribute to text rendering include FontFamily, Font, StringFormat, InstalledFontCollection, and PrivateFontCollection.

The following topics cover text and fonts in more detail:

  • Constructing Font Families and Fonts
  • Drawing Text
  • Formatting Text
  • Enumerating Installed Fonts
  • Creating a Private Font Collection
  • Obtaining Font Metrics
  • Antialiasing with Text


Constructing Font Families and Fonts

GDI+ groups fonts with the same typeface but different styles into font families. For example, the Arial font family contains the following fonts:

  • Arial Regular
  • Arial Bold
  • Arial Italic
  • Arial Bold Italic

GDI+ uses four styles to form families: regular, bold, italic, and bold italic. Adjectives such as narrow and rounded are not considered styles; rather they are part of the family name. For example, Arial Narrow is a font family whose members are the following:

  • Arial Narrow Regular
  • Arial Narrow Bold
  • Arial Narrow Italic
  • Arial Narrow Bold Italic

Before you can draw text with GDI+, you need to construct a FontFamily object and a Font object. The FontFamily objects specifies the typeface (for example, Arial), and the Font object specifies the size, style, and units.

The following example constructs a regular style Arial font with a size of 16 pixels:

FontFamily fontFamily(L"Arial");
Font font(&fontFamily, 16, FontStyleRegular, UnitPixel);

In the preceding code, the first argument passed to the Font constructor is the address of the FontFamily object. The second argument specifies the size of the font measured in units identified by the fourth argument. The third argument identifies the style.

UnitPixel is a member of the Unit enumeration, and FontStyleRegular is a member of the FontStyle enumeration. Both enumerations are declared in Gdiplusenums.h.


Drawing Text

You can use the DrawString method of the Graphics class to draw text at a specified location or within a specified rectangle.

Drawing Text at a Specified Location

To draw text at a specified location, you need Graphics, FontFamily, Font, PointF, and Brush objects.

The following example draws the string "Hello" at location (30, 10). The font family is Times New Roman. The font, which is an individual member of the font family, is Times New Roman, size 24 pixels, regular style. Assume that graphics is an existing Graphics object.

FontFamily  fontFamily(L"Times New Roman");
Font        font(&fontFamily, 24, FontStyleRegular, UnitPixel);
PointF      pointF(30.0f, 10.0f);
SolidBrush  solidBrush(Color(255, 0, 0, 255));

graphics.DrawString(L"Hello", -1, &font, pointF, &solidBrush);

The following illustration shows the output of the preceding code.

In the preceding example, the FontFamily constructor receives a string that identifies the font family. The address of the FontFamily object is passed as the first argument to the Font constructor. The second argument passed to the Font constructor specifies the size of the font measured in units given by the fourth argument. The third argument specifies the style (regular, bold, italic, and so on) of the font.

The DrawString method receives five arguments. The first argument is the string to be drawn, and the second argument is the length (in characters, not bytes) of that string. If the string is null terminated, you can pass –1 for the length. The third argument is the address of the Font object that was constructed previously. The fourth argument is a PointF object that contains the coordinates of the upper-left corner of the string. The fifth argument is the address of a SolidBrush object that will be used to fill the characters of the string.

Drawing Text in a Rectangle

One of the DrawString methods of the Graphics class has a RectF parameter. By calling that DrawString method, you can draw text that wraps in a specified rectangle. To draw text in a rectangle, you need Graphics, FontFamily, Font, RectF, and Brush objects.

The following example creates a rectangle with upper-left corner (30, 10), width 100, and height 122. Then the code draws a string inside that rectangle. The string is restricted to the rectangle and wraps in such a way that individual words are not broken.

WCHAR string[] =
   L"Draw text in a rectangle by passing a RectF to the DrawString method.";

FontFamily   fontFamily(L"Arial");
Font         font(&fontFamily, 12, FontStyleBold, UnitPoint);
RectF        rectF(30.0f, 10.0f, 100.0f, 122.0f);
SolidBrush   solidBrush(Color(255, 0, 0, 255));

graphics.DrawString(string, -1, &font, rectF, NULL, &solidBrush);

Pen pen(Color(255, 0, 0, 0));
graphics.DrawRectangle(&pen, rectF);

The following illustration shows the text drawn in the rectangle.

In the preceding example, the fourth argument passed to the DrawString method is a RectF object that specifies the bounding rectangle for the text. The fifth parameter is of type StringFormat — the argument is NULL because no special string formatting is required.


Formatting Text

To apply special formatting to text, initialize a StringFormat object and pass the address of that object to the DrawString method of the Graphics class.

To draw formatted text in a rectangle, you need Graphics, FontFamily, Font, RectF, StringFormat, and Brush objects.

Aligning Text

The following example draws text in a rectangle. Each line of text is centered (side to side), and the entire block of text is centered (top to bottom) in the rectangle.

WCHAR string[] =
   L"Use StringFormat and RectF objects to center text in a rectangle.";

FontFamily   fontFamily(L"Arial");
Font         font(&fontFamily, 12, FontStyleBold, UnitPoint);
RectF        rectF(30.0f, 10.0f, 120.0f, 140.0f);
StringFormat stringFormat;
SolidBrush   solidBrush(Color(255, 0, 0, 255));

// Center-justify each line of text.
stringFormat.SetAlignment(StringAlignmentCenter);

// Center the block of text (top to bottom) in the rectangle.
stringFormat.SetLineAlignment(StringAlignmentCenter);

graphics.DrawString(string, -1, &font, rectF, &stringFormat, &solidBrush);

Pen pen(Color(255, 0, 0, 0));
graphics.DrawRectangle(&pen, rectF);

The following illustration shows the rectangle and the centered text.

The preceding code calls two methods of the StringFormat object: SetAlignment and SetLineAlignment. The call to SetAlignment specifies that each line of text is centered in the rectangle given by the third argument passed to the DrawString method. The call to SetLineAlignment specifies that the block of text is centered (top to bottom) in the rectangle.

The value StringAlignmentCenter is an element of the StringAlignment enumeration, which is declared in Gdiplusenums.h.

Setting Tab Stops

You can set tab stops for text by calling the SetTabStops method of a StringFormat object and then passing the address of that StringFormat object to the DrawString method of the Graphics class.

The following example sets tab stops at 150, 250, and 350. Then the code displays a tabbed list of names and test scores.

WCHAR string[150] =
   L"Name\tTest 1\tTest 2\tTest 3\n";

wcscat(string, L"Joe\t95\t88\t91\n");
wcscat(string, L"Mary\t98\t84\t90\n");
wcscat(string, L"Sam\t42\t76\t98\n");
wcscat(string, L"Jane\t65\t73\t92\n");

FontFamily   fontFamily(L"Courier New");
Font         font(&fontFamily, 12, FontStyleRegular, UnitPoint);
RectF        rectF(10.0f, 10.0f, 450.0f, 100.0f);
StringFormat stringFormat;
SolidBrush   solidBrush(Color(255, 0, 0, 255));
REAL         tabs[] = {150.0f, 100.0f, 100.0f};

stringFormat.SetTabStops(0.0f, 3, tabs);

graphics.DrawString(string, -1, &font, rectF, &stringFormat, &solidBrush);

Pen pen(Color(255, 0, 0, 0));
graphics.DrawRectangle(&pen, rectF);

The following illustration shows the tabbed text.

The preceding code passes three arguments to the SetTabStops method. The third argument is the address of an array containing the tab offsets. The second argument indicates that there are four offsets in that array. The first argument passed to SetTabStops is 0, which indicates that the first offset in the array is measured from position 0, the left edge of the bounding rectangle.

Drawing Vertical Text

You can use a StringFormat object to specify that text be drawn vertically rather than horizontally.

The following example passes the value StringFormatFlagsDirectionVertical to the SetFormatFlags method of a StringFormat object. The address of that StringFormat object is passed to the DrawString method of the Graphics class. The value StringFormatFlagsDirectionVertical is an element of the StringFormatFlags enumeration, which is declared in Gdiplusenums.h.

WCHAR string[] = L"Vertical text";

FontFamily   fontFamily(L"Lucida Console");
Font         font(&fontFamily, 14, FontStyleRegular, UnitPoint);
PointF       pointF(40.0f, 10.0f);
StringFormat stringFormat;
SolidBrush   solidBrush(Color(255, 0, 0, 255));

stringFormat.SetFormatFlags(StringFormatFlagsDirectionVertical);

graphics.DrawString(string, -1, &font, pointF, &stringFormat, &solidBrush);

The following illustration shows the vertical text.


Enumerating Installed Fonts

The InstalledFontCollection class inherits from the FontCollection abstract base class. You can use an InstalledFontCollection object to enumerate the fonts installed on the computer. The GetFamilies method of an InstalledFontCollection object returns an array of FontFamily objects. Before you call GetFamilies, you must allocate a buffer large enough to hold that array. To determine the size of the required buffer, call the GetFamilyCount method and multiply the return value by sizeof(FontFamily).

The following example lists the names of all the font families installed on the computer. The code retrieves the font family names by calling the GetFamilyName method of each FontFamily object in the array returned by GetFamilies. As the family names are retrieved, they are concatenated to form a comma-separated list. Then the DrawString method of the Graphics class draws the comma-separated list in a rectangle.

FontFamily   fontFamily(L"Arial");
Font         font(&fontFamily, 8, FontStyleRegular, UnitPoint);
RectF        rectF(10.0f, 10.0f, 500.0f, 500.0f);
SolidBrush   solidBrush(Color(255, 0, 0, 0));

int          count = 0;
int          found = 0;
WCHAR        familyName[50];  // enough space for one family name
WCHAR*       familyList = NULL;
FontFamily*  pFontFamily = NULL;

InstalledFontCollection installedFontCollection;

// How many font families are installed?
count = installedFontCollection.GetFamilyCount();

// Allocate a buffer to hold the array of FontFamily
// objects returned by GetFamilies.
pFontFamily = new FontFamily[count];

// Get the array of FontFamily objects.
installedFontCollection.GetFamilies(count, pFontFamily, &found);

// The loop below creates a large string that is a comma-separated
// list of all font family names.
// Allocate a buffer large enough to hold that string.
familyList = new WCHAR[count*sizeof(familyName)];
wcscpy(familyList, L"");

for(INT j = 0; j < count; ++j)
{
   pFontFamily[j].GetFamilyName(familyName);
   wcscat(familyList, familyName);
   wcscat(familyList, L",  ");
}

// Draw the large string (list of all families) in a rectangle.
graphics.DrawString(
   familyList, -1, &font, rectF, NULL, &solidBrush);

delete [] pFontFamily;
delete [] familyList;

The following illustration shows a possible output of the preceding code. If you run the code, the output might be different, depending on the fonts installed on your computer.


Creating a Private Font Collection

The PrivateFontCollection class inherits from the FontCollection abstract base class. You can use a PrivateFontCollection object to maintain a set of fonts specifically for your application. A private font collection can include installed system fonts as well as fonts that have not been installed on the computer. To add a font file to a private font collection, call the AddFontFile method of a PrivateFontCollection object.

The GetFamilies method of a PrivateFontCollection object returns an array of FontFamily objects. Before you call GetFamilies, you must allocate a buffer large enough to hold that array. To determine the size of the required buffer, call the GetFamilyCount method and multiply the return value by sizeof(FontFamily).

The number of font families in a private font collection is not necessarily the same as the number of font files that have been added to the collection. For example, suppose you add the files ArialBd.tff, Times.tff, and TimesBd.tff to a collection. There will be three files but only two families in the collection because Times.tff and TimesBd.tff belong to the same family.

The following example adds the following three font files to a PrivateFontCollection object:

  • C:\WINNT\Fonts\Arial.tff (Arial, regular)
  • C:\WINNT\Fonts\CourBI.tff (Courier New, bold italic)
  • C:\WINNT\Fonts\TimesBd.tff (Times New Roman, bold)

The code calls the GetFamilyCount method of the PrivateFontCollection object to determine the number of families in the private collection, and then calls GetFamilies to retrieve an array of FontFamily objects.

For each FontFamily object in the collection, the code calls the IsStyleAvailable method to determine whether various styles (regular, bold, italic, bold italic, underline, and strikeout) are available. The arguments passed to the IsStyleAvailable method are members of the FontStyle enumeration, which is declared in Gdiplusenums.h.

If a given family/style combination is available, a Font object is constructed using that family and style. The first argument passed to the Font constructor is the font family name (not a FontFamily object as is the case for other variations of the Font constructor), and the final argument is the address of the PrivateFontCollection object. After the Font object is constructed, its address is passed to the DrawString method of the Graphics class to display the family name along with the name of the style.

PointF      pointF(10.0f, 0.0f);
SolidBrush  solidBrush(Color(255, 0, 0, 0));

INT                   count = 0;
INT                   found = 0;
WCHAR                 familyName[50];
WCHAR                 familyNameAndStyle[70];
FontFamily*           pFontFamily;
PrivateFontCollection privateFontCollection;

// Add three font files to the private collection.
privateFontCollection.AddFontFile(L"c:\\Winnt\\Fonts\\Arial.ttf");
privateFontCollection.AddFontFile(L"c:\\Winnt\\Fonts\\CourBI.ttf");
privateFontCollection.AddFontFile(L"c:\\Winnt\\Fonts\\TimesBd.ttf");

// How many font families are in the private collection?
count = privateFontCollection.GetFamilyCount();

// Allocate a buffer to hold the array of FontFamily
// objects returned by GetFamilies.
pFontFamily = new FontFamily[count];

// Get the array of FontFamily objects.
privateFontCollection.GetFamilies(count, pFontFamily, &found);

// Display the name of each font family in the private collection
// along with the available styles for that font family.
for(INT j = 0; j < count; ++j)
{
   // Get the font family name.
   pFontFamily[j].GetFamilyName(familyName);

   // Is the regular style available?
   if(pFontFamily[j].IsStyleAvailable(FontStyleRegular))
   {
      wcscpy(familyNameAndStyle, familyName);
      wcscat(familyNameAndStyle, L" Regular");

      Font* pFont = new Font(
         familyName, 16, FontStyleRegular, UnitPixel, &privateFontCollection);

      graphics.DrawString(familyNameAndStyle, -1, pFont, pointF, &solidBrush);

      pointF.Y += pFont->GetHeight(0.0f);
      delete(pFont);
   }

   // Is the bold style available?
   if(pFontFamily[j].IsStyleAvailable(FontStyleBold))
   {
      wcscpy(familyNameAndStyle, familyName);
      wcscat(familyNameAndStyle, L" Bold");

      Font* pFont = new Font(
         familyName, 16, FontStyleBold, UnitPixel, &privateFontCollection);

      graphics.DrawString(familyNameAndStyle, -1, pFont, pointF, &solidBrush);

      pointF.Y += pFont->GetHeight(0.0f);
      delete(pFont);
   }

   // Is the italic style available?
   if(pFontFamily[j].IsStyleAvailable(FontStyleItalic))
   {
      wcscpy(familyNameAndStyle, familyName);
      wcscat(familyNameAndStyle, L" Italic");

      Font* pFont = new Font(
         familyName, 16, FontStyleItalic, UnitPixel, &privateFontCollection);

      graphics.DrawString(familyNameAndStyle, -1, pFont, pointF, &solidBrush);

      pointF.Y += pFont->GetHeight(0.0f);
      delete(pFont);
   }

   // Is the bold italic style available?
   if(pFontFamily[j].IsStyleAvailable(FontStyleBoldItalic))
   {
      wcscpy(familyNameAndStyle, familyName);
      wcscat(familyNameAndStyle, L" BoldItalic");

      Font* pFont = new Font(familyName, 16,
         FontStyleBoldItalic, UnitPixel, &privateFontCollection);

      graphics.DrawString(familyNameAndStyle, -1, pFont, pointF, &solidBrush);

      pointF.Y += pFont->GetHeight(0.0f);
      delete(pFont);
   }

   // Is the underline style available?
   if(pFontFamily[j].IsStyleAvailable(FontStyleUnderline))
   {
      wcscpy(familyNameAndStyle, familyName);
      wcscat(familyNameAndStyle, L" Underline");

      Font* pFont = new Font(familyName, 16,
         FontStyleUnderline, UnitPixel, &privateFontCollection);

      graphics.DrawString(familyNameAndStyle, -1, pFont, pointF, &solidBrush);

      pointF.Y += pFont->GetHeight(0.0);
      delete(pFont);
   }

   // Is the strikeout style available?
   if(pFontFamily[j].IsStyleAvailable(FontStyleStrikeout))
   {
      wcscpy(familyNameAndStyle, familyName);
      wcscat(familyNameAndStyle, L" Strikeout");

      Font* pFont = new Font(familyName, 16,
         FontStyleStrikeout, UnitPixel, &privateFontCollection);

      graphics.DrawString(familyNameAndStyle, -1, pFont, pointF, &solidBrush);

      pointF.Y += pFont->GetHeight(0.0f);
      delete(pFont);
   }

   // Separate the families with white space.
   pointF.Y += 10.0f;

} // for

delete [] pFontFamily;

The following illustration shows the output of the preceding code.

Arial.tff (which was added to the private font collection in the preceding code example) is the font file for the Arial regular style. Note, however, that the program output shows several available styles other than regular for the Arial font family. That is because GDI+ can simulate the bold, italic, and bold italic styles from the regular style. GDI+ can also produce underlines and strikeouts from the regular style.

Similarly, GDI+ can simulate the bold italic style from either the bold style or the italic style. The program output shows that the bold italic style is available for the Times family even though TimesBd.tff (Times New Roman, bold) is the only Times file in the collection.


Obtaining Font Metrics

The FontFamily class provides the following methods that retrieve various metrics for a particular family/style combination:

  • GetEmHeight(FontStyle)
  • GetCellAscent(FontStyle)
  • GetCellDescent(FontStyle)
  • GetLineSpacing(FontStyle)

The numbers returned by these methods are in font design units, so they are independent of the size and units of a particular Font object.

The following illustration shows ascent, descent, and line spacing..

The following example displays the metrics for the regular style of the Arial font family. The code also creates a Font object (based on the Arial family) with size 16 pixels and displays the metrics (in pixels) for that particular Font object.

WCHAR infoString[100] = L"";  // enough space for one line of output
UINT  ascent;                 // font family ascent in design units
REAL  ascentPixel;            // ascent converted to pixels
UINT  descent;                // font family descent in design units
REAL  descentPixel;           // descent converted to pixels
UINT  lineSpacing;            // font family line spacing in design units
REAL  lineSpacingPixel;       // line spacing converted to pixels

FontFamily   fontFamily(L"Arial");
Font         font(&fontFamily, 16, FontStyleRegular, UnitPixel);
PointF       pointF(10.0f, 10.0f);
SolidBrush   solidBrush(Color(255, 0, 0, 0));

// Display the font size in pixels.
swprintf(infoString, L"font.GetSize() returns %f.", font.GetSize());
graphics.DrawString(
   infoString, wcslen(infoString), &font, pointF, &solidBrush);

// Move down one line.
pointF.Y += font.GetHeight(0.0);

// Display the font family em height in design units.
swprintf(infoString, L"fontFamily.GetEmHeight() returns %d.",
   fontFamily.GetEmHeight(FontStyleRegular));
graphics.DrawString(infoString, -1, &font, pointF, &solidBrush);

// Move down two lines.
pointF.Y += 2.0f * font.GetHeight(0.0f);

// Display the ascent in design units and pixels.
ascent = fontFamily.GetCellAscent(FontStyleRegular);

// 14.484375 = 16.0 * 1854 / 2048
ascentPixel =
   font.GetSize() * ascent / fontFamily.GetEmHeight(FontStyleRegular);
swprintf(infoString, L"The ascent is %d design units, %f pixels.",
   ascent, ascentPixel);
graphics.DrawString(infoString, -1, &font, pointF, &solidBrush);

// Move down one line.
pointF.Y += font.GetHeight(0.0f);

// Display the descent in design units and pixels.
descent = fontFamily.GetCellDescent(FontStyleRegular);

// 3.390625 = 16.0 * 434 / 2048
descentPixel =
   font.GetSize() * descent / fontFamily.GetEmHeight(FontStyleRegular);
swprintf(infoString, L"The descent is %d design units, %f pixels.",
   descent, descentPixel);
graphics.DrawString(infoString, -1, &font, pointF, &solidBrush);

// Move down one line.
pointF.Y += font.GetHeight(0.0f);

// Display the line spacing in design units and pixels.
lineSpacing = fontFamily.GetLineSpacing(FontStyleRegular);

// 18.398438 = 16.0 * 2355 / 2048
lineSpacingPixel =
   font.GetSize() * lineSpacing / fontFamily.GetEmHeight(FontStyleRegular);
swprintf(infoString, L"The line spacing is %d design units, %f pixels.",
   lineSpacing, lineSpacingPixel);
graphics.DrawString(infoString, -1, &font, pointF, &solidBrush);

The following illustration shows the output of the preceding code.

Note the first two lines of output in the preceding illustration. The Font object returns a size of 16, and the FontFamily object returns an em height of 2,048. These two numbers (16 and 2,048) are the key to converting between font design units and the units (in this case pixels) of the Font object.

For example, you can convert the ascent from design units to pixels as follows:

The preceding code positions text vertically by setting the Y data member of a PointF object. The y-coordinate is increased by font.GetHeight(0.0f) for each new line of text. The GetHeight method of a Font object returns the line spacing (in pixels) for that particular Font object. In this example, the number returned by GetHeight is 18.398438. Note that this is the same as the number obtained by converting the line spacing metric to pixels.


Antialiasing with Text

GDI+ provides various quality levels for drawing text. Typically, higher quality rendering takes more processing time than lower quality rendering.

The quality level is a property of the Graphics class. To set the quality level, call the SetTextRenderingHint method of a Graphics object. The SetTextRenderingHint method receives one of the elements of the TextRenderingHint enumeration, which is declared in Gdiplusenums.h.

GDI+ provides traditional antialiasing and a new kind of antialiasing based on Microsoft® ClearType® display technology Only available on Microsoft® Windows® XP and Microsoft Windows .NET Server, ClearType smoothing improves readability on color LCD monitors that have a digital interface, such as the monitors in laptops and high-quality flat desktop displays. Readability on CRT screens is also somewhat improved.

ClearType is dependent on the orientation and ordering of the LCD stripes. Currently, ClearType is implemented only for vertical stripes that are ordered RGB. This might be a concern if you are using a tablet PC, where the display can be oriented in any direction, or if you are using a screen that can be turned from landscape to portrait.

The following example draws text with two different quality settings:

FontFamily  fontFamily(L"Times New Roman");
Font        font(&fontFamily, 32, FontStyleRegular, UnitPixel);
SolidBrush  solidBrush(Color(255, 0, 0, 255));
WCHAR       string1[] = L"SingleBitPerPixel";
WCHAR       string2[] = L"AntiAlias";

graphics.SetTextRenderingHint(TextRenderingHintSingleBitPerPixel);
graphics.DrawString(string1, -1, &font, PointF(10.0f, 10.0f), &solidBrush);

graphics.SetTextRenderingHint(TextRenderingHintAntiAlias);
graphics.DrawString(string2, -1, &font, PointF(10.0f, 60.0f), &solidBrush);

The following illustration shows the output of the preceding code.


Constructing and Drawing Curves

GDI+ supports several types of curves: ellipses, arcs, cardinal splines, and Bézier splines. An ellipse is defined by its bounding rectangle; an arc is a portion of an ellipse defined by a starting angle and a sweep angle. A cardinal spline is defined by an array of points and a tension parameter — the curve passes smoothly through each point in the array, and the tension parameter influences the way the curve bends. A Bézier spline is defined by two end points and two control points — the curve does not pass through the control points, but the control points influence the direction and bend as the curve goes from one end point to the other.

The following topics cover cardinal splines and Bézier splines in more detail:

  • Drawing Cardinal Splines
  • Drawing Bézier Splines


Drawing Cardinal Splines

A cardinal spline is a curve that passes smoothly through a given set of points. To draw a cardinal spline, create a Graphics object and pass the address of an array of points to the DrawCurve method. The following example draws a bell-shaped cardinal spline that passes through five designated points:

Point points[] = {Point(0, 100),
                  Point(50, 80),
                  Point(100, 20),
                  Point(150, 80),
                  Point(200, 100)};

Pen pen(Color(255, 0, 0, 255));
graphics.DrawCurve(&pen, points, 5);

The following illustration shows the curve and five points.

You can use the DrawClosedCurve method of the Graphics class to draw a closed cardinal spline. In a closed cardinal spline, the curve continues through the last point in the array and connects with the first point in the array.

The following example draws a closed cardinal spline that passes through six designated points.

Point points[] = {Point(60, 60),
   Point(150, 80),
   Point(200, 40),
   Point(180, 120),
   Point(120, 100),
   Point(80, 160)};

Pen pen(Color(255, 0, 0, 255));
graphics.DrawClosedCurve(&pen, points, 6);

The following illustration shows the closed spline along with the six points:

You can change the way a cardinal spline bends by passing a tension argument to the DrawCurve method. The following example draws three cardinal splines that pass through the same set of points:

Point points[] = {Point(20, 50),
                  Point(100, 10),
                  Point(200, 100),
                  Point(300, 50),
                  Point(400, 80)};

Pen pen(Color(255, 0, 0, 255));
graphics.DrawCurve(&pen, points, 5, 0.0f);  // tension 0.0
graphics.DrawCurve(&pen, points, 5, 0.6f);  // tension 0.6
graphics.DrawCurve(&pen, points, 5, 1.0f);  // tension 1.0

The following illustration shows the three splines along with their tension values. Note that when the tension is 0, the points are connected by straight lines.


Drawing Bézier Splines

A Bézier spline is defined by four points: a start point, two control points, and an end point. The following example draws a Bézier spline with start point (10, 100) and end point (200, 100). The control points are (100, 10) and (150, 150):

Point p1(10, 100);   // start point
Point c1(100, 10);   // first control point
Point c2(150, 150);  // second control point
Point p2(200, 100);  // end point

Pen pen(Color(255, 0, 0, 255));
graphics.DrawBezier(&pen, p1, c1, c2, p2);

The following illustration shows the resulting Bézier spline along with its start point, control points, and end point. The illustration also shows the spline's convex hull, which is a polygon formed by connecting the four points with straight lines.

You can use the DrawBeziers method of the Graphics class to draw a sequence of connected Bézier splines. The following example draws a curve that consists of two connected Bézier splines. The end point of the first Bézier spline is the start point of the second Bézier spline.

Point p[] = {
   Point(10, 100),   // start point of first spline
   Point(75, 10),    // first control point of first spline
   Point(80, 50),    // second control point of first spline

   Point(100, 150),  // end point of first spline and
                     // start point of second spline

   Point(125, 80),   // first control point of second spline
   Point(175, 200),  // second control point of second spline
   Point(200, 80)};  // end point of second spline

Pen pen(Color(255, 0, 0, 255));
graphics.DrawBeziers(&pen, p, 7);

The following illustration shows the connected splines along with the seven points.


Filling Shapes with a Gradient Brush

You can use a gradient brush to fill a shape with a gradually changing color. For example, you can use a horizontal gradient to fill a shape with color that changes gradually as you move from the left edge of the shape to the right edge. Imagine a rectangle with a left edge that is black (represented by red, green, and blue components 0, 0, 0) and a right edge that is red (represented by 255, 0, 0). If the rectangle is 256 pixels wide, the red component of a given pixel will be one greater than the red component of the pixel to its left. The leftmost pixel in a row has color components (0, 0, 0), the second pixel has (1, 0, 0), the third pixel has (2, 0, 0), and so on, until you get to the rightmost pixel, which has color components (255, 0, 0). These interpolated color values make up the color gradient.

A linear gradient changes color as you move horizontally, vertically, or parallel to a specified slanted line. A path gradient changes color as you move about the interior and boundary of a path. You can customize path gradients to achieve a wide variety of effects.

GDI+ provides the LinearGradientBrush and PathGradientBrush classes, both of which inherit from the Brush class.

The following topics cover linear and path gradients in more detail:

  • Creating a Linear Gradient
  • Creating a Path Gradient
  • Applying Gamma Correction to a Gradient


Creating a Linear Gradient

GDI+ provides horizontal, vertical, and diagonal linear gradients. By default, the color in a linear gradient changes uniformly. However, you can customize a linear gradient so that the color changes in a non-uniform fashion.

Horizontal Linear Gradients

The following example uses a horizontal linear gradient brush to fill a line, an ellipse, and a rectangle:

LinearGradientBrush linGrBrush(
   Point(0, 10),
   Point(200, 10),
   Color(255, 255, 0, 0),   // opaque red
   Color(255, 0, 0, 255));  // opaque blue

Pen pen(&linGrBrush);

graphics.DrawLine(&pen, 0, 10, 200, 10);
graphics.FillEllipse(&linGrBrush, 0, 30, 200, 100);
graphics.FillRectangle(&linGrBrush, 0, 155, 500, 30);

The LinearGradientBrush constructor receives four arguments: two points and two colors. The first point (0, 10) is associated with the first color (red), and the second point (200, 10) is associated with the second color (blue). As you would expect, the line drawn from (0, 10) to (200, 10) changes gradually from red to blue.

The 10s in the points (50, 10) and (200, 10) are not important. What's important is that the two points have the same second coordinate — the line connecting them is horizontal. The ellipse and the rectangle also change gradually from red to blue as the horizontal coordinate goes from 0 to 200.

The following illustration shows the line, the ellipse, and the rectangle. Note that the color gradient repeats itself as the horizontal coordinate increases beyond 200.

Customizing Linear Gradients

In the preceding example, the color components change linearly as you move from a horizontal coordinate of 0 to a horizontal coordinate of 200. For example, a point whose first coordinate is halfway between 0 and 200 will have a blue component that is halfway between 0 and 255.

GDI+ allows you to adjust the way a color varies from one edge of a gradient to the other. Suppose you want to create a gradient brush that changes from black to red according to the following table.

Horizontal coordinate | RGB components
0 | (0, 0, 0)
40 | (128, 0, 0)
200 | (255, 0, 0)

Note that the red component is at half intensity when the horizontal coordinate is only 20 percent of the way from 0 to 200.

The following example calls the SetBlend method of a LinearGradientBrush object to associate three relative intensities with three relative positions. As in the preceding table, a relative intensity of 0.5 is associated with a relative position of 0.2. The code fills an ellipse and a rectangle with the gradient brush.

LinearGradientBrush linGrBrush(
   Point(0, 10),
   Point(200, 10),
   Color(255, 0, 0, 0),     // opaque black
   Color(255, 255, 0, 0));  // opaque red

REAL relativeIntensities[] = {0.0f, 0.5f, 1.0f};
REAL relativePositions[]   = {0.0f, 0.2f, 1.0f};

linGrBrush.SetBlend(relativeIntensities, relativePositions, 3);

graphics.FillEllipse(&linGrBrush, 0, 30, 200, 100);
graphics.FillRectangle(&linGrBrush, 0, 155, 500, 30);

The following illustration shows the resulting ellipse and rectangle.

Diagonal Linear Gradients

The gradients in the preceding examples have been horizontal; that is, the color changes gradually as you move along any horizontal line. You can also define vertical gradients and diagonal gradients. The following code passes the points (0, 0) and (200, 100) to a LinearGradientBrush constructor. The color blue is associated with (0, 0), and the color green is associated with (200, 100). A line (with pen width 10) and an ellipse are filled with the linear gradient brush.

LinearGradientBrush linGrBrush(
   Point(0, 0),
   Point(200, 100),
   Color(255, 0, 0, 255),   // opaque blue
   Color(255, 0, 255, 0));  // opaque green

Pen pen(&linGrBrush, 10);

graphics.DrawLine(&pen, 0, 0, 600, 300);
graphics.FillEllipse(&linGrBrush, 10, 100, 200, 100);

The following illustration shows the line and the ellipse. Note that the color in the ellipse changes gradually as you move along any line that is parallel to the line passing through (0, 0) and (200, 100).


Creating a Path Gradient

The PathGradientBrush class allows you to customize the way you fill a shape with gradually changing colors. A PathGradientBrush object has a boundary path and a center point. You can specify one color for the center point and another color for the boundary. You can also specify separate colors for each of several points along the boundary.

Note In GDI+, a path is a sequence of lines and curves maintained by a GraphicsPath object. For more information about GDI+ paths, see Paths and Constructing and Drawing Paths.

The following example fills an ellipse with a path gradient brush. The center color is set to blue and the boundary color is set to aqua.

// Create a path that consists of a single ellipse.
GraphicsPath path;
path.AddEllipse(0, 0, 140, 70);

// Use the path to construct a brush.
PathGradientBrush pthGrBrush(&path);

// Set the color at the center of the path to blue.
pthGrBrush.SetCenterColor(Color(255, 0, 0, 255));

// Set the color along the entire boundary of the path to aqua.
Color colors[] = {Color(255, 0, 255, 255)};
int count = 1;
pthGrBrush.SetSurroundColors(colors, &count);

graphics.FillEllipse(&pthGrBrush, 0, 0, 140, 70);

The following illustration shows the filled ellipse.

By default, a path gradient brush does not extend outside the boundary of the path. If you use the path gradient brush to fill a shape that extends beyond the boundary of the path, the area of the screen outside the path will not be filled. The following illustration shows what happens if you change the FillEllipse call in the preceding code to graphics.FillRectangle(&pthGrBrush, 0, 10, 200, 40).

Specifying Points on the Boundary

The following example constructs a path gradient brush from a star-shaped path. The code calls the SetCenterColor method to set the color at the centroid of the star to red. Then the code calls the SetSurroundColors method to specify various colors (stored in the colors array) at the individual points in the points array. The final code statement fills the star-shaped path with the path gradient brush.

// Put the points of a polygon in an array.
Point points[] = {Point(75, 0),    Point(100, 50),
                  Point(150, 50),  Point(112, 75),
                  Point(150, 150), Point(75, 100),
                  Point(0, 150),   Point(37, 75),
                  Point(0, 50),    Point(50, 50)};

// Use the array of points to construct a path.
GraphicsPath path;
path.AddLines(points, 10);

// Use the path to construct a path gradient brush.
PathGradientBrush pthGrBrush(&path);

// Set the color at the center of the path to red.
pthGrBrush.SetCenterColor(Color(255, 255, 0, 0));

// Set the colors of the points in the array.
Color colors[] = {Color(255, 0, 0, 0),   Color(255, 0, 255, 0),
                  Color(255, 0, 0, 255), Color(255, 255, 255, 255),
                  Color(255, 0, 0, 0),   Color(255, 0, 255, 0),
                  Color(255, 0, 0, 255), Color(255, 255, 255, 255),
                  Color(255, 0, 0, 0),   Color(255, 0, 255, 0)};

int count = 10;
pthGrBrush.SetSurroundColors(colors, &count);

// Fill the path with the path gradient brush.
graphics.FillPath(&pthGrBrush, &path);

The following illustration shows the filled star.

The following example constructs a path gradient brush based on an array of points. A color is assigned to each of the five points in the array. If you were to connect the five points by straight lines, you would get a five-sided polygon. A color is also assigned to the center (centroid) of that polygon — in this example, the center (80, 75) is set to white. The final code statement in the example fills a rectangle with the path gradient brush.

The color used to fill the rectangle is white at (80, 75) and changes gradually as you move away from (80, 75) toward the points in the array. For example, as you move from (80, 75) to (0, 0), the color changes gradually from white to red, and as you move from (80, 75) to (160, 0), the color changes gradually from white to green.

// Construct a path gradient brush based on an array of points.
PointF ptsF[] = {PointF(0.0f, 0.0f),
                 PointF(160.0f, 0.0f),
                 PointF(160.0f, 200.0f),
                 PointF(80.0f, 150.0f),
                 PointF(0.0f, 200.0f)};

PathGradientBrush pBrush(ptsF, 5);

// An array of five points was used to construct the path gradient
// brush. Set the color of each point in that array.
Color colors[] = {Color(255, 255, 0, 0),  // (0, 0) red
                  Color(255, 0, 255, 0),  // (160, 0) green
                  Color(255, 0, 255, 0),  // (160, 200) green
                  Color(255, 0, 0, 255),  // (80, 150) blue
                  Color(255, 255, 0, 0)}; // (0, 200) red

int count = 5;
pBrush.SetSurroundColors(colors, &count);

// Set the center color to white.
pBrush.SetCenterColor(Color(255, 255, 255, 255));

// Use the path gradient brush to fill a rectangle.
graphics.FillRectangle(&pBrush, Rect(0, 0, 180, 220));

Note that there is no GraphicsPath object in the preceding code. The particular PathGradientBrush constructor in the example receives a pointer to an array of points but does not require a GraphicsPath object. Also, note that the PathGradient brush is used to fill a rectangle, not a path. The rectangle is larger than the path used to define the brush, so some of the rectangle is not painted by the brush. The following illustration shows the rectangle (dotted line) and the portion of the rectangle painted by the path gradient brush.

Customizing a Path Gradient

One way to customize a path gradient brush is to set its focus scales. The focus scales specify an inner path that lies inside the main path. The center color is displayed everywhere inside that inner path rather than only at the center point. To set the focus scales of a path gradient brush, call the SetFocusScales method.

The following example creates a path gradient brush based on an elliptical path. The code sets the boundary color to blue, sets the center color to aqua, and then uses the path gradient brush to fill the elliptical path.

Next the code sets the focus scales of the path gradient brush. The x focus scale is set to 0.3, and the y focus scale is set to 0.8. The code calls the TranslateTransform method of a Graphics object so that the subsequent call to FillPath fills an ellipse that sits to the right of the first ellipse.

To see the effect of the focus scales, imagine a small ellipse that shares its center with the main ellipse. The small (inner) ellipse is the main ellipse scaled (about its center) horizontally by a factor of 0.3 and vertically by a factor of 0.8. As you move from the boundary of the outer ellipse to the boundary of the inner ellipse, the color changes gradually from blue to aqua. As you move from the boundary of the inner ellipse to the shared center, the color remains aqua.

// Create a path that consists of a single ellipse.
GraphicsPath path;
path.AddEllipse(0, 0, 200, 100);

// Create a path gradient brush based on the elliptical path.
PathGradientBrush pthGrBrush(&path);
pthGrBrush.SetGammaCorrection(TRUE);

// Set the color along the entire boundary to blue.
Color color(Color(255, 0, 0, 255));
INT num = 1;
pthGrBrush.SetSurroundColors(&color, &num);

// Set the center color to aqua.
pthGrBrush.SetCenterColor(Color(255, 0, 255, 255));

// Use the path gradient brush to fill the ellipse.
graphics.FillPath(&pthGrBrush, &path);

// Set the focus scales for the path gradient brush.
pthGrBrush.SetFocusScales(0.3f, 0.8f);

// Use the path gradient brush to fill the ellipse again.
// Show this filled ellipse to the right of the first filled ellipse.
graphics.TranslateTransform(220.0f, 0.0f);
graphics.FillPath(&pthGrBrush, &path);

The following illustration shows the output of the preceding code. The ellipse on the left is aqua only at the center point. The ellipse on the right is aqua everywhere inside the inner path.

Another way to customize a path gradient brush is to specify an array of preset colors and an array of interpolation positions.

The following example creates a path gradient brush based on a triangle. The code calls the SetInterpolationColors method of the path gradient brush to specify an array of interpolation colors (dark green, aqua, blue) and an array of interpolation positions (0, 0.25, 1). As you move from the boundary of the triangle to the center point, the color changes gradually from dark green to aqua and then from aqua to blue. The change from dark green to aqua happens in 25 percent of the distance from dark green to blue.

// Vertices of the triangle
Point points[] = {Point(100, 0),
                  Point(200, 200),
                  Point(0, 200)};

// No GraphicsPath object is created. The PathGradient
// brush is constructed directly from the array of points.
PathGradientBrush pthGrBrush(points, 3);

Color presetColors[] = {
   Color(255, 0, 128, 0),    // Dark green
   Color(255, 0, 255, 255),  // Aqua
   Color(255, 0, 0, 255)};   // Blue

REAL interpPositions[] = {
   0.0f,   // Dark green is at the boundary of the triangle.
   0.25f,  // Aqua is 25 percent of the way from the boundary
           // to the center point.
   1.0f};  // Blue is at the center point.

pthGrBrush.SetInterpolationColors(presetColors, interpPositions, 3);

// Fill a rectangle that is larger than the triangle
// specified in the Point array. The portion of the
// rectangle outside the triangle will not be painted.
graphics.FillRectangle(&pthGrBrush, 0, 0, 200, 200);

The following illustration shows the output of the preceding code.

Setting the Center Point

By default, the center point of a path gradient brush is at the centroid of the path used to construct the brush. You can change the location of the center point by calling the SetCenterPoint method of the PathGradientBrush class.

The following example creates a path gradient brush based on an ellipse. The center of the ellipse is at (70, 35), but the center point of the path gradient brush is set to (120, 40).

// Create a path that consists of a single ellipse.
GraphicsPath path;
path.AddEllipse(0, 0, 140, 70);

// Use the path to construct a brush.
PathGradientBrush pthGrBrush(&path);

// Set the center point to a location that is not the centroid of the path.
pthGrBrush.SetCenterPoint(Point(120, 40));

// Set the color at the center point to blue.
pthGrBrush.SetCenterColor(Color(255, 0, 0, 255));

// Set the color along the entire boundary of the path to aqua.
Color colors[] = {Color(255, 0, 255, 255)};
int count = 1;
pthGrBrush.SetSurroundColors(colors, &count);

graphics.FillEllipse(&pthGrBrush, 0, 0, 140, 70);

The following illustration shows the filled ellipse and the center point of the path gradient brush.

You can set the center point of a path gradient brush to a location outside the path that was used to construct the brush. In the preceding code, if you replace the call to SetCenterPoint with pthGrBrush.SetCenterPoint(Point(145, 35)), you will get the following result.

In the preceding illustration, the points at the far right of the ellipse are not pure blue (although they are very close). The colors in the gradient are positioned as if the fill had been allowed to reach the point (145, 35), the color would have reached pure blue (0, 0, 255). But the fill never reaches (145, 35) because a path gradient brush paints only inside its path.


Applying Gamma Correction to a Gradient

You can enable gamma correction for a gradient brush by passing TRUE to the SetGammaCorrection method of that brush. You can disable gamma correction by passing FALSE to the SetGammaCorrection method. Gamma correction is disabled by default.

The following example creates a linear gradient brush and uses that brush to fill two rectangles. The first rectangle is filled without gamma correction and the second rectangle is filled with gamma correction.

LinearGradientBrush linGrBrush(
   Point(0, 10),
   Point(200, 10),
   Color(255, 255, 0, 0),   // Opaque red
   Color(255, 0, 0, 255));  // Opaque blue

graphics.FillRectangle(&linGrBrush, 0, 0, 200, 50);
linGrBrush.SetGammaCorrection(TRUE);
graphics.FillRectangle(&linGrBrush, 0, 60, 200, 50);

The following illustration shows the two filled rectangles. The top rectangle, which does not have gamma correction, appears dark in the middle. The bottom rectangle, which has gamma correction, appears to have more uniform intensity.

The following example creates a path gradient brush based on a star-shaped path. The code uses the path gradient brush with gamma correction disabled (the default) to fill the path. Then the code passes TRUE to the SetGammaCorrection method to enable gamma correction for the path gradient brush. The call to Graphics::TranslateTransform sets the world transformation of a Graphics object so that the subsequent call to FillPath fills a star that sits to the right of the first star.

// Put the points of a polygon in an array.
Point points[] = {Point(75, 0), Point(100, 50),
                  Point(150, 50), Point(112, 75),
                  Point(150, 150), Point(75, 100),
                  Point(0, 150), Point(37, 75),
                  Point(0, 50), Point(50, 50)};

// Use the array of points to construct a path.
GraphicsPath path;
path.AddLines(points, 10);

// Use the path to construct a path gradient brush.
PathGradientBrush pthGrBrush(&path);

// Set the color at the center of the path to red.
pthGrBrush.SetCenterColor(Color(255, 255, 0, 0));

// Set the colors of the points in the array.
Color colors[] = {Color(255, 0, 0, 0),   Color(255, 0, 255, 0),
                  Color(255, 0, 0, 255), Color(255, 255, 255, 255),
                  Color(255, 0, 0, 0),   Color(255, 0, 255, 0),
                  Color(255, 0, 0, 255), Color(255, 255, 255, 255),
                  Color(255, 0, 0, 0),   Color(255, 0, 255, 0)};

int count = 10;
pthGrBrush.SetSurroundColors(colors, &count);

// Fill the path with the path gradient brush.
graphics.FillPath(&pthGrBrush, &path);
pthGrBrush.SetGammaCorrection(TRUE);
graphics.TranslateTransform(200.0f, 0.0f);
graphics.FillPath(&pthGrBrush, &path);

The following illustration shows the output of the preceding code. The star on the right has gamma correction. Note that the star on the left, which does not have gamma correction, has areas that appear dark.


Constructing and Drawing Paths

A path is a sequence of graphics primitives (lines, rectangles, curves, text, and the like) that can be manipulated and drawn as a single unit. A path can be divided into figures that are either open or closed. A figure can contain several primitives.

You can draw a path by calling the DrawPath method of the Graphics class, and you can fill a path by calling the FillPath method of the Graphics class.

The following topics cover paths in more detail:

  • Creating Figures from Lines, Curves, and Shapes
  • Filling Open Figures


Creating Figures from Lines, Curves, and Shapes

To create a path, construct a GraphicsPath object, and then call methods, such as AddLine and AddCurve, to add primitives to the path.

The following example creates a path that has a single arc. The arc has a sweep angle of –180 degrees, which is counterclockwise in the default coordinate system.

Pen pen(Color(255, 255, 0, 0));
GraphicsPath path;
path.AddArc(175, 50, 50, 50, 0, -180);
graphics.DrawPath(&pen, &path);

The following example creates a path that has two figures. The first figure is an arc followed by a line. The second figure is a line followed by a curve, followed by a line. The first figure is left open, and the second figure is closed.

Point points[] = {Point(40, 60), Point(50, 70), Point(30, 90)};

Pen pen(Color(255, 255, 0, 0), 2);
GraphicsPath path;

// The first figure is started automatically, so there is
// no need to call StartFigure here.
path.AddArc(175, 50, 50, 50, 0.0f, -180.0f);
path.AddLine(100, 0, 250, 20);

path.StartFigure();
path.AddLine(50, 20, 5, 90);
path.AddCurve(points, 3);
path.AddLine(50, 150, 150, 180);
path.CloseFigure();

graphics.DrawPath(&pen, &path);

In addition to adding lines and curves to paths, you can add closed shapes: rectangles, ellipses, pies, and polygons. The following example creates a path that has two lines, a rectangle, and an ellipse. The code uses a pen to draw the path and a brush to fill the path.

GraphicsPath path;
Pen          pen(Color(255, 255, 0, 0), 2);
SolidBrush   brush(Color(255, 0, 0, 200));

path.AddLine(10, 10, 100, 40);
path.AddLine(100, 60, 30, 60);
path.AddRectangle(Rect(50, 35, 20, 40));
path.AddEllipse(10, 75, 40, 30);

graphics.DrawPath(&pen, &path);
graphics.FillPath(&brush, &path);

The path in the preceding example has three figures. The first figure consists of the two lines, the second figure consists of the rectangle, and the third figure consists of the ellipse. Even when there are no calls to CloseFigure or StartFigure, intrinsically closed shapes, such as rectangles and ellipses, are considered separate figures.


Filling Open Figures

You can fill a path by passing the address of a GraphicsPath object to the Graphics::FillPath method. The FillPath method fills the path according to the fill mode (alternate or winding) currently set for the path. If the path has any open figures, the path is filled as if those figures were closed. GDI+ closes a figure by drawing a straight line from its ending point to its starting point.

The following example creates a path that has one open figure (an arc) and one closed figure (an ellipse). The Graphics::FillPath method fills the path according to the default fill mode, which is FillModeAlternate.

GraphicsPath path;

// Add an open figure.
path.AddArc(0, 0, 150, 120, 30, 120);

// Add an intrinsically closed figure.
path.AddEllipse(50, 50, 50, 100);

Pen pen(Color(128, 0, 0, 255), 5);
SolidBrush brush(Color(255, 255, 0, 0));

// The fill mode is FillModeAlternate by default.
graphics.FillPath(&brush, &path);
graphics.DrawPath(&pen, &path);

The following illustration shows the output of the preceding code. Note that path is filled (according to FillModeAlternate) as if the open figure were closed by a straight line from its ending point to its starting point.


Using Graphics Containers

A Graphics object provides methods such as DrawLine, DrawImage, and DrawString for displaying vector images, raster images, and text. A Graphics object also has several properties that influence the quality and orientation of the items that are drawn. For example, the smoothing mode property determines whether antialiasing is applied to lines and curves, and the world transformation property influences the position and rotation of the items that are drawn.

A Graphics object is often associated with a particular display device. When you use a Graphics object to draw in a window, the Graphics object is also associated with that particular window.

A Graphics object can be thought of as a container because it holds a set of properties that influence drawing, and it is linked to device-specific information. You can create a secondary container within an existing Graphics object by calling the BeginContainer method of that Graphics object.

The following topics cover Graphics objects and nested containers in more detail:

  • The State of a Graphics Object
  • Nested Graphics Containers


The State of a Graphics Object

The Graphics class is at the heart of GDI+. To draw anything, you create a Graphics object, set its properties, and call its methods (DrawLine, DrawImage, DrawString, and the like).

The following example constructs a Graphics object and a Pen object and then calls the DrawRectangle method of the Graphics object:

HDC          hdc;
PAINTSTRUCT  ps;

hdc = BeginPaint(hWnd, &ps);
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));  // opaque blue
   graphics.DrawRectangle(&pen, 10, 10, 200, 100);
}
EndPaint(hWnd, &ps);

In the preceding code, the BeginPaint method returns a handle to a device context, and that handle is passed to the Graphics constructor. A device context is a structure (maintained by Windows) that holds information about the particular display device being used.

Graphics State

A Graphics object does more than provide drawing methods, such as DrawLine and DrawRectangle. A Graphics object also maintains graphics state, which can be divided into the following categories:

  • A link to a device context
  • Quality settings
  • Transformations
  • A clipping region

Device Context

As an application programmer, you don't have to think about the interaction between a Graphics object and its device context. This interaction is handled by GDI+ behind the scenes.

Quality Settings

A Graphics object has several properties that influence the quality of the items that are drawn on the screen. You can view and manipulate these properties by calling get and set methods. For example, you can call the SetTextRenderingHint method to specify the type of antialiasing (if any) applied to text. Other set methods that influence quality are SetSmoothingMode, SetCompositingMode, SetCompositingQuality, and SetInterpolationMode.

The following example draws two ellipses, one with the smoothing mode set to SmoothingModeAntiAlias and one with the smoothing mode set to SmoothingModeHighSpeed:

Graphics graphics(hdc);
Pen pen(Color(255, 0, 255, 0));  // opaque green

graphics.SetSmoothingMode(SmoothingModeAntiAlias);
graphics.DrawEllipse(&pen, 0, 0, 200, 100);
graphics.SetSmoothingMode(SmoothingModeHighSpeed);
graphics.DrawEllipse(&pen, 0, 150, 200, 100);

Transformations

A Graphics object maintains two transformations (world and page) that are applied to all items drawn by that Graphics object. Any affine transformation can be stored in the world transformation. Affine transformations include scaling, rotating, reflecting, skewing, and translating. The page transformation can be used for scaling and for changing units (for example, pixels to inches). For more information on transformations, see Coordinate Systems and Transformations.

The following example sets the world and page transformations of a Graphics object. The world transformation is set to a 30-degree rotation. The page transformation is set so that the coordinates passed to the second DrawEllipse will be treated as millimeters instead of pixels. The code makes two identical calls to the DrawEllipse method. The world transformation is applied to the first DrawEllipse call, and both transformations (world and page) are applied to the second DrawEllipse call.

Graphics graphics(hdc);
Pen pen(Color(255, 255, 0, 0));

graphics.ResetTransform();
graphics.RotateTransform(30.0f);            // World transformation
graphics.DrawEllipse(&pen, 30, 0, 50, 25);
graphics.SetPageUnit(UnitMillimeter);       // Page transformation
graphics.DrawEllipse(&pen, 30, 0, 50, 25);

The following illustration shows the two ellipses. Note that the 30-degree rotation is about the origin of the coordinate system (upper-left corner of the client area), not about the centers of the ellipses. Also note that the pen width of 1 means 1 pixel for the first ellipse and 1 millimeter for the second ellipse.

Clipping Region

A Graphics object maintains a clipping region that applies to all items drawn by that Graphics object. You can set the clipping region by calling the SetClip method.

The following example creates a plus-shaped region by forming the union of two rectangles. That region is designated as the clipping region of a Graphics object. Then the code draws two lines that are restricted to the interior of the clipping region.

Graphics graphics(hdc);
Pen pen(Color(255, 255, 0, 0), 5);  // opaque red, width 5
SolidBrush brush(Color(255, 180, 255, 255));  // opaque aqua

// Create a plus-shaped region by forming the union of two rectangles.
Region region(Rect(50, 0, 50, 150));
region.Union(Rect(0, 50, 150, 50));
graphics.FillRegion(&brush, &region);

// Set the clipping region.
graphics.SetClip(&region);

// Draw two clipped lines.
graphics.DrawLine(&pen, 0, 30, 150, 160);
graphics.DrawLine(&pen, 40, 20, 190, 150);

The following illustration shows the clipped lines.


Nested Graphics Containers

GDI+ provides containers that you can use to temporarily replace or augment part of the state in a Graphics object. You create a container by calling the BeginContainer method of a Graphics object. You can call BeginContainer repeatedly to form nested containers.

Transformations in Nested Containers

The following example creates a Graphics object and a container within that Graphics object. The world transformation of the Graphics object is a translation 100 units in the x direction and 80 units in the y direction. The world transformation of the container is a 30-degree rotation. The code makes the call DrawRectangle(&pen, -60, -30, 120, 60) twice. The first call to DrawRectangle is inside the container; that is, the call is in between the calls to BeginContainer and EndContainer. The second call to DrawRectangle is after the call to EndContainer.

Graphics           graphics(hdc);
Pen                pen(Color(255, 255, 0, 0));
GraphicsContainer  graphicsContainer;

graphics.TranslateTransform(100.0f, 80.0f);

graphicsContainer = graphics.BeginContainer();
   graphics.RotateTransform(30.0f);
   graphics.DrawRectangle(&pen, -60, -30, 120, 60);
graphics.EndContainer(graphicsContainer);

graphics.DrawRectangle(&pen, -60, -30, 120, 60);

In the preceding code, the rectangle drawn from inside the container is transformed first by the world transformation of the container (rotation) and then by the world transformation of the Graphics object (translation). The rectangle drawn from outside the container is transformed only by the world transformation of the Graphics object (translation). The following illustration shows the two rectangles.

Clipping in Nested Containers

The following example illustrates how nested containers handle clipping regions. The code creates a Graphics object and a container within that Graphics object. The clipping region of the Graphics object is a rectangle, and the clipping region of the container is an ellipse. The code makes two calls to the DrawLine method. The first call to DrawLine is inside the container, and the second call to DrawLine is outside the container (after the call to EndContainer). The first line is clipped by the intersection of the two clipping regions. The second line is clipped only by the rectangular clipping region of the Graphics object.

Graphics           graphics(hdc);
GraphicsContainer  graphicsContainer;
Pen                redPen(Color(255, 255, 0, 0), 2);
Pen                bluePen(Color(255, 0, 0, 255), 2);
SolidBrush         aquaBrush(Color(255, 180, 255, 255));
SolidBrush         greenBrush(Color(255, 150, 250, 130));

graphics.SetClip(Rect(50, 65, 150, 120));
graphics.FillRectangle(&aquaBrush, 50, 65, 150, 120);

graphicsContainer = graphics.BeginContainer();
   // Create a path that consists of a single ellipse.
   GraphicsPath path;
   path.AddEllipse(75, 50, 100, 150);

  // Construct a region based on the path.
   Region region(&path);
   graphics.FillRegion(&greenBrush, &region);

   graphics.SetClip(&region);
   graphics.DrawLine(&redPen, 50, 0, 350, 300);
graphics.EndContainer(graphicsContainer);

graphics.DrawLine(&bluePen, 70, 0, 370, 300);

The following illustration shows the two clipped lines.

As the two preceding examples show, transformations and clipping regions are cumulative in nested containers. If you set the world transformations of the container and the Graphics object, both transformations will apply to items drawn from inside the container. The transformation of the container will be applied first, and the transformation of the Graphics object will be applied second. If you set the clipping regions of the container and the Graphics object, items drawn from inside the container will be clipped by the intersection of the two clipping regions.

Quality Settings in Nested Containers

Quality settings (SmoothingMode, TextRenderingHint, and the like) in nested containers are not cumulative; rather, the quality settings of the container temporarily replace the quality settings of a Graphics object. When you create a new container, the quality settings for that container are set to default values. For example, suppose you have a Graphics object with a smoothing mode of SmoothingModeAntiAlias. When you create a container, the smoothing mode inside the container is the default smoothing mode. You are free to set the smoothing mode of the container, and any items drawn from inside the container will be drawn according to the mode you set. Items drawn after the call to EndContainer will be drawn according to the smoothing mode (SmoothingModeAntiAlias) that was in place before the call to BeginContainer.

Several Layers of Nested Containers

You are not limited to one container in a Graphics object. You can create a sequence of containers, each nested in the preceding, and you can specify the world transformation, clipping region, and quality settings of each of those nested containers. If you call a drawing method from inside the innermost container, the transformations will be applied in order, starting with the innermost container and ending with the outermost container. Items drawn from inside the innermost container will be clipped by the intersection of all the clipping regions.

The following example creates a Graphics object and sets its text rendering hint to TextRenderingHintAntiAlias. The code creates two containers, one nested within the other. The text rendering hint of the outer container is set to TextRenderingHintSingleBitPerPixel, and the text rendering hint of the inner container is set to TextRenderingHintAntiAlias. The code draws three strings: one from the inner container, one from the outer container, and one from the Graphics object itself.

Graphics graphics(hdc);
GraphicsContainer innerContainer;
GraphicsContainer outerContainer;
SolidBrush brush(Color(255, 0, 0, 255));
FontFamily fontFamily(L"Times New Roman");
Font font(&fontFamily, 36, FontStyleRegular, UnitPixel);

graphics.SetTextRenderingHint(TextRenderingHintAntiAlias);

outerContainer = graphics.BeginContainer();

   graphics.SetTextRenderingHint(TextRenderingHintSingleBitPerPixel);

   innerContainer = graphics.BeginContainer();
      graphics.SetTextRenderingHint(TextRenderingHintAntiAlias);
      graphics.DrawString(L"Inner Container", 15, &font,
         PointF(20, 10), &brush);
   graphics.EndContainer(innerContainer);

   graphics.DrawString(L"Outer Container", 15, &font, PointF(20, 50), &brush);

graphics.EndContainer(outerContainer);

graphics.DrawString(L"Graphics Object", 15, &font, PointF(20, 90), &brush);

The following illustration shows the three strings. The strings drawn from the inner container and the Graphics object are smoothed by antialiasing. The string drawn from the outer container is not smoothed by antialiasing because of the TextRenderingHintSingleBitPerPixel setting.


Transformations

Affine transformations include rotating, scaling, reflecting, shearing, and translating. In GDI+, the Matrix class provides the foundation for performing affine transformations on vector drawings, images, and text.

The following topics cover transformations in more detail:

  • Using the World Transformation
  • Why Transformation Order Is Significant


Using the World Transformation

The world transformation is a property of the Graphics class. The numbers that specify the world transformation are stored in a Matrix object, which represents a 3×3 matrix. The Matrix and Graphics classes have several methods for setting the numbers in the world transformation matrix. The examples in this section manipulate rectangles because rectangles are easy to draw and it is easy to see the effects of transformations on rectangles.

We start by creating a 50 by 50 rectangle and locating it at the origin (0, 0). The origin is at the upper-left corner of the client area.

Rect rect(0, 0, 50, 50);
Pen pen(Color(255, 255, 0, 0), 0);
graphics.DrawRectangle(&pen, rect);

The following code applies a scaling transformation that expands the rectangle by a factor of 1.75 in the x direction and shrinks the rectangle by a factor of 0.5 in the y direction:

Rect rect(0, 0, 50, 50);
Pen pen(Color(255, 255, 0, 0), 0);
graphics.ScaleTransform(1.75f, 0.5f);
graphics.DrawRectangle(&pen, rect);

The result is a rectangle that is longer in the x direction and shorter in the y direction than the original.

To rotate the rectangle instead of scaling it, use the following code instead of the preceding code:

Rect rect(0, 0, 50, 50);
Pen pen(Color(255, 255, 0, 0), 0);
graphics.RotateTransform(28.0f);
graphics.DrawRectangle(&pen, rect);

To translate the rectangle, use the following code:

Rect rect(0, 0, 50, 50);
Pen pen(Color(255, 255, 0, 0), 0);
graphics.TranslateTransform(150.0f, 150.0f);
graphics.DrawRectangle(&pen, rect);


Why Transformation Order Is Significant

A single Matrix object can store a single transformation or a sequence of transformations. The latter is called a composite transformation. The matrix of a composite transformation is obtained by multiplying the matrices of the individual transformations.

In a composite transformation, the order of the individual transformations is important. For example, if you first rotate, then scale, then translate, you get a different result than if you first translate, then rotate, then scale. In GDI+, composite transformations are built from left to right. If S, R, and T are scale, rotation, and translation matrices respectively, then the product SRT (in that order) is the matrix of the composite transformation that first scales, then rotates, then translates. The matrix produced by the product SRT is different from the matrix produced by the product TRS.

One reason order is significant is that transformations like rotation and scaling are done with respect to the origin of the coordinate system. Scaling an object that is centered at the origin produces a different result than scaling an object that has been moved away from the origin. Similarly, rotating an object that is centered at the origin produces a different result than rotating an object that has been moved away from the origin.

The following example combines scaling, rotation and translation (in that order) to form a composite transformation. The argument MatrixOrderAppend passed to the RotateTransform method specifies that the rotation will follow the scaling. Likewise, the argument MatrixOrderAppend passed to the TranslateTransform method specifies that the translation will follow the rotation.

Rect rect(0, 0, 50, 50);
Pen pen(Color(255, 255, 0, 0), 0);
graphics.ScaleTransform(1.75f, 0.5f);
graphics.RotateTransform(28.0f, MatrixOrderAppend);
graphics.TranslateTransform(150.0f, 150.0f, MatrixOrderAppend);
graphics.DrawRectangle(&pen, rect);

The following example makes the same method calls as the previous example, but the order of the calls is reversed. The resulting order of operations is first translate, then rotate, then scale, which produces a very different result than first scale, then rotate, then translate:

Rect rect(0, 0, 50, 50);
Pen pen(Color(255, 255, 0, 0), 0);
graphics.TranslateTransform(150.0f, 150.0f);
graphics.RotateTransform(28.0f, MatrixOrderAppend);
graphics.ScaleTransform(1.75f, 0.5f, MatrixOrderAppend);
graphics.DrawRectangle(&pen, rect);

One way to reverse the order of the individual transformations in a composite transformation is to reverse the order of a sequence of method calls. A second way to control the order of operations is to change the matrix order argument. The following example is the same as the previous example, except that MatrixOrderAppend has been changed to MatrixOrderPrepend. The matrix multiplication is done in the order SRT, where S, R, and T are the matrices for scale, rotate, and translate, respectively. The order of the composite transformation is first scale, then rotate, then translate.

Rect rect(0, 0, 50, 50);
Pen pen(Color(255, 255, 0, 0), 0);
graphics.TranslateTransform(150.0f, 150.0f,MatrixOrderPrepend);
graphics.RotateTransform(28.0f, MatrixOrderPrepend);
graphics.ScaleTransform(1.75f, 0.5f, MatrixOrderPrepend);
graphics.DrawRectangle(&pen, rect);

The result of the preceding example is the same result that we achieved in the first example of this section. This is because we reversed both the order of the method calls and the order of the matrix multiplication.


Using Regions

The GDI+ Region class allows you to define a custom shape. The shape can be made up of lines, polygons, and curves.

Two common uses for regions are hit testing and clipping. Hit testing is determining whether the mouse was clicked in a certain region of the screen. Clipping is restricting drawing to a certain region.

The following topics cover regions in more detail:

  • Hit Testing with a Region
  • Clipping with a Region


Hit Testing with a Region

The purpose of hit testing is to determine whether the cursor is over a given object, such as an icon or a button. The following example creates a plus-shaped region by forming the union of two rectangular regions. Assume that the variable point holds the location of the most recent click. The code checks to see whether point is in the plus-shaped region. If point is in the region (a hit), the region is filled with an opaque red brush. Otherwise, the region is filled with a semitransparent red brush.

Point point(60, 10);
// Assume that the variable "point" contains the location
// of the most recent click.
// To simulate a hit, assign (60, 10) to point.
// To simulate a miss, assign (0, 0) to point.

SolidBrush solidBrush(Color());
Region region1(Rect(50, 0, 50, 150));
Region region2(Rect(0, 50, 150, 50));

// Create a plus-shaped region by forming the union of region1 and region2.
// The union replaces region1.
region1.Union(&region2);

if(region1.IsVisible(point, &graphics))
{
   // The point is in the region. Use an opaque brush.
   solidBrush.SetColor(Color(255, 255, 0, 0));
}
else
{
   // The point is not in the region. Use a semitransparent brush.
   solidBrush.SetColor(Color(64, 255, 0, 0));
}

graphics.FillRegion(&solidBrush, &region1);


Clipping with a Region

One of the properties of the Graphics class is the clipping region. All drawing done by a given Graphics object is restricted to the clipping region of that Graphics object. You can set the clipping region by calling the SetClip method.

The following example constructs a path that consists of a single polygon. Then the code constructs a region based on that path. The address of the region is passed to the SetClip method of a Graphics object, and then two strings are drawn.

// Create a path that consists of a single polygon.
Point polyPoints[] = {Point(10, 10), Point(150, 10),
   Point(100, 75), Point(100, 150)};
GraphicsPath path;
path.AddPolygon(polyPoints, 4);

// Construct a region based on the path.
Region region(&path);

// Draw the outline of the region.
Pen pen(Color(255, 0, 0, 0));
graphics.DrawPath(&pen, &path);

// Set the clipping region of the Graphics object.
graphics.SetClip(&region);

// Draw some clipped strings.
FontFamily fontFamily(L"Arial");
Font font(&fontFamily, 36, FontStyleBold, UnitPixel);
SolidBrush solidBrush(Color(255, 255, 0, 0));

graphics.DrawString(L"A Clipping Region", 20, &font,
   PointF(15, 25), &solidBrush);

graphics.DrawString(L"A Clipping Region", 20, &font,
   PointF(15, 68), &solidBrush);

The following illustration shows the clipped strings.


Recoloring

Recoloring is the process of adjusting image colors. Some examples of recoloring are changing one color to another, adjusting a color's intensity relative to another color, adjusting the brightness or contrast of all colors, and converting colors to shades of gray.

The following topics cover recoloring in more detail:

  • Using a Color Matrix to Transform a Single Color
  • Translating Colors
  • Scaling Colors
  • Rotating Colors
  • Shearing Colors
  • Using a Color Remap Table


Using a Color Matrix to Transform a Single Color

GDI+ provides the Image and Bitmap classes for storing and manipulating images. Image and Bitmap objects store the color of each pixel as a 32-bit number: 8 bits each for red, green, blue, and alpha. Each of the four components is a number from 0 through 255, with 0 representing no intensity and 255 representing full intensity. The alpha component specifies the transparency of the color: 0 is fully transparent, and 255 is fully opaque.

A color vector is a 4-tuple of the form (red, green, blue, alpha). For example, the color vector (0, 255, 0, 255) represents an opaque color that has no red or blue, but has green at full intensity.

Another convention for representing colors uses the number 1 for maximum intensity and the number 0 for minimum intensity. Using that convention, the color described in the preceding paragraph would be represented by the vector (0, 1, 0, 1). GDI+ uses the convention of 1 as full intensity when it performs color transformations.

You can apply linear transformations (rotation, scaling, and the like) to color vectors by multiplying by a 4×4 matrix. However, you cannot use a 4×4 matrix to perform a translation (nonlinear). If you add a dummy fifth coordinate (for example, the number 1) to each of the color vectors, you can use a 5×5 matrix to apply any combination of linear transformations and translations. A transformation consisting of a linear transformation followed by a translation is called an affine transformation. A 5×5 matrix that represents an affine transformation is called a homogeneous matrix for a 4-space transformation. The element in the fifth row and fifth column of a 5×5 homogeneous matrix must be 1, and all of the other entries in the fifth column must be 0.

For example, suppose you want to start with the color (0.2, 0.0, 0.4, 1.0) and apply the following transformations:

  1. Double the red component
  2. Add 0.2 to the red, green, and blue components

The following matrix multiplication will perform the pair of transformations in the order listed.

The elements of a color matrix are indexed (zero-based) by row and then column. For example, the entry in the fifth row and third column of matrix M is denoted by M[4][2].

The 5×5 identity matrix (shown in the following illustration) has 1s on the diagonal and 0s everywhere else. If you multiply a color vector by the identity matrix, the color vector does not change. A convenient way to form the matrix of a color transformation is to start with the identity matrix and make a small change that produces the desired transformation.

For a more detailed discussion of matrices and transformations, see Coordinate Systems and Transformations.

The following example takes an image that is all one color (0.2, 0.0, 0.4, 1.0) and applies the transformation described in the preceding paragraphs.

Image            image(L"InputColor.bmp");
ImageAttributes  imageAttributes;
UINT             width = image.GetWidth();
UINT             height = image.GetHeight();

ColorMatrix colorMatrix = {
   2.0f, 0.0f, 0.0f, 0.0f, 0.0f,
   0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
   0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
   0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
   0.2f, 0.2f, 0.2f, 0.0f, 1.0f};

imageAttributes.SetColorMatrix(
   &colorMatrix,
   ColorMatrixFlagsDefault,
   ColorAdjustTypeBitmap);

graphics.DrawImage(&image, 10, 10);

graphics.DrawImage(
   &image,
   Rect(120, 10, width, height),  // destination rectangle
   0, 0,        // upper-left corner of source rectangle
   width,       // width of source rectangle
   height,      // height of source rectangle
   UnitPixel,
   &imageAttributes);

The following illustration shows the original image on the left and the transformed image on the right.

The code in the preceding example uses the following steps to perform the recoloring:

  1. Initialize a ColorMatrix structure.
  2. Create an ImageAttributes object and pass the address of the ColorMatrix structure to the SetColorMatrix method of the ImageAttributes object.
  3. Pass the address of the ImageAttributes object to the DrawImage method of a Graphics object.


Translating Colors

A translation adds a value to one or more of the four color components. The color matrix entries that represent translations are given in the following table.

Component to be translated | Matrix entry
Red | [4][0]
Green | [4][1]
Blue | [4][2]
Alpha | [4][3]

The following example constructs an Image object from the file ColorBars.bmp. Then the code adds 0.75 to the red component of each pixel in the image. The original image is drawn alongside the transformed image.

Image            image(L"ColorBars.bmp");
ImageAttributes  imageAttributes;
UINT             width = image.GetWidth();
UINT             height = image.GetHeight();

ColorMatrix colorMatrix = {
   1.0f,  0.0f, 0.0f, 0.0f, 0.0f,
   0.0f,  1.0f, 0.0f, 0.0f, 0.0f,
   0.0f,  0.0f, 1.0f, 0.0f, 0.0f,
   0.0f,  0.0f, 0.0f, 1.0f, 0.0f,
   0.75f, 0.0f, 0.0f, 0.0f, 1.0f};

imageAttributes.SetColorMatrix(
   &colorMatrix,
   ColorMatrixFlagsDefault,
   ColorAdjustTypeBitmap);

graphics.DrawImage(&image, 10, 10, width, height);

graphics.DrawImage(
   &image,
   Rect(150, 10, width, height),  // destination rectangle
   0, 0,        // upper-left corner of source rectangle
   width,       // width of source rectangle
   height,      // height of source rectangle
   UnitPixel,
   &imageAttributes);

The following illustration shows the original image on the left and the transformed image on the right.

The following table lists the color vectors for the four bars before and after the red translation. Note that because the maximum value for a color component is 1, the red component in the second row does not change. (Similarly, the minimum value for a color component is 0.)

Original | Translated
Black (0, 0, 0, 1) | (0.75, 0, 0, 1)
Red (1, 0, 0, 1) | (1, 0, 0, 1)
Green (0, 1, 0, 1) | (0.75, 1, 0, 1)
Blue (0, 0, 1, 1) | (0.75, 0, 1, 1)


Scaling Colors

A scaling transformation multiplies one or more of the four color components by a number. The color matrix entries that represent scaling are given in the following table.

Component to be scaled | Matrix entry
Red | [0][0]
Green | [1][1]
Blue | [2][2]
Alpha | [3][3]

The following example constructs an Image object from the file ColorBars2.bmp. Then the code scales the blue component of each pixel in the image by a factor of 2. The original image is drawn alongside the transformed image.

Image            image(L"ColorBars2.bmp");
ImageAttributes  imageAttributes;
UINT             width = image.GetWidth();
UINT             height = image.GetHeight();

ColorMatrix colorMatrix = {
   1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
   0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
   0.0f, 0.0f, 2.0f, 0.0f, 0.0f,
   0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
   0.0f, 0.0f, 0.0f, 0.0f, 1.0f};

imageAttributes.SetColorMatrix(
   &colorMatrix,
   ColorMatrixFlagsDefault,
   ColorAdjustTypeBitmap);

graphics.DrawImage(&image, 10, 10, width, height);

graphics.DrawImage(
   &image,
   Rect(150, 10, width, height),  // destination rectangle
   0, 0,        // upper-left corner of source rectangle
   width,       // width of source rectangle
   height,      // height of source rectangle
   UnitPixel,
   &imageAttributes);

The following illustration shows the original image on the left and the scaled image on the right.

The following table shows the color vectors for the four bars before and after the blue scaling. Note that the blue component in the fourth color bar went from 0.8 to 0.6. That is because GDI+ retains only the fractional part of the result. For example, (2)(0.8) = 1.6, and the fractional part of 1.6 is 0.6. Retaining only the fractional part ensures that the result is always in the interval [0, 1].

Original | Scaled
(0.4, 0.4, 0.4, 1) | (0.4, 0.4, 0.8, 1)
(0.4, 0.2, 0.2, 1) | (0.4, 0.2, 0.4, 1)
(0.2, 0.4, 0.2, 1) | (0.2, 0.4, 0.4, 1)
(0.4, 0.4, 0.8, 1) | (0.4, 0.4, 0.6, 1)

The following example constructs an Image object from the file ColorBars2.bmp. Then the code scales the red, green, and blue components of each pixel in the image. The red components are scaled down 25 percent, the green components are scaled down 35 percent, and the blue components are scaled down 50 percent.

Image            image(L"ColorBars.bmp");
ImageAttributes  imageAttributes;
UINT             width = image.GetWidth();
UINT             height = image.GetHeight();

ColorMatrix colorMatrix = {
   0.75f, 0.0f,  0.0f, 0.0f, 0.0f,
   0.0f,  0.65f, 0.0f, 0.0f, 0.0f,
   0.0f,  0.0f,  0.5f, 0.0f, 0.0f,
   0.0f,  0.0f,  0.0f, 1.0f, 0.0f,
   0.0f,  0.0f,  0.0f, 0.0f, 1.0f};

imageAttributes.SetColorMatrix(
   &colorMatrix,
   ColorMatrixFlagsDefault,
   ColorAdjustTypeBitmap);

graphics.DrawImage(&image, 10, 10, width, height);

graphics.DrawImage(
   &image,
   Rect(150, 10, width, height),  // destination rectangle
   0, 0,        // upper-left corner of source rectangle
   width,       // width of source rectangle
   height,      // height of source rectangle
   UnitPixel,
   &imageAttributes);

The following illustration shows the original image on the left and the scaled image on the right.

The following table shows the color vectors for the four bars before and after the red, green and blue scaling.

Original | Scaled
(0.6, 0.6, 0.6, 1) | (0.45, 0.39, 0.3, 1)
(0, 1, 1, 1) | (0, 0.65, 0.5, 1)
(1, 1, 0, 1) | (0.75, 0.65, 0, 1)
(1, 0, 1, 1) | (0.75, 0, 0.5, 1)


Rotating Colors

Rotation in a four-dimensional color space is difficult to visualize. We can make it easier to visualize rotation by agreeing to keep one of the color components fixed. Suppose we agree to keep the alpha component fixed at 1 (fully opaque). Then we can visualize a three-dimensional color space with red, green, and blue axes as shown in the following illustration.

A color can be thought of as a point in 3-D space. For example, the point (1, 0, 0) in space represents the color red, and the point (0, 1, 0) in space represents the color green.

The following illustration shows what it means to rotate the color (1, 0, 0) through an angle of 60 degrees in the Red-Green plane. Rotation in a plane parallel to the Red-Green plane can be thought of as rotation about the blue axis.

The following illustration shows how to initialize a color matrix to perform rotations about each of the three coordinate axes (red, green, blue).

The following example takes an image that is all one color (1, 0, 0.6) and applies a 60-degree rotation about the blue axis. The angle of the rotation is swept out in a plane that is parallel to the Red-Green plane.

Image            image(L"RotationInput.bmp");
ImageAttributes  imageAttributes;
UINT             width = image.GetWidth();
UINT             height = image.GetHeight();
REAL             degrees = 60;
REAL             pi = acos(-1);  // the angle whose cosine is -1.
REAL             r = degrees * pi / 180;  // degrees to radians

ColorMatrix colorMatrix = {
   cos(r),  sin(r), 0.0f, 0.0f, 0.0f,
   -sin(r), cos(r), 0.0f, 0.0f, 0.0f,
   0.0f,    0.0f,   1.0f, 0.0f, 0.0f,
   0.0f,    0.0f,   0.0f, 1.0f, 0.0f,
   0.0f,    0.0f,   0.0f, 0.0f, 1.0f};

imageAttributes.SetColorMatrix(
   &colorMatrix,
   ColorMatrixFlagsDefault,
   ColorAdjustTypeBitmap);

graphics.DrawImage(&image, 10, 10, width, height);

graphics.DrawImage(
   &image,
   Rect(130, 10, width, height),  // destination rectangle
   0, 0,        // upper-left corner of source rectangle
   width,       // width of source rectangle
   height,      // height of source rectangle
   UnitPixel,
   &imageAttributes);

The following illustration shows the original image on the left and the color-rotated image on the right.

The color rotation performed in the preceding code example can be visualized as follows.


Shearing Colors

Shearing increases or decreases a color component by an amount proportional to another color component. For example, consider the transformation where the red component is increased by one half the value of the blue component. Under such a transformation, the color (0.2, 0.5, 1) would become (0.7, 0.5, 1). The new red component is 0.2 + (1/2)(1) = 0.7.

The following example constructs an Image object from the file ColorBars4.bmp. Then the code applies the shearing transformation described in the preceding paragraph to each pixel in the image.

Image            image(L"ColorBars4.bmp");
ImageAttributes  imageAttributes;
UINT             width = image.GetWidth();
UINT             height = image.GetHeight();

ColorMatrix colorMatrix = {
   1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
   0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
   0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
   0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
   0.0f, 0.0f, 0.0f, 0.0f, 1.0f};

imageAttributes.SetColorMatrix(
   &colorMatrix,
   ColorMatrixFlagsDefault,
   ColorAdjustTypeBitmap);

graphics.DrawImage(&image, 10, 10, width, height);

graphics.DrawImage(
   &image,
   Rect(150, 10, width, height),  // destination rectangle
   0, 0,        // upper-left corner of source rectangle
   width,       // width of source rectangle
   height,      // height of source rectangle
   UnitPixel,
   &imageAttributes);

The following illustration shows the original image on the left and the sheared image on the right.

The following table shows the color vectors for the four bars before and after the shearing transformation.

Original | Sheared
(0, 0, 1, 1) | (0.5, 0, 1, 1)
(0.5, 1, 0.5, 1) | (0.75, 1, 0.5, 1)
(1, 1, 0, 1) | (1, 1, 0, 1)
(0.4, 0.4, 0.4, 1) | (0.6, 0.4, 0.4, 1)


Using a Color Remap Table

Remapping is the process of converting the colors in an image according to a color remap table. The color remap table is an array of ColorMap structures. Each ColorMap structure in the array has an oldColor member and a newColor member.

When GDI+ draws an image, each pixel of the image is compared to the array of old colors. If a pixel's color matches an old color, its color is changed to the corresponding new color. The colors are changed only for rendering — the color values of the image itself (stored in an Image or Bitmap object) are not changed.

To draw a remapped image, initialize an array of ColorMap structures. Pass the address of that array to the SetRemapTable method of an ImageAttributes object, and then pass the address of the ImageAttributes object to the DrawImage method of a Graphics object.

The following example creates an Image object from the file RemapInput.bmp. The code creates a color remap table that consists of a single ColorMap structure. The oldColor member of the ColorRemap structure is red, and the newColor member is blue. The image is drawn once without remapping and once with remapping. The remapping process changes all the red pixels to blue.

Image            image(L"RemapInput.bmp");
ImageAttributes  imageAttributes;
UINT             width = image.GetWidth();
UINT             height = image.GetHeight();
ColorMap         colorMap[1];

colorMap[0].oldColor = Color(255, 255, 0, 0);  // opaque red
colorMap[0].newColor = Color(255, 0, 0, 255);  // opaque blue

imageAttributes.SetRemapTable(1, colorMap, ColorAdjustTypeBitmap);

graphics.DrawImage(&image, 10, 10, width, height);

graphics.DrawImage(
   &image,
   Rect(150, 10, width, height),  // destination rectangle
   0, 0,        // upper-left corner of source rectangle
   width,       // width of source rectangle
   height,      // height of source rectangle
   UnitPixel,
   &imageAttributes);

The following illustration shows the original image on the left and the remapped image on the right.

*


Printing

With a few minor adjustments to your code, you can send GDI+ output to a printer rather than to a screen. To draw on a printer, obtain a device context handle for the printer and pass that handle to a Graphics constructor. Place your GDI+ drawing commands in between calls to StartDoc and EndDoc.

The following topics cover sending GDI+ output to printers in more detail:

  • Sending GDI+ Output to a Printer
  • Displaying a Print Dialog Box
  • Optimizing Printing by Providing a Printer Handle


Sending GDI+ Output to a Printer

Using GDI+ to draw on a printer is similar to using GDI+ to draw on a computer screen. To draw on a printer, obtain a device context handle for the printer and then pass that handle to a Graphics constructor.

The following console application draws a line, a rectangle, and an ellipse on a printer named MyPrinter:

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   // Get a device context for the printer.
   HDC hdcPrint = CreateDC(NULL, TEXT("\\\\printserver\\print1"), NULL, NULL);

   DOCINFO docInfo;
   ZeroMemory(&docInfo, sizeof(DOCINFO));
   docInfo.cbSize = sizeof(DOCINFO);
   docInfo.lpszDocName = "GdiplusPrint";

   StartDoc(hdcPrint, &docInfo);
   StartPage(hdcPrint);
      Graphics* graphics = new Graphics(hdcPrint);
      Pen* pen = new Pen(Color(255, 0, 0, 0));
      graphics->DrawLine(pen, 50, 50, 350, 550);
      graphics->DrawRectangle(pen, 50, 50, 300, 500);
      graphics->DrawEllipse(pen, 50, 50, 300, 500);
      delete pen;
      delete graphics;
   EndPage(hdcPrint);
   EndDoc(hdcPrint);

   DeleteDC(hdcPrint);
   GdiplusShutdown(gdiplusToken);
   return 0;
}

In the preceding code, the three GDI+ drawing commands are in between calls to the StartDoc and EndDoc functions, each of which receives the printer device context handle. All graphics commands between StartDoc and EndDoc are routed to a temporary metafile. After the call to EndDoc, the printer driver converts the data in the metafile into the format required by the specific printer being used.

Note If spooling is not enabled for the printer being used, the graphics output is not routed to a metafile. Instead, individual graphics commands are processed by the printer driver and then sent to the printer.

Generally you won't want to hard-code the name of a printer as was done in the preceding console application. One alternative to hard-coding the name is to call GetDefaultPrinter to obtain the name of the default printer. Before you call GetDefaultPrinter, you must allocate a buffer large enough to hold the printer name. You can determine the size of the required buffer by calling GetDefaultPrinter, passing NULL as the first argument.

Note The GetDefaultPrinter function is supported only on Windows 2000 and later.

The following console application gets the name of the default printer and then draws a rectangle and an ellipse on that printer. The DrawRectangle call is in between calls to StartPage and EndPage, so the rectangle is on a page by itself. Similarly, the ellipse is on a page by itself.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   DWORD size;
   HDC hdcPrint;

   DOCINFO docInfo;
   ZeroMemory(&docInfo, sizeof(DOCINFO));
   docInfo.cbSize = sizeof(DOCINFO);
   docInfo.lpszDocName = "GdiplusPrint";

   // Get the size of the default printer name.
   GetDefaultPrinter(NULL, &size);

   // Allocate a buffer large enough to hold the printer name.
   TCHAR* buffer = new TCHAR[size];

   // Get the printer name.
   if(!GetDefaultPrinter(buffer, &size))
   {
      printf("Failure");
   }
   else
   {
      // Get a device context for the printer.
      hdcPrint = CreateDC(NULL, buffer, NULL, NULL);

      StartDoc(hdcPrint, &docInfo);
         Graphics* graphics;
         Pen* pen = new Pen(Color(255, 0, 0, 0));

         StartPage(hdcPrint);
            graphics = new Graphics(hdcPrint);
            graphics->DrawRectangle(pen, 50, 50, 200, 300);
            delete graphics;
         EndPage(hdcPrint);

         StartPage(hdcPrint);
            graphics = new Graphics(hdcPrint);
            graphics->DrawEllipse(pen, 50, 50, 200, 300);
            delete graphics;
         EndPage(hdcPrint);

         delete pen;
      EndDoc(hdcPrint);

      DeleteDC(hdcPrint);
   }

   delete buffer;

   GdiplusShutdown(gdiplusToken);
   return 0;
}


Displaying a Print Dialog Box

One way to get a device context handle for a printer is to display a print dialog box and allow the user to choose a printer. The PrintDlg function (which displays the dialog box) has one parameter that is the address of a PRINTDLG structure. The PRINTDLG structure has several members, but you can leave most of them set to their default values. The two members you need to set are lStructSize and Flags. Set lStructSize to sizeof(PRINTDLG) and set Flags to PD_RETURNDC. Setting Flags to PC_RETURNDC specifies that you want the PrintDlg function to fill the hDC field with a device context handle for the printer chosen by the user.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   DOCINFO docInfo;
   ZeroMemory(&docInfo, sizeof(DOCINFO));
   docInfo.cbSize = sizeof(DOCINFO);
   docInfo.lpszDocName = "GdiplusPrint";

   // Create a PRINTDLG structure, and initialize the appropriate fields.
   PRINTDLG printDlg;
   ZeroMemory(&printDlg, sizeof(PRINTDLG));
   printDlg.lStructSize = sizeof(PRINTDLG);
   printDlg.Flags = PD_RETURNDC;

   // Display a print dialog box.
   if(!PrintDlg(&printDlg))
   {
      printf("Failure\n");
   }
   else
   {
      // Now that PrintDlg has returned, a device context handle
      // for the chosen printer is in printDlg->hDC.

      StartDoc(printDlg.hDC, &docInfo);
      StartPage(printDlg.hDC);
         Graphics* graphics = new Graphics(printDlg.hDC);
         Pen* pen = new Pen(Color(255, 0, 0, 0));
         graphics->DrawRectangle(pen, 200, 500, 200, 150);
         graphics->DrawEllipse(pen, 200, 500, 200, 150);
         graphics->DrawLine(pen, 200, 500, 400, 650);
         delete pen;
         delete graphics;
      EndPage(printDlg.hDC);
      EndDoc(printDlg.hDC);
   }

   if(printDlg.hDevMode)
      GlobalFree(printDlg.hDevMode);
   if(printDlg.hDevNames)
      GlobalFree(printDlg.hDevNames);
   if(printDlg.hDC)
      DeleteDC(printDlg.hDC);

   GdiplusShutdown(gdiplusToken);
   return 0;
}


Optimizing Printing by Providing a Printer Handle

One of the constructors for the Graphics class receives a device context handle and a printer handle. When you send GDI+ commands to certain PostScript printers, the performance will be better if you create your Graphics object with that particular constructor.

The following console application calls GetDefaultPrinter to get the name of the default printer. The code passes the printer name to CreateDC to obtain a device context handle for the printer. The code also passes the printer name to OpenPrinter to obtain a printer handle. Both the device context handle and the printer handle are passed to the Graphics constructor. Then two figures are drawn on the printer.

Note The GetDefaultPrinter function is supported only on Windows 2000 and later.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   DWORD   size;
   HDC     hdcPrint;
   HANDLE  printerHandle;

   DOCINFO docInfo;
   ZeroMemory(&docInfo, sizeof(DOCINFO));
   docInfo.cbSize = sizeof(DOCINFO);
   docInfo.lpszDocName = "GdiplusPrint";

   // Get the length of the printer name.
   GetDefaultPrinter(NULL, &size);
   TCHAR* buffer = new TCHAR[size];

   // Get the printer name.
   if(!GetDefaultPrinter(buffer, &size))
   {
      printf("Failure");
   }
   else
   {
      // Get a device context for the printer.
      hdcPrint = CreateDC(NULL, buffer, NULL, NULL);

      // Get a printer handle.
      OpenPrinter(buffer, &printerHandle, NULL);

      StartDoc(hdcPrint, &docInfo);
      StartPage(hdcPrint);
         Graphics* graphics = new Graphics(hdcPrint, printerHandle);
         Pen* pen = new Pen(Color(255, 0, 0, 0));
         graphics->DrawRectangle(pen, 200, 500, 200, 150);
         graphics->DrawEllipse(pen, 200, 500, 200, 150);
         delete(pen);
         delete(graphics);
      EndPage(hdcPrint);
      EndDoc(hdcPrint);

      ClosePrinter(printerHandle);
      DeleteDC(hdcPrint);
   }

   delete buffer;

   GdiplusShutdown(gdiplusToken);
   return 0;
}


GDI+ Reference

The following topics provide reference information about the GDI+ API with the C++ programming language:

  • Classes
  • Functions
  • Constants
  • Enumerations
  • Structures


Classes

GDI+ provides the following classes:

  • AdjustableArrowCap
  • Bitmap
  • BitmapData
  • Brush
  • CachedBitmap
  • CharacterRange
  • Color
  • CustomLineCap
  • EncoderParameter
  • EncoderParameters
  • Font
  • FontCollection
  • FontFamily
  • GdiplusBase
  • Graphics
  • GraphicsPath
  • GraphicsPathIterator
  • HatchBrush
  • Image
  • ImageAttributes
  • ImageCodecInfo
  • InstalledFontCollection
  • LinearGradientBrush
  • Matrix
  • Metafile
  • MetafileHeader
  • PathData
  • PathGradientBrush
  • Pen
  • Point
  • PointF
  • PrivateFontCollection
  • PropertyItem
  • Rect
  • RectF
  • Region
  • Size
  • SizeF
  • SolidBrush
  • StringFormat
  • TextureBrush


AdjustableArrowCap Class

The AdjustableArrowCap class is a subclass of the CustomLineCap Class. This class builds a line cap that looks like an arrow.

Inheritance

GdiplusBase
CustomLineCap
AdjustableArrowCap

Constructors

Constructor | Description
AdjustableArrowCap | Creates and initializes a new AdjustableArrowCap object.

Methods

Uninherited

Method | Description
GetHeight | Gets the height of the arrow cap.
GetMiddleInset | Gets the value of the inset.
GetWidth | Gets the width of the arrow cap.
IsFilled | Checks to determine whether the arrow cap is filled.
SetFillState | Sets the fill state of the arrow cap.
SetHeight | Sets the height of the arrow cap.
SetMiddleInset | Sets the inset value of the arrow cap.
SetWidth | Sets the width of the arrow cap.

Inherited from CustomLineCap

Method | Description
Clone | Copies the content of the existing object into a new CustomLineCap object.
GetBaseCap | Gets the style of the base cap.
GetBaseInset | Gets the offset from the line cap at the base of the line to the start of the line.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetStrokeCaps | Gets the end cap styles for both the start and end caps.
GetStrokeJoin | Gets the style of LineJoin used to join multiple lines in the same GraphicsPath object.
GetWidthScale | Gets the value of the scale width.
SetBaseCap | Sets the style of base cap.
SetBaseInset | Sets the offset from the line cap at the base of the line to the start of the line.
SetStrokeCap | Sets the line caps for both the start and end caps.
SetStrokeCaps | Sets the end cap styles for both the start and end caps.
SetStrokeJoin | Sets the style of LineJoin used to join multiple lines in the same GraphicsPath.
SetWidthScale | Sets the value of the scale width.

Remarks

A line cap is the shape on the end of a line. Use the Pen::SetCustomStartCap and Pen::SetCustomEndCap methods to associate an AdjustableArrowCap object with a Pen object.


AdjustableArrowCap::AdjustableArrowCap(height, width, isFilled)

Creates an adjustable arrow line cap with the specified height and width. The arrow line cap can be filled or nonfilled. The middle inset defaults to zero.

AdjustableArrowCap(
  REAL height,
  REAL width,
  BOOL isFilled
);

Parameters

height
[in] Real number that specifies the length, in units, of the arrow from its base to its point.
width
[in] Real number that specifies the distance, in units, between the corners of the base of the arrow.
isFilled
[in] Boolean value that specifies whether the arrow is filled. The default value is TRUE.

Return Values

This method does not return a value.

Remarks

The middle inset is the number of units that the midpoint of the base shifts towards the vertex. A middle inset of zero results in no shift — the base is a straight line, giving the arrow a triangular shape. A positive (greater than zero) middle inset results in a shift the specified number of units toward the vertex — the base is an arrow shape that points toward the vertex, giving the arrow cap a V-shape. A negative (less than zero) middle inset results in a shift the specified number of units away from the vertex — the base becomes an arrow shape that points away from the vertex, giving the arrow either a diamond shape (if the absolute value of the middle inset is equal to the height) or distorted diamond shape. If the middle inset is equal to or greater than the height of the arrow cap, the cap does not appear at all. The value of the middle inset affects the arrow cap only if the arrow cap is filled. The middle inset defaults to zero when an AdjustableArrowCap object is constructed.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluslinecaps.h; include Gdiplus.h.

See Also

Reference
GetMiddleInset, SetMiddleInset


AdjustableArrowCap Methods

This topic lists the methods of the AdjustableArrowCap class. For a complete class listing, see AdjustableArrowCap Class.

  • Clone()
  • GetBaseCap()
  • GetBaseInset()
  • GetHeight()
  • GetLastStatus()
  • GetMiddleInset()
  • GetStrokeCaps(startCap, endCap)
  • GetStrokeJoin()
  • GetWidth()
  • GetWidthScale()
  • IsFilled()
  • SetBaseCap(baseCap)
  • SetBaseInset(Inset)
  • SetFillState(isFilled)
  • SetHeight(height)
  • SetMiddleInset(middleInset)
  • SetStrokeCap(strokeCap)
  • SetStrokeCaps(startCap, endCap)
  • SetStrokeJoin(lineJoin)
  • SetWidth(width)
  • SetWidthScale(widthScale)


AdjustableArrowCap::GetHeight()

The GetHeight method gets the height of the arrow cap. The height is the distance from the base of the arrow to its vertex.

REAL GetHeight(void);

Parameters

This method has no parameters.

Return Values

This method returns the height of the arrow cap.

Example Code [C++]

The following example creates an AdjustableArrowCap object, myArrow, and sets the height of the cap. The code then creates a Pen object, assigns myArrow as the ending line cap for this Pen object, and draws a capped line. Next, the code gets the height of the arrow cap, creates a new arrow cap with height equal to the height of myArrow, assigns the new arrow cap as the ending line cap for the Pen object, and draws another capped line.

VOID Example_GetHeight(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an AdjustableArrowCap with a height of 10 pixels.
   AdjustableArrowCap myArrow(10, 10, true);

   // Create a Pen, and assign myArrow as the end cap.
   Pen arrowPen(Color(255, 0, 0, 0));
   arrowPen.SetCustomEndCap(&myArrow);

   // Draw a line using arrowPen.
   graphics.DrawLine(&arrowPen, Point(0, 20), Point(100, 20));

   // Create a second arrow cap using the height of the first one.
   AdjustableArrowCap otherArrow(myArrow.GetHeight(), 20, true);

   // Assign the new arrow cap as the end cap for arrowPen.
   arrowPen.SetCustomEndCap(&otherArrow);

   // Draw a line using arrowPen.
   graphics.DrawLine(&arrowPen, Point(0, 55), Point(100, 55));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluslinecaps.h; include Gdiplus.h.


AdjustableArrowCap::GetMiddleInset()

The GetMiddleInset method gets the value of the inset. The middle inset is the number of units that the midpoint of the base shifts towards the vertex.

REAL GetMiddleInset(void);

Parameters

This method has no parameters.

Return Values

This method returns the inset value.

Remarks

The middle inset is the number of units that the midpoint of the base shifts towards the vertex. A middle inset of zero results in no shift — the base is a straight line, giving the arrow a triangular shape. A positive (greater than zero) middle inset results in a shift the specified number of units toward the vertex — the base is an arrow shape that points toward the vertex, giving the arrow cap a V-shape. A negative (less than zero) middle inset results in a shift the specified number of units away from the vertex — the base becomes an arrow shape that points away from the vertex, giving the arrow either a diamond shape (if the absolute value of the middle inset is equal to the height) or distorted diamond shape. If the middle inset is equal to or greater than the height of the arrow cap, the cap does not appear at all. The value of the middle inset affects the arrow cap only if the arrow cap is filled. The middle inset defaults to zero when an AdjustableArrowCap object is constructed.

Example Code [C++]

The following example creates an AdjustableArrowCap object, myArrow, with middle inset set to zero (default value). The code then creates a Pen object, assigns myArrow as the ending line cap for this Pen object, and draws a capped line. Next, the code gets the middle inset, increments it, and draws another capped line.

VOID Example_GetMiddleInset(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an AdjustableArrowCap with width and height set to 10.
   // Middle inset defaults to 0 pixels.
   AdjustableArrowCap myArrow(10, 10, true);

   // Create a Pen, and assign myArrow as the end cap.
   Pen arrowPen(Color(255, 0, 0, 0));
   arrowPen.SetCustomEndCap(&myArrow);

   // Draw a line using arrowPen.
   graphics.DrawLine(&arrowPen, Point(0, 10), Point(100, 10));

   // Get the inset of the arrow.
   REAL inset = myArrow.GetMiddleInset();

   // Increase inset by 5 pixels and draw another line.
   myArrow.SetMiddleInset(inset + 5);
   arrowPen.SetCustomEndCap(&myArrow);
   graphics.DrawLine(&arrowPen, Point(0, 40), Point(100, 40));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluslinecaps.h; include Gdiplus.h.


AdjustableArrowCap::GetWidth()

The GetWidth method gets the width of the arrow cap. The width is the distance between the endpoints of the base of the arrow.

REAL GetWidth(void);

Parameters

This method has no parameters.

Return Values

This method returns the width of the arrow cap.

Example Code [C++]

The following example creates an AdjustableArrowCap object, myArrow, and sets the width of the cap to 5 pixels. Next, the code creates a Pen object, assigns myArrow as the ending line cap for this Pen object, and draws a capped line. The code obtains the width using GetWidth and sets the height equal to the width. The code then draws another capped line with the new cap.

VOID Example_GetWidth(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an AdjustableArrowCap with a width of 10 pixels.
   AdjustableArrowCap myArrow(10, 5, true);

   // Create a Pen, and assign myArrow as the end cap.
   Pen arrowPen(Color(255, 0, 0, 0));
   arrowPen.SetCustomEndCap(&myArrow);

   // Get the width of the arrow.
   REAL width = myArrow.GetWidth();

   // Draw a line using arrowPen.
   graphics.DrawLine(&arrowPen, Point(0, 0), Point(100, 100));

   // Set height equal to width and draw another line.
   myArrow.SetHeight(width);
   arrowPen.SetCustomEndCap(&myArrow);
   graphics.DrawLine(&arrowPen, Point(0, 40), Point(100, 140));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluslinecaps.h; include Gdiplus.h.


AdjustableArrowCap::IsFilled()

The IsFilled method determines whether the arrow cap is filled.

BOOL IsFilled(void);

Parameters

This method has no parameters.

Return Values

If the arrow cap is filled, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates an AdjustableArrowCap object, myArrow, and sets the fill mode to TRUE. The code then creates a Pen object and assigns myArrow as the ending line cap for this Pen object. Next, the code tests whether myArrow is filled and, if it is, draws a line.

VOID Example_D(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an AdjustableArrowCap that is filled.
   AdjustableArrowCap myArrow(10, 10, true);

   // Create a Pen, and assign myArrow as the end cap.
   Pen arrowPen(Color(255, 0, 0, 0));
   arrowPen.SetCustomEndCap(&myArrow);

   // If the cap is filled, draw a line using arrowPen.
   if (myArrow.IsFilled())
   {
       graphics.DrawLine(&arrowPen, Point(0, 0), Point(100, 100));
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluslinecaps.h; include Gdiplus.h.


AdjustableArrowCap::SetFillState(isFilled)

The SetFillState method sets the fill state of the arrow cap. If the arrow cap is not filled, only the outline is drawn.

Status SetFillState(
  BOOL isFilled
);

Parameters

isFilled
[in] Boolean value that specifies whether the arrow cap is filled.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates an AdjustableArrowCap object, myArrow, and sets the fill mode to FALSE. The code then creates a Pen object and assigns myArrow as the ending line cap for this Pen object. Next, the code draws a line.

VOID Example_SetFillState(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an AdjustableArrowCap. Fill state defaults to TRUE when
   // arrow cap is constructed.
   AdjustableArrowCap myArrow(10, 10);

   // Set fill state to FALSE.
   myArrow.SetFillState(false);

   // Create a Pen, and assign myArrow as the end cap.
   Pen arrowPen(Color(255, 0, 0, 0));
   arrowPen.SetCustomEndCap(&myArrow);

   // Draw a line using arrowPen.
   graphics.DrawLine(&arrowPen, Point(0, 0), Point(100, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluslinecaps.h; include Gdiplus.h.


AdjustableArrowCap::SetHeight(height)

The SetHeight method sets the height of the arrow cap. This is the distance from the base of the arrow to its vertex.

Status SetHeight(
  REAL height
);

Parameters

height
[in] Real number that specifies the height, in units, for the arrow cap.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates an AdjustableArrowCap object, myArrow, and sets the height of the cap to 15 pixels. The code then creates a Pen object and assigns myArrow as the ending line cap for this Pen object. Next, the code draws a capped line.

VOID Example_SetHeight(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an AdjustableArrowCap with a width of 10 pixels.
   AdjustableArrowCap myArrow(10, 5, true);

   // Create a Pen, and assign myArrow as the end cap.
   Pen arrowPen(Color(255, 0, 0, 0));
   arrowPen.SetCustomEndCap(&myArrow);

   // Get the width of the arrow.
   REAL width = myArrow.GetWidth();

   // Draw a line using arrowPen.
   graphics.DrawLine(&arrowPen, Point(0, 0), Point(100, 100));

   // Set height equal to width and draw another line.
   myArrow.SetHeight(width);
   arrowPen.SetCustomEndCap(&myArrow);
   graphics.DrawLine(&arrowPen, Point(0, 40), Point(100, 140));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluslinecaps.h; include Gdiplus.h.


AdjustableArrowCap::SetMiddleInset(middleInset)

The SetMiddleInset method sets the number of units that the midpoint of the base shifts towards the vertex.

Status SetMiddleInset(
  REAL middleInset
);

Parameters

middleInset
[in] Real number that specifies the number of units that the midpoint of the base shifts towards the vertex.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The middle inset is the number of units that the midpoint of the base shifts towards the vertex. A middle inset of zero results in no shift — the base is a straight line, giving the arrow a triangular shape. A positive (greater than zero) middle inset results in a shift the specified number of units toward the vertex — the base is an arrow shape that points toward the vertex, giving the arrow cap a V-shape. A negative (less than zero) middle inset results in a shift the specified number of units away from the vertex — the base becomes an arrow shape that points away from the vertex, giving the arrow either a diamond shape (if the absolute value of the middle inset is equal to the height) or distorted diamond shape. If the middle inset is equal to or greater than the height of the arrow cap, the cap does not appear at all. The value of the middle inset affects the arrow cap only if the arrow cap is filled. The middle inset defaults to zero when an AdjustableArrowCap object is constructed.

Example Code [C++]

The following example creates an AdjustableArrowCap object, myArrow, and sets the middle inset of the cap to 5 pixels. The code then creates a Pen object and assigns myArrow as the ending line cap for this Pen object. Next, the code draws a capped line.

VOID Example_SetMiddleInset(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an AdjustableArrowCap, and set the middle inset to 5.
   AdjustableArrowCap myArrow(10, 10, true);
   myArrow.SetMiddleInset(5.0f);

   // Create a Pen, and assign myArrow as the end cap.
   Pen arrowPen(Color(255, 0, 0, 0));
   arrowPen.SetCustomEndCap(&myArrow);

   // Draw a line using arrowPen.
   graphics.DrawLine(&arrowPen, Point(0, 0), Point(100, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluslinecaps.h; include Gdiplus.h.


AdjustableArrowCap::SetWidth(width)

The SetWidth method sets the width of the arrow cap. The width is the distance between the endpoints of the base of the arrow.

Status SetWidth(
  REAL width
);

Parameters

width
[in] Real number that specifies the distance, in units, between the two corners of the base of the arrow.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates an AdjustableArrowCap object, myArrow, and sets the width of the cap to 10 pixels. The code then creates a Pen object, assigns myArrow as the ending line cap for this Pen object, and draws a capped line. Next, the code sets the width to 15 pixels, reassigns the arrow cap to the pen, and draws a new capped line.

VOID Example_SetWidth(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an AdjustableArrowCap, and set the middle inset to 5.
   AdjustableArrowCap myArrow(10, 10, true);

   // Create a Pen, and assign myArrow as the end cap.
   Pen arrowPen(Color(255, 0, 0, 0));
   arrowPen.SetCustomEndCap(&myArrow);

   // Draw a line using arrowPen.
   graphics.DrawLine(&arrowPen, Point(0, 0), Point(100, 100));

   // Set the cap to the new width, and reassign the arrow cap
   // to the pen object.
   myArrow.SetWidth(15.7f);
   arrowPen.SetCustomEndCap(&myArrow);

   // Draw a line with new cap.
   graphics.DrawLine(&arrowPen, Point(0, 40), Point(100, 140));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluslinecaps.h; include Gdiplus.h.


Bitmap Class

The Bitmap class inherits from the Image class. The Image class provides methods for loading and saving vector images (metafiles) and raster images (bitmaps). The Bitmap class expands on the capabilities of the Image class by providing additional methods for creating and manipulating raster images.

Inheritance

GdiplusBase
Image
Bitmap

Constructors

Constructor | Description
Bitmap | Overloaded. Creates and initializes a new Bitmap object.

Methods

Uninherited

Method | Description
Clone | Overloaded. Creates a copy of this Bitmap object.
FromBITMAPINFO | Creates a Bitmap object based on a BITMAPINFO structure and an array of pixel data.
FromDirectDrawSurface7 | Creates a Bitmap object based on a DirectDraw surface.
FromFile | Creates a Bitmap object based on an image file.
FromHBITMAP | Creates a Bitmap object based on a handle to a bitmap and a handle to a palette.
FromHICON | Creates a Bitmap object based on a handle to an icon.
FromResource | Creates a Bitmap object based on an instance handle and the name of a bitmap resource.
FromStream | Creates a Bitmap object based on a stream.
GetHBITMAP | Gets a bitmap handle that represents this Bitmap object.
GetHICON | Gets an icon handle that represents this Bitmap object.
GetPixel | Gets the color of a specified pixel in this bitmap.
LockBits | Locks a portion of the pixels in this bitmap.
SetPixel | Sets the color of a specified pixel in this bitmap.
SetResolution | Sets the resolution of this Bitmap object.
UnlockBits | Unlocks a portion of the pixels in this bitmap.

Inherited from Image

Method | Description
Clone | Creates a new Image object and initializes it with the contents of this Image object.
GetAllPropertyItems | Gets all the property items (pieces of metadata) stored in this Image object.
GetBounds | Gets a rectangle that indicates the size of the image.
GetEncoderParameterList | Gets the list of parameters supported by a specified encoder.
GetEncoderParameterListSize | Gets the size (in bytes) of the list of parameters supported by a specified encoder.
GetFlags | Gets a set of flags that indicate certain attributes of this Image object.
GetFrameCount | Gets the number of frames in a specified dimension of this Image object.
GetFrameDimensionsCount | Gets the number of frame dimensions in this Image object.
GetFrameDimensionsList | Gets the frame dimension IDs of this Image object.
GetHeight | Gets the height, in pixels, of this image.
GetHorizontalResolution | Gets the horizontal resolution, in dots per inch, of this image.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetPalette | Gets the color palette of this Image object.
GetPaletteSize | Gets the size, in bytes, of the color palette of this Image object.
GetPhysicalDimension | Gets the width and height of this image.
GetPixelFormat | Gets the pixel format of this image.
GetPropertyCount | Gets the number of property items (pieces of metadata) stored in this Image object.
GetPropertyIdList | Gets a list of the property IDs stored in this Image object.
GetPropertyItem | Gets a specified property item (piece of metadata) from this Image object.
GetPropertyItemSize | Gets the size (in bytes) of a specified property item (piece of metadata) stored in this Image object.
GetPropertySize | Gets the total size, in bytes, of the property items stored in this Image object. Also gets the number of property items.
GetRawFormat | Gets a GUID that identifies the format of this Image object.
GetThumbnailImage | Gets a thumbnail image from this Image object.
GetType | Gets the image type (bitmap or metafile).
GetVerticalResolution | Gets the vertical resolution, in dots per inch, of this image.
GetWidth | Gets the width, in pixels, of this image.
RemovePropertyItem | Removes a property item (piece of metadata) from this Image object.
RotateFlip | Rotates this image.
Save | Overloaded. Saves this image to a file or to a stream.
SaveAdd | Overloaded. Adds a frame to this Image object.
SelectActiveFrame | Selects a specified frame of this Image object.
SetPalette | Sets the color palette of this Image object.
SetPropertyItem | Sets a specified property item (piece of metadata) of this Image object.


Bitmap Constructors

This topic lists the constructors of the Bitmap class. For a complete class listing, see Bitmap Class.

  • Bitmap(filename, useIcm)
  • Bitmap(gdiBitmapInfo, gdiBitmapData)
  • Bitmap(hbm, hpal)
  • Bitmap(hicon)
  • Bitmap(hInstance, bitmapName)
  • Bitmap(stream, useIcm)
  • Bitmap(surface)
  • Bitmap(width, height, format)
  • Bitmap(width, height, stride, format, scan0)
  • Bitmap(width, height, target)


Bitmap::Bitmap(filename, useIcm)

Creates a Bitmap object based on an image file.

Bitmap(
  const WCHAR* filename,
  BOOL useIcm
);

Parameters

filename
[in] Pointer to a null-terminated string that specifies the path name of the image file. The graphics file formats supported by GDI+ are BMP, GIF, JPEG, PNG, TIFF, Exif, WMF, and EMF.
useIcm
[in] Optional. Boolean value that specifies whether the new Bitmap object applies color correction according to color management information that is embedded in the image file. Embedded information can include International Color Consortium (ICC) profiles, gamma values, and chromaticity information. TRUE specifies that color correction is enabled, and FALSE specifies that color correction is not enabled. The default value is FALSE.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, FromFile, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Basic Color Management Concepts, Images, Bitmaps, and Metafiles


Bitmap::Bitmap(gdiBitmapInfo, gdiBitmapData)

Creates a Bitmap object based on a BITMAPINFO structure and an array of pixel data.

Bitmap(
  const BITMAPINFO* gdiBitmapInfo,
  VOID* gdiBitmapData
);

Parameters

gdiBitmapInfo
[in] Pointer to a GDI BITMAPINFO structure. This structure defines several bitmap attributes, such as size and pixel format. The BITMAPINFO structure is defined in Wingdi.h.
gdiBitmapData
[in] Pointer to an array of bytes that contains the pixel data.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Bitmaps, FromBITMAPINFO, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::Bitmap(hbm, hpal)

Creates a Bitmap object based on a handle to a Windows GDI bitmap and a handle to a GDI palette.

Bitmap(
  HBITMAP hbm,
  HPALETTE hpal
);

Parameters

hbm
[in] Handle to a GDI bitmap.
hpal
[in] Handle to a GDI palette used to define the bitmap colors if hbm is not a device-independent bitmap (DIB).

Remarks

You are responsible for deleting the GDI bitmap and the GDI palette. However, you should not delete the GDI bitmap or the GDI palette until after the GDI+ Bitmap object is deleted or goes out of scope.

Do not pass to the GDI+ Bitmap constructor a GDI bitmap or a GDI palette that is currently (or was previously) selected into a device context.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Bitmaps, Color Palettes, FromHBITMAP, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::Bitmap(hicon)

Creates a Bitmap object based on an icon.

Bitmap(
  HICON hicon
);

Parameters

hicon
[in] Handle to a GDI icon.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Icons, FromHICON, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::Bitmap(hInstance, bitmapName)

Creates a Bitmap object based on an application or DLL instance handle and the name of a bitmap resource.

Bitmap(
  HINSTANCE hInstance,
  const WCHAR* bitmapName
);

Parameters

hInstance
[in] Handle to an instance of a module whose executable file contains a bitmap resource.
bitmapName
[in] Pointer to a null-terminated string that specifies the path name of the bitmap resource to be loaded. Alternatively, this parameter can consist of the resource identifier in the low-order word and zero in the high-order word. You can use the MAKEINTRESOURCE macro to create this value.

Example Code [C++]

The following example creates a Bitmap object based on an application instance handle and the name of a bitmap resource. Assume that the code is compiled into an executable file that contains a bitmap resource named BitmapResource1. The WinMain function receives the instance handle of the running application and stores that handle in a global variable g_hInstance. The WndProc function (in response to a WM_PAINT message) constructs a Bitmap object based on the handle stored in g_hInstance and the name of the bitmap resource. The call to Graphics::DrawImage draws the bitmap on the screen.

HINSTANCE g_hInstance;

INT WINAPI
WinMain(HINSTANCE hInstance, HINSTANCE, PSTR szCmdLine, INT iCmdShow)
{
   g_hInstance = hInstance;
…
}

LRESULT CALLBACK
WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
   HDC         hdc;
   PAINTSTRUCT ps;
   Graphics*   pGraphics;
   Bitmap*     pBitmap;

   switch(message)
   {
   case WM_PAINT:

      hdc = BeginPaint(hWnd, &ps);
      pGraphics = new Graphics(hdc);

      pBitmap = new Bitmap(g_hInstance, L"BitmapResource1");
      pGraphics->DrawImage(pBitmap, 10, 10);

      delete pBitmap;
      delete pGraphics;
      EndPaint(hWnd, &ps);
      return 0;

   case WM_DESTROY:
      PostQuitMessage(0);
      return 0;

   default:
      return DefWindowProc(hWnd, message, wParam, lParam);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, FromResource, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::Bitmap(stream, useIcm)

Creates a Bitmap object based on a stream.

Bitmap(
  IStream* stream,
  BOOL useIcm
);

Parameters

stream
[in] Pointer to an IStream COM interface.
useIcm
[in] Boolean value that specifies whether the new Bitmap object applies color correction according to color management information that is embedded in the stream. Embedded information can include International Color Consortium (ICC) profiles, gamma values, and chromaticity information. TRUE specifies that color correction is enabled, and FALSE specifies that color correction is not enabled. The default value is FALSE.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, FromStream, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Basic Color Management Concepts, Images, Bitmaps, and Metafiles


Bitmap::Bitmap(surface)

Creates a Bitmap object based on a DirectDraw surface. The Bitmap object maintains a reference to the DirectDraw surface until the Bitmap object is deleted or goes out of scope.

Bitmap(
  IDirectDrawSurface7* surface
);

Parameters

surface
[in] Pointer to an IDrectDrawSurface7 COM interface.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, FromDirectDrawSurface7, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::Bitmap(width, height, format)

Creates a Bitmap object of a specified size and pixel format. The pixel data must be provided after the Bitmap object is constructed.

Bitmap(
  INT width,
  INT height,
  PixelFormat format
);

Parameters

width
[in] Integer that specifies the width, in pixels, of the bitmap.
height
[in] Integer that specifies the height, in pixels, of the bitmap.
format
[in] Optional. Integer that specifies the pixel format of the bitmap. The PixelFormat data type and constants that represent various pixel formats are defined in Gdipluspixelformats.h. For more information about pixel format constants, see Image Pixel Format Constants. The default value is PixelFormat32bppARGB.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Image, Image Pixel Format Constants
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::Bitmap(width, height, stride, format, scan0)

Creates a Bitmap object based on an array of bytes along with size and format information.

Bitmap(
  INT width,
  INT height,
  INT stride,
  PixelFormat format,
  BYTE* scan0
);

Parameters

width
[in] Integer that specifies the width, in pixels, of the bitmap.
height
[in] Integer that specifies the height, in pixels, of the bitmap.
stride
[in] Integer that specifies the byte offset between the beginning of one scan line and the next. This is usually (but not necessarily) the number of bytes in the pixel format (for example, 2 for 16 bits per pixel) multiplied by the width of the bitmap. The value passed to this parameter must be a multiple of four.
format
[in] Integer that specifies the pixel format of the bitmap. The PixelFormat data type and constants that represent various pixel formats are defined in Gdipluspixelformats.h. For more information about pixel format constants, see Image Pixel Format Constants.
scan0
[in] Pointer to an array of bytes that contains the pixel data. The caller is responsible for allocating and freeing the block of memory pointed to by this parameter.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Image, Image Pixel Format Constants
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::Bitmap(width, height, target)

Creates a Bitmap object based on a Graphics object, a width, and a height.

Bitmap(
  INT width,
  INT height,
  Graphics* target
);

Parameters

width
[in] Integer that specifies the width, in pixels, of the bitmap.
height
[in] Integer that specifies the height, in pixels, of the bitmap.
target
[in] Pointer to a Graphics object that contains information used to initialize certain properties (for example, dots per inch) of the new Bitmap object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Graphics, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap Methods

This topic lists the methods of the Bitmap class. For a complete class listing, see Bitmap Class.

  • Clone()
  • Clone(Rect& rect, PixelFormat format)
  • Clone(RectF& rect, PixelFormat format)
  • Clone(INT x, INT y, INT width, INT height, PixelFormat format)
  • Clone(REAL x, REAL y, REAL width, REAL, height, PixelFormat format)
  • FromBITMAPINFO(gdiBitmapInfo, gdiBitmapData)
  • FromDirectDrawSurface7(surface)
  • FromFile(filename, useEmbeddedColorManagement)
  • FromHBITMAP(hbm, hpal)
  • FromHICON(hicon)
  • FromResource(hInstance, bitmapName)
  • FromStream(stream, useEmbeddedColorManagement)
  • GetAllPropertyItems(totalBufferSize, numProperties, allItems)
  • GetBounds(srcRect, srcUnit)
  • GetEncoderParameterList(clsidEncoder, size, buffer)
  • GetEncoderParameterListSize(clsidEncoder)
  • GetFlags()
  • GetFrameCount(dimensionID)
  • GetFrameDimensionsCount()
  • GetFrameDimensionsList(dimensionIDs, count)
  • GetHBITMAP(colorBackground, hbmReturn)
  • GetHeight()
  • GetHICON(hicon)
  • GetHorizontalResolution()
  • GetLastStatus()
  • GetPalette(palette, size)
  • GetPaletteSize()
  • GetPhysicalDimension(size)
  • GetPixel(x, y, color)
  • GetPixelFormat()
  • GetPropertyCount()
  • GetPropertyIdList(numOfProperty, list)
  • GetPropertyItem(propId, propSize, buffer)
  • GetPropertyItemSize(propId)
  • GetPropertySize(totalBufferSize, numProperties)
  • GetRawFormat(format)
  • GetThumbnailImage(thumbWidth, thumbHeight, callback, callbackData)
  • GetType()
  • GetVerticalResolution()
  • GetWidth()
  • LockBits(rect, flags, format, lockedBitmapData)
  • RemovePropertyItem(propId)
  • RotateFlip(rotateFlipType)
  • SelectActiveFrame(dimensionID, frameIndex)
  • SetPalette(palette)
  • SetPixel(x, y, color)
  • SetPropertyItem(item)
  • SetResolution(xdpi, ydpi)
  • UnlockBits(lockedBitmapData)


Bitmap::Clone Methods

This topic lists the Clone methods of the Bitmap class. For a complete list of methods for the Bitmap class, see Bitmap Methods.

  • Clone()
  • Clone(Rect& rect, PixelFormat format)
  • Clone(RectF& rect, PixelFormat format)
  • Clone(INT x, INT y, INT width, INT height, PixelFormat format)
  • Clone(REAL x, REAL y, REAL width, REAL, height, PixelFormat format)


Bitmap::Clone(Rect& rect, PixelFormat format)

The Clone method creates a new Bitmap object by copying a portion of this bitmap.

Bitmap* Clone(
  const Rect& rect,
  PixelFormat format
);

Parameters

rect
[in] Reference to a rectangle that specifies the portion of this bitmap to be copied.
format
[in] Integer that specifies the pixel format of the new bitmap. The PixelFormat data type and constants that represent various pixel formats are defined in Gdipluspixelformats.h. For more information about pixel format constants, see Image Pixel Format Constants.

Return Values

This method returns a pointer to the new Bitmap object.

Example Code [C++]

The following example creates a Bitmap object from an image file, clones the upper-left portion of the image, and then draws the cloned image.

VOID Example_Clone(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Bitmap object from a JPEG file.
   Bitmap bitmap(L"Climber.jpg");

   // Clone a portion of the bitmap.
   Bitmap* clone = bitmap.Clone(Rect(0, 0, 100, 100), PixelFormatDontCare);

   // Draw the clone.
   graphics.DrawImage(clone, 0, 0);

   delete clone;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Clone Methods, Image, Image Pixel Format Constants, Rect
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::Clone(RectF& rect, PixelFormat format)

The Clone method creates a new Bitmap object by copying a portion of this bitmap.

Bitmap* Clone(
  const RectF& rect,
  PixelFormat format
);

Parameters

rect
[in] Reference to a rectangle that specifies the portion of this bitmap to be copied.
format
[in] Integer that specifies the pixel format of the new bitmap. The PixelFormat data type and constants that represent various pixel formats are defined in Gdipluspixelformats.h. For more information about pixel format constants, see Image Pixel Format Constants.

Return Values

This method returns a pointer to the new Bitmap object.

Example Code [C++]

The following example creates a Bitmap object from an image file, clones the upper-left portion of the image, and then draws the cloned image.

VOID Example_Clone2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Bitmap object from an image file.
   Bitmap bitmap(L"Climber.jpg");

   // Clone a portion of the bitmap.
   RectF rect(0.0f, 0.0f, 100.0f, 100.0f);
   Bitmap* clone = bitmap.Clone(rect, PixelFormatDontCare);

   // Draw the clone.
   graphics.DrawImage(clone, 0, 0);

   delete clone;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Clone Methods, Image, Image Pixel Format Constants, RectF
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::Clone(INT x, INT y, INT width, INT height, PixelFormat format)

The Clone method creates a new Bitmap object by copying a portion of this bitmap.

Bitmap* Clone(
  INT x,
  INT y,
  INT width,
  INT height,
  PixelFormat format
);

Parameters

x
[in] Integer that specifies the x-coordinate of the upper-left corner of the rectangle that specifies the portion of this bitmap to copy.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the rectangle that specifies the portion of this bitmap to copy.
width
[in] Integer that specifies the width of the rectangle that specifies the portion of this bitmap to copy.
height
[in] Integer that specifies the height of the rectangle that specifies the portion of this image to copy.
format
[in] Integer that specifies the pixel format of the new bitmap. The PixelFormat data type and constants that represent various pixel formats are defined in Gdipluspixelformats.h. For more information about pixel format constants, see Image Pixel Format Constants.

Return Values

This method returns a pointer to the new Bitmap object.

Example Code [C++]

The following example creates a Bitmap object from an image file, clones the upper-left portion of the image, and then draws the cloned image.

VOID Example_Clone3(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Bitmap object from a JPEG file.
   Bitmap bitmap(L"Climber.jpg");

   // Clone a portion of the bitmap.
   Bitmap* clone = bitmap.Clone(0, 0, 100, 100, PixelFormatDontCare);

   // Draw the clone.
   graphics.DrawImage(clone, 0, 0);

   delete clone;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Clone Methods, Image, Image Pixel Format Constants
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::Clone(REAL x, REAL y, REAL width, REAL height, PixelFormat format)

The Clone method creates a new Bitmap object by copying a portion of this bitmap.

Bitmap* Clone(
  REAL x,
  REAL y,
  REAL width,
  REAL height,
  PixelFormat format
);

Parameters

x
[in] Real number that specifies the x-coordinate of the upper-left corner of the rectangle that specifies the portion of this bitmap to copy.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the rectangle that specifies the portion of this bitmap to copy.
width
[in] Real number that specifies the width of the rectangle that specifies the portion of this bitmap to copy.
height
[in] Real number that specifies the height of the rectangle that specifies the portion of this image to copy.
format
[in] Integer that specifies the pixel format of the new bitmap. The PixelFormat data type and constants that represent various pixel formats are defined in Gdipluspixelformats.h. For more information about pixel format constants, see Image Pixel Format Constants.

Return Values

This method returns a pointer to the new Bitmap object.

Example Code [C++]

The following example creates a Bitmap object from an image file, clones the upper-left portion of the image, and then draws the cloned image.

VOID Example_Clone4(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Bitmap object from a JPEG file.
   Bitmap bitmap(L"Climber.jpg");

   // Clone a portion of the bitmap.
   Bitmap* clone;
   clone = bitmap.Clone(0.0f, 0.0f, 100.0f, 100.0f, PixelFormatDontCare);

   // Draw the clone.
   graphics.DrawImage(clone, 0, 0);

   delete clone;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Clone Methods, Image, Image Pixel Format Constants
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::FromBITMAPINFO(gdiBitmapInfo, gdiBitmapData)

The FromBITMAPINFO method creates a Bitmap object based on a BITMAPINFO structure and an array of pixel data.

static Bitmap* FromBITMAPINFO(
  const BITMAPINFO* gdiBitmapInfo,
  VOID* gdiBitmapData
);

Parameters

gdiBitmapInfo
[in] Pointer to a GDI BITMAPINFO structure. This structure defines several bitmap attributes, such as size and pixel format. The BITMAPINFO structure is defined in Wingdi.h.
gdiBitmapData
[in] Pointer to an array of bytes that contains the pixel data.

Return Values

This method returns a pointer to the new Bitmap object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Bitmaps, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::FromDirectDrawSurface7(surface)

The FromDirectDrawSurface7 method creates a Bitmap object based on a DirectDraw surface. The Bitmap object maintains a reference to the DirectDraw surface until the Bitmap object is deleted.

static Bitmap* FromDirectDrawSurface7(
  IDirectDrawSurface7* surface
);

Parameters

surface
[in] Pointer to an IDirectDrawSurface7 COM interface.

Return Values

This method returns a pointer to the new Bitmap object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::FromFile(filename, useEmbeddedColorManagement)

The FromFile method creates a Bitmap object based on an image file.

static Bitmap* FromFile(
  const WCHAR* filename,
  BOOL useEmbeddedColorManagement
);

Parameters

filename
[in] Pointer to a null-terminated string that specifies the path name of the image file.
useEmbeddedColorManagement
[in] Optional. Boolean value that specifies whether the new Bitmap object applies color correction according to color management information that is embedded in the image file. Embedded information can include International Color Consortium (ICC) profiles, gamma values, and chromaticity information. TRUE specifies that color correction is enabled, and FALSE specifies that color correction is not enabled. The default value is FALSE.

Return Values

This method returns a pointer to the new Bitmap object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Basic Color Management Concepts, Images, Bitmaps, and Metafiles


Bitmap::FromHBITMAP(hbm, hpal)

The FromHBITMAP method creates a Bitmap object based on a handle to a Windows GDI bitmap and a handle to a GDI palette.

static Bitmap* FromHBITMAP(
  HBITMAP hbm,
  HPALETTE hpal
);

Parameters

hbm
[in] Handle to GDI bitmap.
hpal
[in] Handle to a GDI palette used to define the bitmap colors if hbm is not a device-independent bitmap (DIB).

Return Values

This method returns a pointer to the new Bitmap object.

Remarks

You are responsible for deleting the GDI bitmap and the GDI palette. However, you should not delete the GDI bitmap or the GDI palette until after the GDI+ Bitmap object is deleted or goes out of scope.

Do not pass to the FromHBITMAP method a GDI bitmap or a GDI palette that is currently (or was previously) selected into a device context.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Bitmaps, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::FromHICON(hicon)

The FromHICON method creates a Bitmap object based on a handle to an icon.

static Bitmap* FromHICON(
  HICON hicon
);

Parameters

hicon
[in] Handle to a GDI icon.

Return Values

This method returns a pointer to the new Bitmap object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Icons, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::FromResource(hInstance, bitmapName)

The FromResource method creates a Bitmap object based on an application or DLL instance handle and the name of a bitmap resource.

static Bitmap* FromResource(
  HINSTANCE hInstance,
  const WCHAR* bitmapName
);

Parameters

hInstance
[in] Handle to an instance of a module whose executable file contains a bitmap resource.
bitmapName
[in] Pointer to a null-terminated string that specifies the path name of the bitmap resource to be loaded. Alternatively, this parameter can consist of the resource identifier in the low-order word and zero in the high-order word. You can use the MAKEINTRESOURCE macro to create this value.

Return Values

This method returns a pointer to the new Bitmap object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap Constructors, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::FromStream(stream, useEmbeddedColorManagement)

The FromStream method creates a Bitmap object based on a stream.

static Bitmap* FromStream(
  IStream* stream,
  BOOL useEmbeddedColorManagement
);

Parameters

stream
[in] Pointer to an IStream COM interface. The implementation of IStream must include the Seek, Read, and Stat methods.
useEmbeddedColorManagement
[in] Optional. Boolean value that specifies whether the new Bitmap object applies color correction according to color management information that is embedded in the stream. Embedded information can include International Color Consortium (ICC) profiles, gamma values, and chromaticity information. TRUE specifies that color correction is enabled, and FALSE specifies that color correction is not enabled. The default value is FALSE.

Return Values

This method returns a pointer to the new Bitmap object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmaps, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Basic Color Management Concepts, Images, Bitmaps, and Metafiles


Bitmap::GetHBITMAP(colorBackground, hbmReturn)

The GetHBITMAP method creates a Windows GDI bitmap from this Bitmap object.

Status GetHBITMAP(
  const Color& colorBackground,
  HBITMAP* hbmReturn
);

Parameters

colorBackground
[in] Reference to a Color object that specifies the background color. This parameter is ignored if the bitmap is totally opaque.
hbmReturn
[out] Pointer to an HBITMAP that receives a handle to the GDI bitmap.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmaps, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::GetHICON(hicon)

The GetHICON method creates an icon from this Bitmap object.

Status GetHICON(
  HICON* hicon
);

Parameters

hicon
[out] Pointer to an HICON that receives a handle to the icon.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Icons, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::GetPixel(x, y, color)

The GetPixel method gets the color of a specified pixel in this bitmap.

Status GetPixel(
  INT x,
  INT y,
  Color* color
);

Parameters

x
[in] Integer that specifies the x-coordinate (column) of the pixel.
y
[in] Integer that specifies the y-coordinate (row) of the pixel.
color
[out] Pointer to a Color object that receives the color of the specified pixel.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Depending on the format of the bitmap, GetPixel might not return the same value as was set by SetPixel. For example, if you call SetPixel on a Bitmap object whose pixel format is 32bppPARGB, the pixel's RGB components are premultiplied. A subsequent call to GetPixel might return a different value because of rounding. Also, if you call SetPixel on a Bitmap object whose color depth is 16 bits per pixel, information could be lost during the conversion from 32 to 16 bits, and a subsequent call to GetPixel might return a different value.

Example Code [C++]

The following example creates a Bitmap object based on a JPEG file. The code calls the GetPixel method to obtain the color of a pixel in the bitmap and then fills a rectangle with the retrieved color.

VOID Example_GetPixel(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Bitmap object from a JPEG file.
   Bitmap myBitmap(L"Climber.jpg");

   // Get the value of a pixel from myBitmap.
   Color pixelColor;
   myBitmap.GetPixel(25, 25, &pixelColor);

   // Fill a rectangle with the pixel color.
   SolidBrush brush(pixelColor);
   graphics.FillRectangle(&brush, Rect(0, 0, 100, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Color, Image, LockBits, SetPixel
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::LockBits(rect, flags, format, lockedBitmapData)

The LockBits method locks a rectangular portion of this bitmap and provides a temporary buffer that you can use to read or write pixel data in a specified format. Any pixel data that you write to the buffer is copied to the Bitmap object when you call UnlockBits.

Status LockBits(
  const Rect* rect,
  UINT flags,
  PixelFormat format,
  BitmapData* lockedBitmapData
);

Parameters

rect
[in] Pointer to a rectangle that specifies the portion of the bitmap to be locked.
flags
[in] Set of flags that specify whether the locked portion of the bitmap is available for reading or for writing and whether the caller has already allocated a buffer. Individual flags are defined in the ImageLockMode enumeration.
format
[in] Integer that specifies the format of the pixel data in the temporary buffer. The pixel format of the temporary buffer does not have to be the same as the pixel format of this Bitmap object. The PixelFormat data type and constants that represent various pixel formats are defined in Gdipluspixelformats.h. For more information about pixel format constants, see Image Pixel Format Constants.

GDI+ version 1.0 does not support processing of 16-bits-per-channel images, so you should not set this parameter equal to PixelFormat48bppRGB, PixelFormat64bppARGB, or PixelFormat64bppPARGB.

lockedBitmapData
[in, out] Pointer to a BitmapData object. If the ImageLockModeUserInputBuf flag of the flags parameter is cleared, then lockedBitmapData serves only as an output parameter. In that case, the Scan0 data member of the BitmapData object receives a pointer to a temporary buffer, which is filled with the values of the requested pixels. The other data members of the BitmapData object receive attributes (width, height, format, and stride) of the pixel data in the temporary buffer. If the pixel data is stored bottom-up, the Stride data member is negative. If the pixel data is stored top-down, the Stride data member is positive.

If the ImageLockModeUserInputBuf flag of the flags parameter is set, then lockedBitmapData serves as an input parameter (and possibly as an output parameter). In that case, the caller must allocate a buffer for the pixel data that will be read or written. The caller also must create a BitmapData object, set the Scan0 data member of that BitmapData object to the address of the buffer, and set the other data members of the BitmapData object to specify the attributes (width, height, format, and stride) of the buffer.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following examples show three ways to use the LockBits method. The first example shows how to lock a portion of a bitmap for reading. The second example shows how to lock a portion of a bitmap and then write pixel data to a buffer that is allocated by the LockBits method. The third example shows how to write to a locked bitmap from a buffer that you allocate ahead of time.

  • Locking Pixel Data for Reading
  • Locking Pixel Data for Writing
  • Locking Pixel Data for Writing from a User Input Buffer

Locking Pixel Data for Reading

The following console application creates a Bitmap object based on a BMP file. The call to the LockBits method locks a 5×3 rectangular portion of the bitmap for reading. The locked portion starts at (20, 30); that is, row 30, column 20. One of the arguments passed to LockBits is the address of a BitmapData object. When LockBits returns, the Scan0 data member of the BitmapData object points to a block of memory that holds the values of the pixels in the 5×3 portion of the bitmap. The Stride data member of the BitmapData object holds the byte offset between one scan line and the next scan line in that block of memory.

The nested loops display the hexadecimal values of the fifteen retrieved pixels. Note that pixels is a pointer to a UINT, so the code must calculate the number of UINTs that fit in a scan line. Because each UINT is four bytes, that number is the stride divided by 4.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Bitmap* bitmap = new Bitmap(L"LockBitsTest1.bmp");
   BitmapData* bitmapData = new BitmapData;
   Rect rect(20, 30, 5, 3);

   // Lock a 5×3 rectangular portion of the bitmap for reading.
   bitmap->LockBits(
      &rect,
      ImageLockModeRead,
      PixelFormat32bppARGB,
      bitmapData);

   printf("The stride is %d.\n\n", bitmapData->Stride);

   // Display the hexadecimal value of each pixel in the 5×3 rectangle.
   UINT* pixels = (UINT*)bitmapData->Scan0;

   for(UINT row = 0; row < 3; ++row)
   {
      for(UINT col = 0; col < 5; ++col)
      {
         printf("%x\n", pixels[row * bitmapData->Stride / 4 + col]);
      }
      printf("----------\n");
   }

   bitmap->UnlockBits(bitmapData);

   delete bitmapData;
   delete bitmap;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, LockBitsTest1.bmp, produced the following output:

The stride is 120.

ffff0000
ffffffff
ffff0000
ffffffff
ffff0000
----------
ff00ff00
ffffffff
ff00ff00
ffffffff
ff00ff00
----------
ff0000ff
ffffffff
ff0000ff
ffffffff
ff0000ff
----------

Locking Pixel Data for Writing

The following example creates a Bitmap object based on a BMP file. The call to the LockBits method locks a 50×30 rectangular portion of the bitmap for writing. The locked portion starts at (20, 10); that is, row 10, column 20. One of the arguments passed to LockBits is the address of a BitmapData object. When LockBits returns, the Scan0 data member of the BitmapData object points to a block of memory that represents the pixels in the 50×30 portion of the bitmap. The Stride data member of the BitmapData object holds the byte offset between one scan line and the next scan line in that block of memory.

Scan0 does not point to the actual pixel data of the Bitmap object; rather, it points to a temporary buffer that represents a portion of the pixel data in the Bitmap object. The code writes the value 0xff00ff00 (green) to 1500 locations in the temporary buffer. Later, the call to UnlockBits copies those values to the Bitmap object itself.

Note that pixels is a pointer to a UINT, so the code must calculate the number of UINTs that fit in a scan line. Because each UINT is four bytes, that number is the stride divided by 4.

VOID Example_LockBits2(HDC hdc)
{
   Graphics graphics(hdc);
   UINT* pixels;

   // Create a Bitmap object from a BMP file.
   Bitmap bitmap(L"LockBitsTest2.bmp");

   // Display the bitmap before locking and altering it.
   graphics.DrawImage(&bitmap, 10, 10);

   // Lock a 50×30 rectangular portion of the bitmap for writing.
   BitmapData bitmapData;
   Rect rect(20, 10, 50, 30);

   bitmap.LockBits(
      &rect,
      ImageLockModeWrite,
      PixelFormat32bppARGB,
      &bitmapData);

   // Write to the temporary buffer provided by LockBits.
   pixels = (UINT*)bitmapData.Scan0;

   for(UINT row = 0; row < 30; ++row)
   {
      for(UINT col = 0; col < 50; ++col)
      {
         pixels[row * bitmapData.Stride / 4 + col] = 0xff00ff00;
      }
   }

   // Commit the changes, and unlock the 50×30 portion of the bitmap.
   bitmap.UnlockBits(&bitmapData);

   // Display the altered bitmap.
   graphics.DrawImage(&bitmap, 150, 10);
}

The preceding code, along with a particular file, LockBitsTest2.bmp, produced the following output.

Locking Pixel Data for Writing from a User Input Buffer

The following example creates a Bitmap object based on a BMP file. The call to the LockBits method locks a 50×30 rectangular portion of the bitmap for writing. The locked portion starts at (20, 10); that is, row 10, column 20. The ImageLockModeUserInputBuf flag of the flags parameter is set, so lockedBitmapData serves as an input parameter.

Before calling LockBits, the code allocates a buffer and fills that buffer with the pixel data (in this case, all aqua pixels) that will later be written to the Bitmap object. The code creates a BitmapData object and sets its Scan0 data member to the address of the pixel data buffer. The code also initializes the other data members of the BitmapData object with the attributes (width, height, format, and stride) of the pixel data buffer.

The code passes the address of the initialized BitmapData object to the LockBits method. The subsequent call to UnlockBits copies the pixel data in the buffer to the Bitmap object.

Note that each scan line in the pixels array has 50 UINTs, but the code must set the stride to the number of bytes in each scan line. Because each UINT is four bytes, that number is the width (50) multiplied by 4.

VOID Example_LockBits3(HDC hdc)
{
   Graphics graphics(hdc);
   INT row, col;

   // Create and fill a pixel data buffer.
   UINT pixels[30][50];
   for(row = 0; row < 30; ++row)
      for(col = 0; col < 50; ++col)
         pixels[row][col] = 0xff00ffff;  // aqua

   BitmapData bitmapData;
   bitmapData.Width = 50,
   bitmapData.Height = 30,
   bitmapData.Stride = 4*bitmapData.Width;
   bitmapData.PixelFormat = PixelFormat32bppARGB;
   bitmapData.Scan0 = (VOID*)pixels;
   bitmapData.Reserved = NULL;

   // Create a Bitmap object from a BMP file.
   Bitmap bitmap(L"LockBitsTest2.bmp");

   // Display the bitmap before locking and altering it.
   graphics.DrawImage(&bitmap, 10, 10);

   // Lock a 50×30 rectangular portion of the bitmap for writing.
   Rect rect(20, 10, 50, 30);

   bitmap.LockBits(
      &rect,
      ImageLockModeWrite|ImageLockModeUserInputBuf,
      PixelFormat32bppARGB,
      &bitmapData);

   // Commit the changes and unlock the 50×30 portion of the bitmap.
   bitmap.UnlockBits(&bitmapData);

   // Display the altered bitmap.
   graphics.DrawImage(&bitmap, 150, 10);
}

The preceding code, along with a particular file, LockBitsTest2.bmp, produced the following output.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
BitmapData, Image, ImageLockMode, Image Pixel Format Constants, UnlockBits
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::SetPixel(x, y, color)

The SetPixel method sets the color of a specified pixel in this bitmap.

Status SetPixel(
  INT x,
  INT y,
  const Color& color
);

Parameters

x
[in] Integer that specifies the x-coordinate (column) of the pixel.
y
[in] Integer that specifies the y-coordinate (row) of the pixel.
color
[in] Reference to a Color object that specifies the color to set.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Depending on the format of the bitmap, GetPixel might not return the same value as was set by SetPixel. For example, if you call SetPixel on a Bitmap object whose pixel format is 32bppPARGB, the RGB components are premultiplied. A subsequent call to GetPixel might return a different value because of rounding. Also, if you call SetPixel on a Bitmap whose color depth is 16 bits per pixel, information could be lost in the conversion from 32 to 16 bits, and a subsequent call to GetPixel might return a different value.

Example Code [C++]

The following example creates a Bitmap object based on a JPEG file. The code draws the bitmap once unaltered. Then the code calls the SetPixel method to create a checkered pattern of black pixels in the bitmap and draws the altered bitmap.

VOID Example_SetPixel(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Bitmap object from a JPEG file.
   Bitmap myBitmap(L"Climber.jpg");

   // Draw the bitmap.
   graphics.DrawImage(&myBitmap, 0, 0);

   // Create a checkered pattern with black pixels.
   for (UINT row = 0; row < myBitmap.GetWidth(); row += 2)
   {
      for (UINT col = 0; col < myBitmap.GetHeight(); col += 2)
      {
         myBitmap.SetPixel(row, col, Color(255, 0, 0, 0));
      }
   }

   // Draw the altered bitmap.
   graphics.DrawImage(&myBitmap, 200, 0);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Color, GetPixel, Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::SetResolution(xdpi, ydpi)

The SetResolution method sets the resolution of this Bitmap object.

Status SetResolution(
  REAL xdpi,
  REAL ydpi
);

Parameters

xdpi
[in] Real number that specifies the horizontal resolution in dots per inch.
ydpi
[in] Real number that specifies the vertical resolution in dots per inch.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Image
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Bitmap::UnlockBits(lockedBitmapData)

The UnlockBits method unlocks a portion of this bitmap that was previously locked by a call to LockBits.

Status UnlockBits(
  BitmapData* lockedBitmapData
);

Parameters

lockedBitmapData
[in] Pointer to a BitmapData object that was previously passed to LockBits.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

LockBits and UnlockBits must be used as a pair. A call to the LockBits method of a Bitmap object establishes a temporary buffer that you can use to read or write pixel data in a specified format. After you write to the temporary buffer, a call to UnlockBits copies the pixel data in the buffer to the Bitmap object. If the pixel format of the temporary buffer is different from the pixel format of the Bitmap object, the pixel data is converted appropriately.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Image, LockBits, Image Pixel Format Constants
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


BitmapData Class

The BitmapData class is used by the LockBits and UnlockBits methods of the Bitmap class. A BitmapData object stores attributes of a bitmap.

Data Members

The following table lists the data members of the BitmapData class in the order that they are defined in the header file.

Data members | Description
Width | UINT. Number of pixels in one scan line of the bitmap.
Height | UINT. Number of scan lines in the bitmap.
Stride | INT. Offset, in bytes, between consecutive scan lines of the bitmap. If the stride is positive, the bitmap is top-down. If the stride is negative, the bitmap is bottom-up.
PixelFormat | PixelFormat. Integer that specifies the pixel format of the bitmap.
Scan0 | Void*. Pointer to the first (index 0) scan line of the bitmap.
Reserved | UINT_PTR. Reserved for future use.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimaging.h; include Gdiplus.h.


Brush Class

The Brush class is an abstract base class that defines a Brush object. A Brush object is used to paint the interior of graphics shapes, such as rectangles, ellipses, pies, polygons, and paths.

Inheritance

GdiplusBase
Brush

Methods

Method | Description
Clone | Creates a new Brush object based on this brush.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetType | Gets the type of this brush.
~Brush | Brush object destructor.


Brush Methods

This topic lists the methods of the Brush class. For a complete class listing, see Brush Class.

  • Clone()
  • GetLastStatus()
  • GetType()


Brush::Clone()

The Clone method creates a new Brush object based on this brush.

virtual Brush* Clone(void) const;

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new Brush object.

Example Code [C++]

The following example creates a SolidBrush object, clones it, and then uses the clone to fill a rectangle.

VOID Example_Clone(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   // Create a copy of solidBrush.
   Brush *cloneBrush = solidBrush.Clone();

   // Use cloneBrush to fill a rectangle.
   graphics.FillRectangle(cloneBrush, Rect(0, 0, 100, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
HatchBrush, LinearGradientBrush, PathGradientBrush, SolidBrush, TextureBrush
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


Brush::GetLastStatus()

The GetLastStatus method returns a value that indicates the nature of this Brush object's most recent method failure.

Status GetLastStatus(void) const;

Parameters

This method has no parameters.

Return Values

The GetLastStatus method returns an element of the Status enumeration.

If no methods invoked on this Brush object have failed since the previous call to GetLastStatus, then GetLastStatus returns Ok.

If at least one method invoked on this Brush object has failed since the previous call to GetLastStatus, then GetLastStatus returns a value that indicates the nature of the most recent failure.

Remarks

You can call GetLastStatus immediately after constructing a Brush object to determine whether the constructor succeeded.

The first time you call the GetLastStatus method of a Brush object, it returns Ok if the constructor succeeded and all methods invoked so far on the Brush object succeeded. Otherwise, it returns a value that indicates the nature of the most recent failure.

Example Code [C++]

The following example creates a SolidBrush object solidBrush and checks the status of the call used to create solidBrush. Then, if the call was successful, the code uses solidBrush to fill a rectangle.

VOID Example_GetLastStatus(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush solidBrush(Color(255, 0, 255, 0));

   // Get the status of the last call.
   Status lastStatus = solidBrush.GetLastStatus();

   //If the call to create myBrush was successful, use it to fill a rectangle.
   if (lastStatus == Ok)
       graphics.FillRectangle(&solidBrush, Rect(0, 0, 100, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
HatchBrush, LinearGradientBrush, PathGradientBrush, SolidBrush, TextureBrush
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


Brush::GetType()

The GetType method gets the type of this brush.

BrushType GetType(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the type of this brush. The value returned is one of the elements of the BrushType enumeration.

Example Code [C++]

The following example creates a SolidBrush object, checks the type of the object, and then, if the type is BrushTypeSolidColor, uses the brush to fill a rectangle.

VOID Example_GetType(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush solidBrush(Color(255, 0, 0, 255));

   // Get the type of solidBrush.
   BrushType type = solidBrush.GetType();

   //If the type of solidBrush is BrushTypeSolidColor, use it to fill a rectangle.
   if (type == BrushTypeSolidColor)
       graphics.FillRectangle(&solidBrush, Rect(0, 0, 100, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
HatchBrush, LinearGradientBrush, PathGradientBrush, SolidBrush, TextureBrush
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


CachedBitmap Class

A CachedBitmap object stores a bitmap in a format that is optimized for display on a particular device. To display a cached bitmap, call the Graphics::DrawCachedBitmap method.

Inheritance

GdiplusBase
CachedBitmap

Constructors

Constructor | Description
CachedBitmap | Creates and initializes a new CachedBitmap object.

Methods

Method | Description
GetLastStatus | Gets a value that indicates whether this CachedBitmap object was constructed successfully.
~CachedBitmap | CachedBitmap object destructor.


CachedBitmap::CachedBitmap(bitmap, graphics)

Creates a CachedBitmap object based on a Bitmap object and a Graphics object. The cached bitmap takes the pixel data from the Bitmap object and stores it in a format that is optimized for the display device associated with the Graphics object.

CachedBitmap(
  Bitmap* bitmap,
  Graphics* graphics
);

Parameters

bitmap
[in] Pointer to a Bitmap object that contains the pixel data to be optimized.
graphics
[in] Pointer to a Graphics object that is associated with a display device for which the image will be optimized.

Remarks

You can display a cached bitmap by passing the address of a CachedBitmap object to the DrawCachedBitmap method of a Graphics object. Use the Graphics object that was passed to the CachedBitmap constructor or another Graphics object that represents the same device.

Example Code [C++]

The following example creates a CachedBitmap object based on a Bitmap object and a Graphics object. The code calls the DrawCachedBitmap method of that Graphics object to display the cached bitmap.

VOID Example_CachedBitmap(HDC hdc)
{
   Graphics graphics(hdc);
   Bitmap bitmap(L"Grapes.jpg");
   CachedBitmap cachedBitmap(&bitmap, &graphics);

   graphics.DrawCachedBitmap(&cachedBitmap, 10, 10);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, Graphics, Image
Tasks and Examples
Using a Cached Bitmap to Improve Performance


CachedBitmap::GetLastStatus()

The GetLastStatus method returns a value that indicates whether this CachedBitmap object was constructed successfully.

Status GetLastStatus(void);

Parameters

This method has no parameters.

Return Values

If this CachedBitmap object was constructed successfully, the GetLastSatus method returns Ok, which is an element of the Status enumeration.

If this CachedBitmap object was not constructed successfully, the GetLastStatus method returns an element of the Status enumeration that indicates the nature of the failure.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, Graphics, Image
Tasks and Examples
Using a Cached Bitmap to Improve Performance


CharacterRange Class

A CharacterRange object specifies a range of character positions within a string.

Data Members

Data member | Description
First | INT. Specifies the first position of this range.
Length | INT. Specifies the number of positions in this range.

Constructors

Constructor | Description
CharacterRange | Overloaded. Creates and initializes a new instance of the CharacterRange class.

Methods

Method | Description
operator= | Sets this CharacterRange object equal to the specified CharacterRange object.
~CharacterRange | CharacterRange object destructor.

Remarks

A character range is a range of character positions within a string of text. The area of the display that is occupied by a group of characters that are specified by the character range is the bounding region. A character range is set by StringFormat::SetMeasurableCharacterRanges. The number of ranges that are currently set can be determined by calling StringFormat::GetMeasurableCharacterRangeCount. This number is also the number of regions expected to be obtained by the MeasureCharacterRanges method.


CharacterRange Constructors

This topic lists the constructors of the CharacterRange class. For a complete class listing, see CharacterRange Class.

  • CharacterRange()
  • CharacterRange(first, length)


CharacterRange::CharacterRange()

Creates a CharacterRange object with the data members set to zero.

CharacterRange(void);

Parameters

This method has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetMeasurableCharacterRangeCount, SetMeasurableCharacterRanges, MeasureCharacterRanges


CharacterRange::CharacterRange(first, length)

Creates a CharacterRange object and initializes the data members to the values specified.

CharacterRange(
  INT first,
  INT length
);

Parameters

first
[in] Integer that specifies the first position of this range. For example, if first is set to 0, then the first position of this range is position 0 in the string.
length
[in] Integer that specifies the number of positions in this range.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetMeasurableCharacterRangeCount, SetMeasurableCharacterRanges, MeasureCharacterRanges


CharacterRange::operator=(rhs)

The operator= method sets this CharacterRange object equal to the specified CharacterRange object.

CharacterRange& operator=(
  const CharacterRange& rhs,
);

Parameters

rhs
[in] Reference to a CharacterRange object that is assigned to this CharacterRange object.

Return Values

This method returns a reference to this CharacterRange object to allow cascaded assignments.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetMeasurableCharacterRangeCount, SetMeasurableCharacterRanges, MeasureCharacterRanges


Color Class

A Color object stores a 32-bit value that represents a color. The color value contains four, 8-bit components: alpha, red, green, and blue. The first 8 bits (the most significant) contain the alpha component, the next 8 bits contain the red component, the next 8 bits contain the green component, and the next 8 bits (the least significant) contain the blue component. The 32-bit value is stored in a variable of type ARGB.

Enumeration Elements

Black
Silver
Gray
White
Maroon
Red
Purple
Fuchsia
Green
Lime
Olive
Yellow
Navy
Blue
Teal
Aqua

Constructors

Constructor | Description
Color | Overloaded. Creates and initializes a new Color object.

Methods

Method | Description
GetA | Gets the alpha component.
GetAlpha | Gets the alpha component.
GetB | Gets the blue component.
GetBlue | Gets the blue component.
GetG | Gets the green component.
GetGreen | Gets the green component.
GetR | Gets the red component.
GetRed | Gets the red component.
GetValue | Gets the ARGB value.
MakeARGB | Makes an ARGB value from specified alpha, red, green, and blue components.
SetFromCOLORREF | Sets the color of this Color object by using a GDI COLORREF value.
SetValue | Sets the color of this Color object by using an ARGB value.
ToCOLORREF | Converts the color of this Color object to a GDI COLORREF value.

Remarks

The alpha component, the most significant 8 bits, specifies the transparency of a color. All four component values range from 0 to 255. An alpha component value of 0 specifies that the color is transparent, and an alpha value of 255 specifies that the color is opaque. Alpha component values from 1 through 254 specify the degree to which the color is blended with the background when the color is rendered. The red, green, and blue color component values range from 0 to 255 and determine the intensity of the color. The MakeARGB method is used to encapsulate the four color components into a single 32-bit value.


Color Constructors

This topic lists the constructors of the Color class. For a complete class listing, see Color Class.

  • Color()
  • Color(a, r, g, b)
  • Color(argb)
  • Color(r, g, b)


Color::Color()

Creates a Color object and initializes it to opaque black. This is the default constructor.

Color(void);

Parameters

This method has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
Color Constructors


Color::Color(a, r, g, b)

Creates a Color object by using specified values for the alpha, red, green, and blue components.

Color(
  BYTE a,
  BYTE r,
  BYTE g,
  BYTE b
);

Parameters

a
[in] Byte that specifies the alpha component.
r
[in] Byte that specifies the red component.
g
[in] Byte that specifies the green component.
b
[in] Byte that specifies the blue component.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
Color Constructors


Color::Color(argb)

Creates a Color object by using an ARGB value.

Color(
  ARGB argb
);

Parameters

argb
[in] Value that specifies the alpha, red, green, and blue color components.

Remarks

An ARGB value is a DWORD that contains the alpha, red, green, and blue components of a color. ARGB is defined in Gdipluspixelformats.h.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
Color Constructors, MakeARGB


Color::Color(r, g, b)

Creates a Color object by using specified values for the red, green, and blue components. This constructor sets the alpha component to 255 (opaque).

Color(
  BYTE r,
  BYTE g,
  BYTE b
);

Parameters

r
[in] Byte that specifies the red component.
g
[in] Byte that specifies the green component.
b
[in] Byte that specifies the blue component.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
Color Constructors


Color Methods

This topic lists the methods of the Color class. For a complete class listing, see Color Class.

  • GetA
  • GetAlpha
  • GetB
  • GetBlue
  • GetG
  • GetGreen
  • GetR
  • GetRed
  • GetValue
  • MakeARGB
  • SetFromCOLORREF
  • SetValue
  • ToCOLORREF


Color::GetA()

The GetA method gets the alpha component of this Color object.

BYTE GetA(void);

Parameters

This method has no parameters.

Return Values

This method returns the alpha component of this color.

Example Code [C++]

The following example creates a Color object, gets the alpha component of the color, and creates a second Color object that uses the same alpha component. It then fills a rectangle by using a Brush object based on the second color.

VOID Example_GetA(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Color object with an alpha value of 128.
   Color firstColor(128, 255, 0, 0);

   // Get the alpha value of firstColor.
   char alpha = firstColor.GetA();

   // Create a second Color object with an alpha value taken from firstColor.
   Color secondColor(alpha, 0, 0, 255);

   // Create a pen using secondColor and use it to draw a line.
   Pen pen((secondColor), 20);
   graphics.DrawLine(&pen, 50, 50, 200, 50);

}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
GetAlpha, GetB, GetBlue, GetG, GetGreen, GetR, GetRed, GetValue


Color::GetAlpha()

The GetAlpha method gets the alpha component of this Color object.

BYTE GetAlpha(void);

Parameters

This method has no parameters.

Return Values

This method returns the alpha component of this color.

Example Code [C++]

The following example creates a Color object, gets the alpha component of the color, and creates a second Color object that uses the same alpha component. It then fills a rectangle by using a Brush object based on the second color.

VOID Example_GetAlpha(HDC hdc)
{

   Graphics graphics(hdc);

   // Create a Color object with an alpha component value of 128.
   Color firstColor(128, 255, 0, 0);

   // Get the alpha value of firstColor.
   int alpha = firstColor.GetAlpha();

   // Create a new Color object with the same alpha component value as firstColor.
   Color secondColor(alpha, 0, 0, 255);

   // Create a SolidBrush object with secondColor, and use it to fill a rectangle.
   SolidBrush alphaBrush(secondColor);
   graphics.FillRectangle(&alphaBrush, Rect(0, 0, 100, 100));

}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
GetAlpha, GetB, GetBlue, GetG, GetGreen, GetR, GetRed, GetValue


Color::GetB()

The GetB method gets the blue component of this Color object.

BYTE GetB(void);

Parameters

This method has no parameters.

Return Values

This method returns the blue component of this color.

Example Code [C++]

The following example creates a Color object, gets the blue component of the color, and creates a second Color object that uses the same blue component. It then fills a rectangle by using a Brush object based on the second color.

VOID Example_GetB(HDC hdc)
{

   Graphics graphics(hdc);

   // Create a Color object with a blue component value of 255.
   Color firstColor(0, 255, 255, 255);

   // Get the blue component value of firstColor.
   int blue = firstColor.GetB();

   // Create a new Color object with the same blue component value as firstColor.
   Color secondColor(255, 0, 0, blue);

   // Create a SolidBrush object with secondColor, and use it to fill a rectangle.
   SolidBrush blueBrush(secondColor);
   graphics.FillRectangle(&blueBrush, Rect(0, 0, 100, 100));

}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
GetAlpha, GetB, GetBlue, GetG, GetGreen, GetR, GetRed, GetValue


Color::GetBlue()

The GetBlue method gets the blue component of this Color object.

BYTE GetBlue(void);

Parameters

This method has no parameters.

Return Values

This method returns the blue component of this color.

Example Code [C++]

The following example creates a Color object, gets the blue component of the color, and creates a second Color object that uses the same blue component. It then fills a rectangle by using a Brush object based on the second color.

VOID Example_GetBlue(HDC hdc)
{

   Graphics graphics(hdc);

   // Create a Color object with a blue component value of 255.
   Color firstColor(0, 255, 255, 255);

   // Get the blue component value of firstColor.
   int blue = firstColor.GetBlue();

   // Create a new Color object with the same blue component value as firstColor.
   Color secondColor(255, 0, 0, blue);

   // Create a SolidBrush object with secondColor, and use it to fill a rectangle.
   SolidBrush blueBrush(secondColor);
   graphics.FillRectangle(&blueBrush, Rect(0, 0, 100, 100));

}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
GetAlpha, GetB, GetBlue, GetG, GetGreen, GetR, GetRed, GetValue


Color::GetG()

The GetG method gets the green component of this Color object.

BYTE GetG(void);

Parameters

This method has no parameters.

Return Values

This method returns the green component of this color.

Example Code [C++]

The following example creates a Color object, gets the green component of the color, and creates a second Color object that uses the same green component. It then fills a rectangle by using a Brush object based on the second color.

VOID Example_GetG(HDC hdc)
{

   Graphics graphics(hdc);

   // Create a Color object with a blue component value of 255.
   Color firstColor(0, 255, 255, 255);

   // Get the blue component value of firstColor.
   int green = firstColor.GetG();

   // Create a new Color object with the same blue component value as firstColor.
   Color secondColor(255, 0, green, 0);

   // Create a SolidBrush object with secondColor, and use it to fill a rectangle.
   SolidBrush greenBrush(secondColor);
   graphics.FillRectangle(&greenBrush, Rect(0, 0, 100, 100));

}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
GetAlpha, GetB, GetBlue, GetG, GetGreen, GetR, GetRed, GetValue


Color::GetGreen()

The GetGreen method gets the green component of this Color object.

BYTE GetGreen(void);

Parameters

This method has no parameters.

Return Values

This method returns the green component of this color.

Example Code [C++]

The following example creates a Color object, gets the green component of the color, and creates a second Color object that uses the same green component. It then fills a rectangle by using a Brush object based on the second color.

VOID Example_GetGreen(HDC hdc)
{

   Graphics graphics(hdc);

   // Create a Color object with a green component value of 255.
   Color firstColor(0, 255, 255, 255);

   // Get the green component value of firstColor.
   int green = firstColor.GetGreen();

   // Create a new Color object with the same green component value as firstColor.
   Color secondColor(255, 0, green, 0);

   // Create a SolidBrush object with secondColor, and use it to fill a rectangle.
   SolidBrush greenBrush(secondColor);
   graphics.FillRectangle(&greenBrush, Rect(0, 0, 100, 100));

}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
GetAlpha, GetB, GetBlue, GetG, GetGreen, GetR, GetRed, GetValue


Color::GetR()

The GetR method gets the red component of this Color object.

BYTE GetR(void);

Parameters

This method has no parameters.

Return Values

This method returns the red component of this color.

Example Code [C++]

The following example creates a Color object, gets the red component of the color, and creates a second Color object that uses the same red component. It then fills a rectangle by using a Brush object based on the second color.

VOID Example_GetR(HDC hdc)
{

   Graphics graphics(hdc);

   // Create a Color object with a red component value of 255.
   Color firstColor(0, 255, 255, 255);

   // Get the red component value of firstColor.
   int red = firstColor.GetR();

   // Create a new Color object with the same red component value as firstColor.
   Color secondColor(255, red, 0, 0);

   // Create a SolidBrush object with secondColor, and use it to fill a rectangle.
   SolidBrush redBrush(secondColor);
   graphics.FillRectangle(&redBrush, Rect(0, 0, 100, 100));

}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
GetAlpha, GetB, GetBlue, GetG, GetGreen, GetR, GetRed, GetValue


Color::GetRed()

The GetRed method gets the red component of this Color object.

BYTE GetRed(void);

Parameters

This method has no parameters.

Return Values

This method returns the red component of this color.

Example Code [C++]

The following example creates a Color object, gets the red component of the color, and creates a second Color object that uses the same red component. It then fills a rectangle by using a Brush object based on the second color.

VOID Example_GetRed(HDC hdc)
{

   Graphics graphics(hdc);

   // Create a Color object with a red component value of 255.
   Color firstColor(0, 255, 255, 255);

   // Get the red component value of firstColor.
   int red = firstColor.GetRed();

   // Create a new Color object with the same red component value as firstColor.
   Color secondColor(255, red, 0, 0);

   // Create a SolidBrush object with secondColor, and use it to fill a rectangle.
   SolidBrush redBrush(secondColor);
   graphics.FillRectangle(&redBrush, Rect(0, 0, 100, 100));

}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
GetR, GetValue


Color::GetValue()

The GetValue method gets the ARGB value of this Color object.

ARGB GetValue(void);

Parameters

This method has no parameters.

Return Values

This method returns a 32-bit ARGB value that holds the alpha, red, green, and blue components of this color. ARGB is defined in Gdipluspixelformats.h.

Example Code [C++]

The following example creates a Color object, gets an ARGB value that represents the color, and creates a second Color object that uses the same ARGB value. It then fills a rectangle by using a Brush object based on the second color.

VOID Example_GetValue(HDC hdc)
{

   Graphics graphics(hdc);

   // Create a Color object that initializes the ARGB value.
   Color firstColor(255, 128, 128, 255);

   // Get the ARGB value of firstColor.
   ARGB argb = firstColor.GetValue();

   // Create a new Color object with the same ARGB value as firstColor.
   Color secondColor(argb);

   // Create a SolidBrush object with secondColor, and use it to fill a rectangle.
   SolidBrush argbBrush(secondColor);
   graphics.FillRectangle(&argbBrush, Rect(0, 0, 100, 100));

}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
MakeARGB


Color::MakeARGB(a, r, g, b)

The MakeARGB method creates a 32-bit value that consolidates the specified alpha, red, green, and blue components.

static ARGB MakeARGB(
  BYTE a,
  BYTE r,
  BYTE g,
  BYTE b
);

Parameters

a
[in] Byte that specifies the alpha component.
r
[in] Byte that specifies the red component.
g
[in] Byte that specifies the green component.
b
[in] Byte that specifies the blue component.

Return Values

This method returns an ARGB value that holds the specified alpha, red, green, and blue components.

Example Code [C++]

The following example creates an ARGB value from four BYTE values and then creates a Color object based on that ARGB value. Then the code uses the Color object to fill a rectangle.

VOID Example_MakeARGB(HDC hdc)
{

   Graphics graphics(hdc);

   // Declare and initialize color component values as BYTE types.
   BYTE a = 0xFF;
   BYTE r = 0x80;
   BYTE g = 0x80;
   BYTE b = 0xFF;

   // Create an ARGB value from the four component values.
   ARGB argb = Color::MakeARGB(a, r, g, b);

   // Create a Color object from the ARGB value.
   Color argbColor(argb);

   // Create a SolidBrush object with argbColor, and use it to fill a rectangle.
   SolidBrush argbBrush(argbColor);
   graphics.FillRectangle(&argbBrush, Rect(0, 0, 100, 100));

}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
GetValue, SetFromCOLORREF


Color::SetFromCOLORREF(rgb)

The SetFromCOLORREF method uses a GDI COLORREF value to set the ARGB value of this Color object.

VOID SetFromCOLORREF(
  COLORREF rgb
);

Parameters

rgb
[in] GDI COLORREF value that specifies the red, green, and blue components of this Color object's ARGB value. The default value of the alpha component for this Color object is 255.

Return Values

This method does not return a value.

Remarks

A 32-bit GDI COLORREF value contains three, 8-bit color components. The most significant 8 bits are zeros and are not used, the next 8 bits contain the blue component, the next 8 bits contain the green component, and the last 8 bits (the least significant) contain the red component. Note that the ordering (starting with the high-order bits) of the components in a COLORREF value is blue, green, red; whereas, the ordering of an ARGB value is alpha, red, green, blue.

Example Code [C++]

The following example creates a Color object and sets a GDI COLORREF value. The code then sets the Color object to the value of the GDI COLORREF value, creates a pen, and draws a line.

VOID Example_SetFromCOLORREF(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a color object.
   Color gdipColor(255, 0, 0, 255);

   // COLORREF is defined as an unsigned long in Wingdi.h
   unsigned long gdiColorRef = RGB(0, 0, 0);   // Set a GDI COLORREF value.

   // Set the color object to the COLORREF value.
   gdipColor.SetFromCOLORREF(gdiColorRef);

   // Create a Pen object based on the Color object.
   Pen pen((gdipColor), 10);

   // Draw a line.
   graphics.DrawLine(&pen, 0, 0, 200, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
MakeARGB, ToCOLORREF


Color::SetValue(argb)

The SetValue method sets the color of this Color object.

VOID SetValue(
  ARGB argb
);

Parameters

argb
[in] Thirty-two bit ARGB value that specifies the color. An ARGB value consolidates the alpha, red, green, and blue components of a color. ARGB is defined in Gdipluspixelformats.h.

Return Values

This method does not return a value.

Example Code [C++]

The following example initializes an ARGB value and then passes that value to the SetValue method of a Color object. The code creates a brush based on the Color object and then uses the brush to fill a rectangle.

VOID Example_SetValue(HDC hdc)
{

   Graphics graphics(hdc);

   // Create a Color object set to white.
   Color myColor(255, 255, 255, 255);

   // Create an ARGB value, and use it to set the color of the Color object.
   ARGB argb = 0xFF8080FF;
   myColor.SetValue(argb);

   // Create a SolidBrush object with myColor, and use it to fill a rectangle.
   SolidBrush argbBrush(myColor);
   graphics.FillRectangle(&argbBrush, Rect(0, 0, 100, 100));

}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
GetValue, MakeARGB


Color::ToCOLORREF()

The ToCOLORREF method converts this Color object's ARGB value to a GDI COLORREF value.

COLORREF ToCOLORREF(void);

Parameters

This method has no parameters.

Return Values

This method returns a GDI COLORREF value that has the same red, green, and blue components as this color's ARGB value.

Remarks

When the ARGB value is converted to a COLORREF value, the alpha component of the ARGB value is ignored.

Example Code [C++]

The following example creates two Color objects and converts the ARGB value of the first Color object into a GDI COLORREF value. The code then passes that COLORREF value to the SetFromCOLORREF method of the second Color object. Finally, the code uses the second Color object to fill a rectangle.

VOID Example_ToCOLORREF(HDC hdc)
{

   Graphics graphics(hdc);

   // Create two Color objects.
   Color firstColor(255, 128, 128, 255);
   Color secondColor(255, 255, 255, 255);

   // Convert the ARGB value of the first color to a COLORREF value.
   COLORREF colorRef = firstColor.ToCOLORREF();

   // Use the COLORREF value to set the color of secondColor.
   secondColor.SetFromCOLORREF(colorRef);

   // Create a SolidBrush object based on secondColor, and fill a rectangle.
   SolidBrush colorRefBrush(secondColor);
   graphics.FillRectangle(&colorRefBrush, Rect(0, 0, 100, 100));

}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.

See Also

Reference
SetFromCOLORREF


CustomLineCap Class

The CustomLineCap class encapsulates a custom line cap. A line cap defines the style of graphic used to draw the ends of a line. It can be various shapes, such as a square, circle, or diamond. A custom line cap is defined by the path that draws it. The path is drawn by using a Pen object to draw the outline of a shape or by using a Brush object to fill the interior. The cap can be used on either or both ends of the line. Spacing can be adjusted between the end caps and the line.

Inheritance

GdiplusBase
CustomLineCap

Constructors

Constructor | Description
CustomLineCap | Initializes a new CustomLineCap object.

Methods

Method | Description
Clone | Copies the content of the existing object into a new CustomLineCap object.
GetBaseCap | Gets the style of the base cap.
GetBaseInset | Gets the offset from the line cap at the base of the line to the start of the line.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetStrokeCaps | Gets the end cap styles for both the start and end caps.
GetStrokeJoin | Gets the style of LineJoin used to join multiple lines in the same GraphicsPath object.
GetWidthScale | Gets the value of the scale width.
SetBaseCap | Sets the style of base cap.
SetBaseInset | Sets the offset from the line cap at the base of the line to the start of the line.
SetStrokeCap | Sets the line caps for both the start and end caps.
SetStrokeCaps | Sets the end cap styles for both the start and end caps.
SetStrokeJoin | Sets the style of LineJoin used to join multiple lines in the same GraphicsPath.
SetWidthScale | Sets the value of the scale width.
~CustomLineCap | CustomLineCap object destructor.


CustomLineCap::CustomLineCap(fillPath, strokePath, baseCap, baseInset)

Creates a CustomLineCap object.

CustomLineCap(
  const GraphicsPath* fillPath,
  const GraphicsPath* strokePath,
  LineCap baseCap,
  REAL baseInset
);

Parameters

fillPath
[in] Pointer to a path.
strokePath
[in] Pointer to a path.
baseCap
[in] Optional. Element of the LineCap enumeration that specifies the line cap that will be used. The default value is LineCapFlat.
baseInset
[in] Optional. The default value is 0.

Return Values

This method does not return a value.

Remarks

The fillPath and strokePath parameters cannot be used at the same time. You should pass NULL to one of those two parameters. If you pass nonnull values to both parameters, then fillPath is ignored.

The CustomLineCap class uses the winding fill mode regardless of the fill mode that is set for the GraphicsPath object passed to the CustomLineCap constructor.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.


CustomLineCap Methods

This topic lists the methods of the CustomLineCap class. For a complete class listing, see CustomLineCap Class.

  • Clone()
  • GetBaseCap()
  • GetBaseInset()
  • GetLastStatus()
  • GetStrokeCaps(startCap, endCap)
  • GetStrokeJoin()
  • GetWidthScale()
  • SetBaseCap(baseCap)
  • SetBaseInset(inset)
  • SetStrokeCap(strokeCap)
  • SetStrokeCaps(startCap, endCap)
  • SetStrokeJoin(lineJoin)
  • SetWidthScale(widthScale)


CustomLineCap::Clone()

The Clone method copies the contents of the existing object into a new CustomLineCap object.

CustomLineCap* Clone(void);

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new CustomLineCap object.

Example Code [C++]

The following example creates a CustomLineCap object with a stroke path, creates a second CustomLineCap object by cloning the first, and then assigns the cloned cap to a Pen object. It then draws a line by using the Pen object.

VOID Example_Clone(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Path, and add two lines to it.
   Point points[3] = {Point(-15, -15), Point(0, 0), Point(15, -15)};
   GraphicsPath capPath(FillModeAlternate);
   capPath.AddLines(points, 3);

   // Create a CustomLineCap object.
   CustomLineCap firstCap(NULL, &capPath);

   // Create a copy of firstCap.
   CustomLineCap * secondCap = firstCap.Clone();

   // Create a Pen object, assign second cap as the custom end cap, and
   // draw a line.
   Pen pen(Color(255, 0, 0, 0), 1);
   pen.SetCustomEndCap(secondCap);
   graphics.DrawLine(&pen, Point(0, 0), Point(100, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
LineCap


CustomLineCap::GetBaseCap()

The GetBaseCap method gets the style of the base cap. The base cap is a LineCap object used as a cap at the end of a line along with this CustomLineCap object.

LineCap GetBaseCap(void);

Parameters

This method has no parameters.

Return Values

This method returns the value of the line cap used at the base of the line.

Example Code [C++]

The following example creates a CustomLineCap object, sets its base cap, and then gets the base cap and assigns it to a Pen object. It then uses the Pen object to draw a line.

VOID Example_GetBaseCap(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Path object.
   GraphicsPath capPath;

   //Create a CustomLineCap object, and set its base cap to LineCapRound.
   CustomLineCap custCap(NULL, &capPath);
   custCap.SetBaseCap(LineCapRound);

   // Get the base cap of custCap.
   LineCap baseCap = custCap.GetBaseCap();

   // Create a Pen object, assign baseCap as the end cap, and draw a line.
   Pen pen(Color(255, 0, 255, 0), 5);
   pen.SetEndCap(baseCap);
   graphics.DrawLine(&pen, Point(0, 0), Point(100, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
LineCap


CustomLineCap::GetBaseInset()

The GetBaseInset method gets the distance between the base cap to the start of the line.

REAL GetBaseInset(void);

Parameters

This method has no parameters.

Return Values

This method returns the base inset value.

Remarks

The base inset is used to separate the base cap from the start of the line. A value of 0 makes the base cap and the line touch. A value greater than 0 inserts a space (in units) between the line cap and the start of the line.

Example Code [C++]

The following example creates a CustomLineCap object, gets the base inset of the cap, and then creates a second CustomLineCap object that uses the same base inset.

VOID Example_GetBaseInset(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Path object.
   GraphicsPath capPath;

   //Create a CustomLineCap object, and set its base cap to LineCapRound.
   CustomLineCap custCap(NULL, &capPath, LineCapRound, 5);

   // Get the base inset of custCap.
   REAL baseInset = custCap.GetBaseInset();

   // Create a second CustomLineCap object with the same base inset as the
   // first.
   CustomLineCap insetCap(NULL, &capPath, LineCapRound, baseInset);

   // Create a Pen object and assign insetCap as the custom end cap.
   // Then draw a line.
   Pen pen(Color(255, 0, 0, 255), 5);
   pen.SetCustomEndCap(&insetCap);
   graphics.DrawLine(&pen, Point(0, 0), Point(100, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
LineCap


CustomLineCap::GetLastStatus()

The GetLastStatus method returns a value that indicates the nature of this CustomLineCap object's most recent method failure.

Status GetLastStatus(void) const;

Parameters

This method has no parameters.

Return Values

The GetLastStatus method returns an element of the Status enumeration.

If no methods invoked on this CustomLineCap object have failed since the previous call to GetLastStatus, then GetLastStatus returns Ok.

If at least one method invoked on this CustomLineCap object has failed since the previous call to GetLastStatus, then GetLastStatus returns a value that indicates the nature of the most recent failure.

Remarks

You can call GetLastStatus immediately after constructing a CustomLineCap object to determine whether the constructor succeeded.

The first time you call the GetLastStatus method of a CustomLineCap object, it returns Ok if the constructor succeeded and all methods invoked so far on the CustomLineCap object succeeded. Otherwise, it returns a value that indicates the nature of the most recent failure.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.


CustomLineCap::GetStrokeCaps(startCap, endCap)

The GetStrokeCaps method gets the end cap styles for both the start line cap and the end line cap. Line caps are LineCap objects that end the individual lines within a path.

Status GetStrokeCaps(
  LineCap* startCap,
  LineCap* endCap
);

Parameters

startCap
[out] Pointer to a variable that receives an element of the LineCap enumeration that indicates the line cap used at the start of the line to be drawn.
endCap
[out] Pointer to a variable that receives an element of the LineCap enumeration that indicates the line cap used at the end of the line to be drawn.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a CustomLineCap object and sets its start and end line caps. It then gets the line caps and assigns them as the start and end caps of a Pen object that it then uses to draw a line.

VOID Example_GetStrokeCaps(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Path and add two lines to it.
   Point points[3] = {Point(-15, -15), Point(0, 0), Point(15, -15)};
   GraphicsPath capPath;
   capPath.AddLines(points, 3);

   // Create a CustomLineCap object.
   CustomLineCap custCap(NULL, &capPath);

   // Set the start and end caps for custCap.
   custCap.SetStrokeCaps(LineCapTriangle, LineCapRound);

   // Get the start and end caps from custCap.
   LineCap startStrokeCap, endStrokeCap;
   custCap.GetStrokeCaps(&startStrokeCap, &endStrokeCap);

   // Create a Pen object, assign startStrokeCap and endStrokeCap as the
   // start and end caps, and draw a line.
   Pen strokeCapPen(Color(255, 0, 0, 0), 15.2f);
   strokeCapPen.SetLineCap(startStrokeCap, endStrokeCap, DashCapFlat);
   graphics.DrawLine(&strokeCapPen, Point(100, 100), Point(300, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
LineCap, Status


CustomLineCap::GetStrokeJoin()

The GetStrokeJoin method returns the style of LineJoin used to join multiple lines in the same GraphicsPath object.

LineJoin GetStrokeJoin(void);

Parameters

This method has no parameters.

Return Values

This method returns the style of line join.

Remarks

The CustomLineCap object uses a path and a stroke to define the end cap. The stroke is contained in a GraphicsPath object, which can contain more than one figure. If there is more than one figure in the GraphicsPath object, the stroke join determines how their joint is graphically displayed.

Example Code [C++]

The following example creates a CustomLineCap object with a stroke join. It then gets the stroke join and assigns it as the line join of a Pen object that it then uses to draw a line.

VOID Example_GetStrokeJoin(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Path, and add two lines to it.
   Point points[3] = {Point(-15, -15), Point(0, 0), Point(15, -15)};
   GraphicsPath capPath;
   capPath.AddLines(points, 3);

   // Create a CustomLineCap object.
   CustomLineCap custCap(NULL, &capPath);

   // Set the stroke join for custCap.
   custCap.SetStrokeJoin(LineJoinBevel);

   // Get the stroke join from custCap.
   LineJoin strokeJoin = custCap.GetStrokeJoin();

   // Create a Pen object, assign strokeJoin as the line join, and draw two
   // joined lines in a path.
   Pen strokeJoinPen(Color(255, 255, 0, 0), 15.1f);
   strokeJoinPen.SetLineJoin(strokeJoin);
   GraphicsPath joinPath;
   joinPath.AddLine(Point(10, 10), Point(10, 200));
   joinPath.AddLine(Point(10, 200), Point(200, 200));
   graphics.DrawPath(&strokeJoinPen, &joinPath);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
LineCap, LineJoin


CustomLineCap::GetWidthScale()

The GetWidthScale method gets the value of the scale width. This is the amount to scale the custom line cap relative to the width of the Pen object used to draw a line. The default value of 1.0 does not scale the line cap.

REAL GetWidthScale(void);

Parameters

This method has no parameters.

Return Values

This method returns the value of the width-scaling factor. It is of type REAL.

Example Code [C++]

The following example creates a CustomLineCap object and sets the width scale. It then gets the width scale, assigns the custom cap to a Pen object, and draws a line.

VOID Example_GetWidthScale(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Path, and add two lines to it.
   Point points[3] = {Point(-15, -15), Point(0, 0), Point(15, -15)};
   GraphicsPath capPath;
   capPath.AddLines(points, 3);

   // Create a CustomLineCap object with capPath as the stroke path.
   CustomLineCap custCap(NULL, &capPath);

   // Set the width scale for custCap.
   custCap.SetWidthScale(3);

   // Get the width scale from custCap.
   REAL widthScale = custCap.GetWidthScale();

   // If the width scale is 3, assign custCap as the end cap of a Pen object
   // and draw a line.
   if (widthScale == 3)
   {
       Pen widthScalePen(Color(255, 0, 255, 0), 1.0f);
       widthScalePen.SetCustomEndCap(&custCap);
       graphics.DrawLine(&widthScalePen, Point(0, 0), Point(200, 200));
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, LineCap, Status


CustomLineCap::SetBaseCap(baseCap)

The SetBaseCap method sets the LineCap that appears as part of this CustomLineCap at the end of a line.

Status SetBaseCap(
  LineCap baseCap
);

Parameters

baseCap
[in] Element of the LineCap enumeration that specifies the line cap used on the ends of the line to be drawn.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a CustomLineCap object and sets its base cap. It then assigns the custom cap as the end cap of a Pen object and draws a line.

VOID Example_SetBaseCap(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Path object.
   Point points[3] = {Point(-15, -15), Point(0, 0), Point(15, -15)};
   GraphicsPath capPath;
   capPath.AddLines(points, 3);

   //Create a CustomLineCap object and set its base cap to LineCapRound.
   CustomLineCap custCap(NULL, &capPath);
   custCap.SetBaseCap(LineCapRound);

   // Create a Pen object, assign custCap as the custom end cap, and draw a
   // line.
   Pen pen(Color(255, 0, 0, 255), 5.3f);
   pen.SetCustomEndCap(&custCap);
   graphics.DrawLine(&pen, Point(10, 10), Point(100, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, LineCap, Pen, Status


CustomLineCap::SetBaseInset(inset)

The SetBaseInset method sets the base inset value of this custom line cap. This is the distance between the end of a line and the base cap.

Status SetBaseInset(
  REAL inset
);

Parameters

inset
[in] Real number that specifies the distance, in units, from the base cap to the start of the line. If this value is greater than the length of the line, the behavior of this method is undefined.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a CustomLineCap object and sets the base inset of the cap. It then assigns the custom cap to a Pen object and draws a line.

VOID Example_SetBaseInset(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Path object.
   GraphicsPath capPath;

   //Create a CustomLineCap object and set its base cap to LineCapRound.
   CustomLineCap custCap(NULL, &capPath, LineCapRound, 5);

   // Create a Pen object, assign custCap as the custom end cap, and then
   // draw a line.
   Pen pen(Color(255, 0, 0, 0), 5.1f);
   pen.SetCustomEndCap(&custCap);
   graphics.DrawLine(&pen, Point(0, 0), Point(100, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, LineCap, Status


CustomLineCap::SetStrokeCap(strokeCap)

The SetStrokeCap method sets the LineCap object used to start and end lines within the GraphicsPath object that defines this CustomLineCap object.

Status SetStrokeCap(
  LineCap strokeCap
);

Parameters

strokeCap
[in] Element of the LineCap enumeration that specifies the line cap that will be used on the ends of the line to be drawn.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a CustomLineCap object and sets its start and end stroke caps. It then assigns the custom cap to a Pen ojbect and draws a line.

VOID Example_SetStrokeCap(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Path, and add two lines to it.
   Point points[3] = {Point(-15, -15), Point(0, 0), Point(15, -15)};
   GraphicsPath capPath;
   capPath.AddLines(points, 3);

   // Create a CustomLineCap object.
   CustomLineCap custCap(NULL, &capPath);

   // Set the start and end caps for custCap.
   custCap.SetStrokeCap(LineCapTriangle);

   // Create a Pen object, assign startStrokeCap and endStrokeCap as the
   // start and end caps, and draw a line.
   Pen strokeCapPen(Color(255, 255, 0, 0), 4.8f);
   strokeCapPen.SetCustomEndCap(&custCap);
   graphics.DrawLine(&strokeCapPen, Point(100, 100), Point(300, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
LineCap, Status


CustomLineCap::SetStrokeCaps(startCap, endCap)

The SetStrokeCaps method sets the LineCap objects used to start and end lines within the GraphicsPath object that defines this CustomLineCap object.

Status SetStrokeCaps(
  LineCap startCap,
  LineCap endCap
);

Parameters

startCap
[in] Element of the LineCap enumeration that specifies the line cap that will be used for the start of the line to be drawn.
endCap
[in] Element of the LineCap enumeration that specifies the line cap that will be used for the end of the line to be drawn.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a CustomLineCap object and sets its start and end stroke caps. It then assigns the custom cap to a Pen object and draws a line.

VOID Example_SetStrokeCaps(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Path, and add two lines to it.
   Point points[3] = {Point(-15, -15), Point(0, 0), Point(15, -15)};
   GraphicsPath capPath;
   capPath.AddLines(points, 3);

   // Create a CustomLineCap object.
   CustomLineCap custCap(NULL, &capPath);

   // Set the start and end caps for custCap.
   custCap.SetStrokeCaps(LineCapTriangle, LineCapRound);

   // Create a Pen object, assign startStrokeCap and endStrokeCap as the
   // start and end caps, and draw a line.
   Pen strokeCapPen(Color(255, 255, 0, 255), 5.0f);
   strokeCapPen.SetCustomEndCap(&custCap);
   graphics.DrawLine(&strokeCapPen, Point(100, 100), Point(300, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
LineCap, Status


CustomLineCap::SetStrokeJoin(lineJoin)

The SetStrokeJoin method sets the style of line join for the stroke. The line join specifies how two lines that intersect within the GraphicsPath object that makes up the custom line cap are joined.

Status SetStrokeJoin(
  LineJoin lineJoin
);

Parameters

lineJoin
[in] Element of the LineJoin enumeration that specifies the line join that will be used for two lines that are drawn by the same pen and that have overlapping ends.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a CustomLineCap object with a stroke join. It then assigns the custom cap to a Pen object and draws a line.

VOID Example_SetStrokeJoin(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Path, and add two lines to it.
   Point points[3] = {Point(-15, -15), Point(0, 0), Point(15, -15)};
   GraphicsPath capPath;
   capPath.AddLines(points, 3);

   // Create a CustomLineCap object.
   CustomLineCap custCap(NULL, &capPath);

   // Set the stroke join for custCap.
   custCap.SetStrokeJoin(LineJoinBevel);

   // Create a Pen object, assign custCap to a Pen object, and draw a line.
   Pen strokeJoinPen(Color(255, 200, 150, 0), 5.0f);
   strokeJoinPen.SetCustomEndCap(&custCap);
   graphics.DrawLine(&strokeJoinPen, Point(0, 0), Point(200, 200));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
LineCap, LineJoin, Status


CustomLineCap::SetWidthScale(widthScale)

The SetWidthScale method sets the value of the scale width. This is the amount to scale the custom line cap relative to the width of the Pen used to draw lines. The default value of 1.0 does not scale the line cap.

Status SetWidthScale(
  IN REAL widthScale
);

Parameters

widthScale
[in] Real number that specifies the scaling factor that will be used to scale the line width.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a CustomLineCap object and sets the width scale. It then assigns the custom cap to a Pen object, and draws a line.

VOID Example_SetWidthScale(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Path, and add two lines to it.
   Point points[3] = {Point(-15, -15), Point(0, 0), Point(15, -15)};
   GraphicsPath capPath;
   capPath.AddLines(points, 3);

   // Create a CustomLineCap object with capPath as the stroke path.
   CustomLineCap custCap(NULL, &capPath);

   // Set the width scale for custCap.
   custCap.SetWidthScale(3);

   // Assign custCap to a Pen object and draw a line.
   Pen widthScalePen(Color(255, 0, 180, 180), 1.7f);
   widthScalePen.SetCustomEndCap(&custCap);
   graphics.DrawLine(&widthScalePen, Point(0, 0), Point(200, 200));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
LineCap, Status


EncoderParameter Class

An EncoderParameter object holds a parameter that can be passed to an image encoder. An EncoderParameter object can also be used to receive a list of possible values supported by a particular parameter of a particular image encoder.

Data Members

The following table lists the data members of the EncoderParameter class in the order that they are defined in the header file.

Data member | Description
Guid | GUID. Identifies the parameter category. GUIDs that represent various parameter categories (EncoderCompression, EncoderColorDepth, and the like) are defined in Gdiplusimaging.h.
NumberOfValues | ULONG. Number of values in the array pointed to by the Value data member.
Type | ULONG. Identifies the data type of the parameter. The EncoderParameterValueType enumeration in Gdiplusenums.h defines several possible value types.
Value | VOID*. Pointer to an array of values. Each value has the type specified by the Type data member.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimaging.h; include Gdiplus.h.

See Also

Reference
EncoderParameters, GetEncoderParameterList, GetEncoderParameterListSize, EncoderParameterValueType
Tasks and Examples
Using Image Encoders and Decoders


EncoderParameters Class

An EncoderParameters object is an array of EncoderParameter objects along with a data member that specifies the number of EncoderParameter objects in the array.

Data Members

The following table lists the data members of the EncoderParameters class in the order that they are defined in the header file.

Data member | Description
Count | UINT. Number of EncoderParameter objects in the array.
Parameter[1] | Array of EncoderParameter objects.

Remarks

When you create an EncoderParameters object, you must allocate enough memory to hold all of the EncoderParameter objects that will eventually be placed in the array. For example, if you want to create an EncoderParameters object that will hold an array of five EncoderParameter objects, you should use code similar to the following:

EncoderParameters* pEncoderParameters = (EncoderParameters*)
   malloc(sizeof(EncoderParameters) + 4 * sizeof(EncoderParameter));

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimaging.h; include Gdiplus.h.

See Also

Reference
EncoderParameter, GetEncoderParameterList, GetEncoderParameterListSize, EncoderParameterValueType
Tasks and Examples
Using Image Encoders and Decoders


Font Class

The Font class encapsulates the characteristics, such as family, height, size, and style (or combination of styles), of a specific font. A Font object is used when drawing strings.

Inheritance

GdiplusBase
Font

Constructors

Constructor | Description
Font Constructors | Overloaded. Creates and initializes a new Font object.

Methods

Method | Description
Clone | Creates a new Font object based on this Font object.
GetFamily | Gets information about the font family on which this font is based.
GetHeight | Overloaded. Gets the height of this font.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetLogFontA | Gets the attributes of this Font object by using a LOGFONTA structure.
GetLogFontW | Gets the attributes of this Font object by using a LOGFONTW structure.
GetSize | Gets the font size (commonly called em size) of this Font object.
GetStyle | Gets the style of this Font object.
GetUnit | Gets the unit of measure of this Font object.
IsAvailable | Determines whether this Font object was created successfully.
~Font | Font object destructor.


Font Constructors

This topic lists the constructors of the Font class. For a complete class listing, see Font Class.

  • Font(hdc)
  • Font(HDC hdc, LOGFONTA* logfont)
  • Font(HDC hdc, LOGFONTW* logfont)
  • Font(hdc, hfont)
  • Font(family, emSize, style, unit)
  • Font(familyName, emSize, style, unit, fontCollection)


Font::Font(hdc)

Creates a Font object based on the GDI font object that is currently selected into a specified device context. This constructor is provided for compatibility with GDI.

Font(
  HDC hdc
);

Parameters

hdc
[in] Handle to a Windows device context that has a font selected. A handle is a number that Windows uses internally to reference an object.

Remarks

In most cases when you obtain a device context handle by calling the GetHDC method of a Graphics object, the device context will not have a font selected. If you pass such a handle to this constructor, the constructor will fail.

A device context is a structure that is maintained internally. It is associated with a particular device, such as a video monitor or a printer. There is usually one device context associated with each window displayed on a video monitor. A device context contains some graphics attributes used by GDI+.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Tasks and Examples
Using Text and Fonts
Concepts
Changes in the Programming Model


Font::Font(HDC hdc, LOGFONTA* logfont)

Creates a Font object directly from a GDI logical font. The GDI logical font is a LOGFONTA structure, which is the one-byte character version of a logical font. This constructor is provided for compatibility with GDI.

Font(
  HDC hdc,
  const LOGFONTA* logfont
);

Parameters

hdc
[in] Handle to a Windows device context. A handle is a number that Windows uses internally to reference an object.
logfont
[in] Pointer to a LOGFONTA structure variable that contains attributes of the font. The LOGFONTA structure is the one-byte character version of the logical font.

Remarks

A device context is a structure that is maintained internally. It is associated with a particular device, such as a video monitor or a printer. There is usually one device context associated with each window displayed on a video monitor. A device context contains some graphics attributes used by GDI+.

A LOGFONTA structure is a GDI structure. GDI+ uses only some of the attributes contained in this structure.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
LOGFONTA
Tasks and Examples
Using Text and Fonts
Concepts
Changes in the Programming Model


Font::Font(HDC hdc, LOGFONTW* logfont)

Creates a Font object directly from a GDI logical font. The GDI logical font is a LOGFONTW structure, which is the wide character version of a logical font. This constructor is provided for compatibility with GDI.

Font(
  HDC hdc,
  const LOGFONTW* logfont
);

Parameters

hdc
[in] Handle to a Windows device context. A handle is a number that Windows uses internally to reference an object.
logfont
[in] Pointer to a LOGFONTW structure variable that contains attributes of the font. The LOGFONTW structure is the wide character version of the logical font.

Remarks

A device context is a structure that is maintained internally. It is associated with a particular device, such as a video monitor or a printer. There is usually one device context associated with each window displayed on a video monitor. A device context contains some graphics attributes used by GDI+.

A LOGFONTW structure is a GDI structure. GDI+ uses only some of the attributes contained in this structure.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
LOGFONTW
Tasks and Examples
Using Text and Fonts
Concepts
Changes in the Programming Model


Font::Font(hdc, hfont)

Creates a Font object indirectly from a GDI logical font by using a handle to a GDI LOGFONT structure.

Font(
  HDC hdc,
  const HFONT hfont
);

Parameters

hdc
[in] Handle to a Windows device context. A handle is a number that Windows uses internally to reference an object.
hfont
[in] Handle to a logical font.

Remarks

A device context is a structure that is maintained internally. It is associated with a particular device, such as a video monitor or a printer. There is usually one device context associated with each window displayed on a video monitor. A device context contains some graphics attributes used by GDI+.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Tasks and Examples
Using Text and Fonts
Concepts
Changes in the Programming Model


Font::Font(family, emSize, style, unit)

Creates a Font object based on a FontFamily object, a size, a font style, and a unit of measurement.

Font(
  const FontFamily* family,
  REAL emSize,
  INT style,
  Unit unit
);

Parameters

family
[in] Pointer to a FontFamily object that specifies information such as the string that identifies the font family and the font family's text metrics measured in design units.
emSize
[in] Real number that specifies the font height measured in the units specified in the unit parameter.
style
[in] Optional. Integer that specifies the style of the typeface. This value must be an element of the FontStyle enumeration or the result of a bitwise OR applied to two or more of these elements. For example, FontStyleBold | FontStyleUnderline | FontStyleStrikeout sets the style as a combination of the three styles. The default value is FontStyleRegular.
unit
[in] Optional. Element of the Unit enumeration that specifies the unit of measurement for the font size. The default value is UnitPoint.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
FontFamily, FontStyle, Unit
Tasks and Examples
Using Text and Fonts


Font::Font(familyName, emSize, style, unit, fontCollection)

Creates a Font object based on a font family, a size, a font style, a unit of measurement, and a FontCollection object.

Font(
  const WCHAR* familyName,
  REAL emSize,
  INT style,
  Unit unit,
  const FontCollection* fontCollection
);

Parameters

familyName
[in] Name of the font family.
emSize
[in] Real number that specifies the font height measured in the units specified in the unit parameter.
style
[in] Optional. Integer that specifies the style of the typeface. This value must be an element of the FontStyle enumeration or the result of a bitwise OR applied to two or more of these elements. For example, FontStyleBold | FontStyleUnderline | FontStyleStrikeout sets the style as a combination of the three styles. The default value is FontStyleRegular.
unit
[in] Optional. Element of the Unit enumeration that specifies the unit of measurement for the font size. The default value is UnitPoint.
fontCollection
[in] Optional. Pointer to a FontCollection object that specifies a user-defined group of fonts. If the value of this parameter is NULL, the system font collection is used. The default value is NULL.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
FontFamily, FontStyle, Unit
Tasks and Examples
Using Text and Fonts


Font Methods

This topic lists the methods of the Font class. For a complete class listing, see Font Class.

  • Clone()
  • GetFamily(family)
  • GetHeight(dpi)
  • GetHeight(graphics)
  • GetLastStatus()
  • GetLogFontA(g, logfontA)
  • GetLogFontW(g, logfontW)
  • GetSize()
  • GetStyle()
  • GetUnit()
  • IsAvailable()


Font::Clone()

The Clone method creates a new Font object based on this Font object.

Font* Clone(void) const;

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new Font object.

Example Code [C++]

The following example creates a Font object, clones it, and then uses the clone to draw text.

VOID Example_Clone(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Font object.
   Font font(L"Arial", 16);

   // Create a clone of the Font object.
   Font* cloneFont = font.Clone();

   // Draw Text with cloneFont.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   WCHAR      string[256];
   wcscpy(string, L"This is a cloned Font");
   graphics.DrawString(string,
                       21, cloneFont, PointF(0.0f, 0.0f), &solidbrush);

   // Delete the cloned Font object.
   delete cloneFont;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Tasks and Examples
Using Text and Fonts


Font::GetFamily(family)

The GetFamily method gets the font family on which this font is based.

Status GetFamily(
  FontFamily* family
) const;

Parameters

family
[out] Pointer to a FontFamily object that receives the font family.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Font object, retrieves the information about the font family on which it is based, and then uses the FontFamily object to create a second Font object. The example then uses the second Font object to draw text.

VOID Example_GetFamily(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Font object.
   Font myFont(L"Arial", 16);

   // Get the FontFamily of myFont.
   FontFamily fontFamily;
   myFont.GetFamily(&fontFamily);

   // Create a new Font object from fontFamily.
   Font familyFont(&fontFamily, 16);

   // Draw Text with familyFont.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   WCHAR      string[256];
   wcscpy(string, L"This is a Font created from a FontFamily");
   graphics.DrawString(string, 40, &familyFont, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
FontFamily
Tasks and Examples
Using Text and Fonts


Font::GetHeight Methods

This topic lists the GetHeight methods of the Font class. For a complete list of methods for the Font class, see Font Methods.

  • Font::GetHeight(dpi)
  • Font::GetHeight(graphics)


Font::GetHeight(dpi)

The GetHeight method gets the height, in pixels, of this font.

REAL GetHeight(
  REAL dpi
) const;

Parameters

dpi
[in] Real number that specifies the dots per inch of the video display.

Return Values

This method returns the height of the font in pixels.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetSize, GetStyle, GetUnit
Tasks and Examples
Using Text and Fonts


Font::GetHeight(graphics)

The GetHeight method gets the height of the font in the units of the Graphics object.

REAL GetHeight(
  const Graphics* graphics
) const;

Parameters

graphics
[in] Pointer to a Graphics object that specifies the attributes of the display device.

Return Values

This method returns the height of the font in the units that are currently set in the Graphics object.

Example Code [C++]

The following example creates a Font object, retrieves the height of the Font object, and uses the height to position two lines of text, with the second line directly below the first.

VOID Example_GetHeight(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Font object.
   Font myFont(L"Arial", 16);

   // Draw text with myFont.
   SolidBrush solidbrush_1(Color(255, 0, 0, 0));
   WCHAR      string[256];
   wcscpy(string, L"The first line of text");
   graphics.DrawString(string, 22, &myFont, PointF(0, 0), &solidbrush_1);

   // Get the height of myFont.
   REAL height = myFont.GetHeight(&graphics);

   // Draw text immediately below the first line of text.
   SolidBrush solidbrush_2(Color(255, 255, 0, 0));
   WCHAR      string2[256];
   wcscpy(string2, L"The second line of text");
   graphics.DrawString(string2,
                       23, &myFont, PointF(0, height), &solidbrush_2);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics
Tasks and Examples
Using Text and Fonts


Font::GetLastStatus()

The GetLastStatus method returns a value that indicates the nature of this Font object's most recent method failure.

Status GetLastStatus(void) const;

Parameters

This method has no parameters.

Return Values

The GetLastStatus method returns an element of the Status enumeration.

If no methods invoked on this Font object have failed, then GetLastStatus returns Ok.

If at least one method invoked on this Font object has failed, then GetLastStatus returns a value that indicates the nature of the most recent failure.

Remarks

You can call GetLastStatus immediately after constructing a Font object to determine whether the constructor succeeded.

The first time you call the GetLastStatus method of a Font object, it returns Ok if the constructor succeeded and all methods invoked so far on the Font object succeeded. Otherwise, it returns a value that indicates the nature of the most recent failure.

Example Code [C++]

The following example creates a Font object, checks to see that the call to create the object was successful, and, if it was, uses the Font object to draw text.

VOID Example_GetLastStatus(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Font object.
   Font myFont(L"Arial", 16);

   // Check the status of the last call.
   Status status = myFont.GetLastStatus();

   // If the call to create myFont succeeded, use myFont to write text.
   if (status == Ok)
   {
       SolidBrush solidbrush(Color(255, 0, 0, 0));
       WCHAR      string[256];
       wcscpy(string, L"The call succeeded");
       graphics.DrawString(string, 18, &myFont, PointF(0, 0), &solidbrush);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, IsAvailable, Status
Tasks and Examples
Using Text and Fonts


Font::GetLogFontA(g, logfontA)

The GetLogFontA method uses a LOGFONTA structure to get the attributes of this Font object.

Status GetLogFontA(
  const Graphics* g,
  LOGFONTA* logfontA
) const;

Parameters

g
[in] Pointer to a Graphics object that contains attributes of the display device.
logfontA
[out] Pointer to a LOGFONTA structure variable that receives the font attributes.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Font object, gets the font attributes from the Font object, and uses these attributes (contained in the LOGFONTA structure) to create a second Font object. The second Font object is then used to draw text.

VOID Example_GetLogFontA(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Font object.
   Font myFont(L"Arial", 16);

   // Get attributes of myFont.
   LOGFONTA logFont;
   myFont.GetLogFontA(&graphics, &logFont);

   // Create a second Font object from logFont.
   Font logfontFont(hdc, &logFont);

   // Draw text using logfontFont.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   WCHAR      string[256];
   wcscpy(string, L"Font from a LOGFONT");
   graphics.DrawString(string, 19, &logfontFont, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, LOGFONTA
Tasks and Examples
Using Text and Fonts


Font::GetLogFontW(g, logfontW)

The GetLogFontW method uses a LOGFONTW structure to get the attributes of this Font object.

Status GetLogFontW(
  const Graphics* g,
  LOGFONTW* logfontW
) const;

Parameters

g
[in] Pointer to a Graphics object that contains attributes of the video display.
logfontW
[out] Pointer to a LOGFONTW structure variable that receives the font attributes.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Font object, gets the font attributes from the Font object, and uses these attributes (contained in the LOGFONTW structure) to create a second Font object. The second Font object is then used to draw text.

VOID Example_GetLogFontW(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Font object.
   Font myFont(L"Arial", 16);

   // Get attributes of myFont.
   LOGFONTW logFont;
   myFont.GetLogFontW(&graphics, &logFont);

   // Create a second Font object from logFont.
   Font logfontFont(hdc, &logFont);

   // Draw text using logfontFont.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   WCHAR      string[256];
   wcscpy(string, L"Font from a LOGFONT");
   graphics.DrawString(string, 19, &logfontFont, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, LOGFONTW
Tasks and Examples
Using Text and Fonts


Font::GetSize()

The GetSize method returns the font size (commonly called the em size) of this Font object. The size is in the units of this Font object.

REAL GetSize(void) const;

Parameters

This method has no parameters.

Return Values

The method returns the font size. The size is in the units of this Font object.

Example Code [C++]

The following example creates a Font object, gets the size of the font, and creates a second Font object of the same size as the first. The second Font object is then used to draw text.

VOID Example_GetSize(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Font object.
   Font myFont(L"Arial", 16);

   // Get the size of myFont.
   REAL size = myFont.GetSize();

   // Create a second Font object with the same emSize as myFont.
   Font sizeFont(L"Arial", size);

   // Draw text using sizeFont.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   WCHAR      string[256];
   wcscpy(string, L"Font with an acquired size");
   graphics.DrawString(string, 26, &sizeFont, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetHeight, GetStyle, GetUnit
Tasks and Examples
Using Text and Fonts


Font::GetStyle()

The GetStyle method gets the style of this font's typeface.

INT GetStyle(void) const;

Parameters

This method has no parameters.

Return Values

This method returns a value that is an element of the FontStyle enumeration or the result of a bitwise OR applied to two or more elements of the FontStyle enumeration.

Example Code [C++]

The following example creates a Font object, gets the FontStyle associated with the font, and creates a second Font object by using the same style. The second Font object is then used to draw text.

VOID Example_GetStyle(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Font object.
   Font myFont(L"Arial", 16, FontStyleItalic);

   // Get the style of myFont.
   int style = myFont.GetStyle();

   // Create a second Font object with the same emSize as myFont.
   Font styleFont(L"Arial", 20, style);

   // Draw text using sizeFont.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   WCHAR      string[256];
   wcscpy(string, L"Font with an acquired style");
   graphics.DrawString(string, 27, &styleFont, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
FontStyle, GetSize, GetFamily, GetHeight, GetUnit
Tasks and Examples
Using Text and Fonts


Font::GetUnit()

The GetUnit method returns the unit of measure of this Font object.

Unit GetUnit(void) const;

Parameters

This method has no parameters.

Return Values

This method returns one of the elements of the Unit enumeration.

Example Code [C++]

The following example creates a Font object, gets the unit of measure of the font, and then sets the page units of the Graphics object to the returned unit. It then uses the Font object to draw text.

VOID Example_GetUnit(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Font object.
   Font myFont(L"Arial", 12);

   // Get the unit of measure for myFont.
   Unit unit = myFont.GetUnit();

   // Set the Graphics units of graphics to the retrieved unit value.
   graphics.SetPageUnit(unit);

   // Draw text using sizeFont.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   WCHAR      string[256];
   wcscpy(string, L"Here is some text");
   graphics.DrawString(string, 17, &myFont, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetHeight, GetSize, GetStyle, GetUnit, Unit
Tasks and Examples
Using Text and Fonts


Font::IsAvailable()

The IsAvailable method determines whether this Font object was created successfully.

BOOL IsAvailable(void) const;

Parameters

This method has no parameters.

Return Values

If the font was constructed successfully, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a Font object and then tests whether the Font object is available. If the Font object is available, it is used to draw text.

VOID Example_IsAvailable(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Font object.
   Font myFont(L"Arial", 18);

   // Check whether myFont is available.
   BOOL available = myFont.IsAvailable();

   // Draw text using myFont, if it is availiable.
   if (available)
   {
       SolidBrush solidbrush(Color(255, 0, 0, 0));
       WCHAR      string[256];
       wcscpy(string, L"Here is some text");
       graphics.DrawString(string, 17, &myFont, PointF(0, 0), &solidbrush);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetLastStatus
Tasks and Examples
Using Text and Fonts


FontCollection Class

The FontCollection class is an abstract base class. It contains methods for enumerating the font families in a collection of fonts. Objects built from this class include the InstalledFontCollection and PrivateFontCollection classes.

Inheritance

GdiplusBase
FontCollection

Constructors

Constructor | Description
FontCollection | Creates an empty FontCollection object.

Methods

Method | Description
GetFamilies | Gets the font families contained in this font collection.
GetFamilyCount | Gets the number of font families contained in this font collection.
GetLastStatus | Returns a value that indicates the result of this FontCollection object's previous method call.
~FontCollection | FontCollection object destructor.


FontCollection::FontCollection()

Creates an empty FontCollection object.

FontCollection(void);

Parameters

This constructor has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Font, InstalledFontCollection, PrivateFontCollection
Tasks and Examples
Using Text and Fonts


FontCollection Methods

This topic lists the methods of the FontCollection class. For a complete class listing, see FontCollection Class.

  • GetFamilies(numSought, gpfamilies, numFound)
  • GetFamilyCount()
  • GetLastStatus()


FontCollection::GetFamilies(numSought, gpfamilies, numFound)

The GetFamilies method gets the font families contained in this font collection.

Status GetFamilies(
  INT numSought,
  FontFamily* gpfamilies,
  INT* numFound
) const;

Parameters

numSought
[in] Integer that specifies the number of font families in this font collection.
gpfamilies
[out] Pointer to an array that receives the FontFamily objects.
numFound
[out] Pointer to an INT that receives the number of font families found in this collection. This number should be the same as the numSought value.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A font family consists of a single font type with related styles. An example of a single font type is Arial Regular. An example of a font family is a set of fonts containing Arial Regular, Arial Italic, and Arial Bold style fonts.

Example Code [C++]

The following example creates a PrivateFontCollection object, gets the FontFamily objects contained within the collection, and uses one of the font families to draw text.

VOID Example_GetFamilies(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a PrivateFontCollection object, and add three families.
   PrivateFontCollection fontCollection;
   fontCollection.AddFontFile(L"C:\\WINNT\\Fonts\\Arial.ttf");
   fontCollection.AddFontFile(L"C:\\WINNT\\Fonts\\CourBI.ttf");
   fontCollection.AddFontFile(L"C:\\WINNT\\Fonts\\TimesBd.ttf");

   // Create an array to hold the font families, and get the font families of
   // fontCollection.
   FontFamily families[3];
   int numFamilies;
   fontCollection.GetFamilies(3, families, &numFamilies);

   // Create a Font object from the first FontFamily object in the array.
   Font myFont(&families[0], 16);

   // Use myFont to draw text.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   WCHAR      string[256];
   wcscpy(string, L"This is an Arial font");
   graphics.DrawString(string,
                       wcslen(string), &myFont, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
FontFamily, GetFamilyCount, PrivateFontCollection
Tasks and Examples
Using Text and Fonts


FontCollection::GetFamilyCount()

The GetFamilyCount method gets the number of font families contained in this font collection.

INT GetFamilyCount(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the number of font families contained in this font collection.

Remarks

A font family consists of a single font type with related styles. An example of a single font type is Arial Regular. An example of a font family is a set of fonts containing Arial Regular, Arial Italic, and Arial Bold style fonts.

Example Code [C++]

The following example creates a PrivateFontCollection object, gets the number of FontFamily objects contained within the collection, and outputs that number.

VOID Example_GetFamilyCount(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a PrivateFontCollection object, and add three families.
   PrivateFontCollection fontCollection;
   fontCollection.AddFontFile(L"C:\\WINNT\\Fonts\\Arial.ttf");
   fontCollection.AddFontFile(L"C:\\WINNT\\Fonts\\CourBI.ttf");
   fontCollection.AddFontFile(L"C:\\WINNT\\Fonts\\TimesBd.ttf");

   // Get the number of font families in the collection.
   int numFamilies = fontCollection.GetFamilyCount();

   // Print the number of families as text.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   Font       font(L"Arial", 16);
   WCHAR      string[256];
   swprintf(string, L"There are %i families in fontCollection.", numFamilies);
   graphics.DrawString(string,
                       wcslen(string), &font, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
PrivateFontCollection
Tasks and Examples
Using Text and Fonts


FontCollection::GetLastStatus()

The GetLastStatus method returns a value that indicates the result of this FontCollection object's previous method call.

Status GetLastStatus(void) const;

Parameters

This method has no parameters.

Return Values

The GetLastStatus method returns an element of the Status enumeration.

If the previous method invoked on this FontCollection object succeeded, GetLastStatus returns Ok.

If the previous method failed, then GetLastStatus returns one of the other elements of the Status enumeration that indicates the nature of the failure.

Remarks

You can call GetLastStatus immediately after constructing a FontCollection object to determine whether the constructor succeeded. GetLastStatus returns Ok if the constructor succeeded. Otherwise, it returns a value that indicates the nature of the failure.

Note that the implementation of GetLastStatus in the Font and FontCollection classes is different from the implementation of this method in other classes. Also, the implementation of GetLastStatus in the Font class is different from the implementation of GetLastStatus in the FontCollection class.

Example Code [C++]

The following example creates a PrivateFontCollection object, checks the status of a method call, and, if successful, draws text.

VOID Example_GetLastStatus(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a PrivateFontCollection object, and add three families.
   PrivateFontCollection fontCollection;
   fontCollection.AddFontFile(L"C:\\WINNT\\Fonts\\Arial.ttf");
   fontCollection.AddFontFile(L"C:\\WINNT\\Fonts\\CourBI.ttf");
   fontCollection.AddFontFile(L"C:\\WINNT\\Fonts\\TimesBd.ttf");

   // Create an array to hold the font families, and get the font families of
   // fontCollection.
   FontFamily families[3];
   int numFamilies;
   fontCollection.GetFamilies(3, families, &numFamilies);

   // Verify that the call to GetFamilies was successful.
   Status status = fontCollection.GetLastStatus();

   // If the call was successful, draw text.
   if (status == Ok)
   {
      // Create a Font object from the first FontFamily object in the array.
      Font myFont(&families[0], 16);

      // Use myFont to draw text.
      SolidBrush solidbrush(Color(255, 0, 0, 0));
      WCHAR      string[256];
      wcscpy(string, L"The call was successful");
      graphics.DrawString(string,
                          wcslen(string), &myFont, PointF(0, 0), &solidbrush);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
PrivateFontCollection
Tasks and Examples
Using Text and Fonts


FontFamily Class

This FontFamily class encapsulates a set of fonts that make up a font family. A font family is a group of fonts that have the same typeface but different styles.

Inheritance

GdiplusBase
FontFamily

Constructors

Constructor | Description
FontFamily | Overloaded. Creates a new FontFamily object.

Methods

Method | Description
Clone | Creates a new FontFamily object based on this FontFamily object.
GenericMonospace | Gets a FontFamily object that specifies a generic monospace typeface.
GenericSansSerif | Gets a FontFamily object that specifies a generic sans serif typeface.
GenericSerif | Gets a FontFamily object that specifies a generic serif typeface.
GetCellAscent | Gets the cell ascent, in design units, of this font family.
GetCellDescent | Gets the cell descent, in design units, of this font family.
GetEmHeight | Gets the size (commonly called em height), in design units, of this font family.
GetFamilyName | Gets the name of this font family.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetLineSpacing | Gets the distance between two consecutive lines.
IsAvailable | Determines whether this FontFamily object was created successfully.
IsStyleAvailable | Determines whether the specified style is available for this font family.
~FontFamily | FontFamily object destructor.

Remarks

Only regular, bold, italic, and bold italic are abstracted into the family, other styles, such as Narrow or Black, are considered separate font families. For example Times New Roman is a font family. The Times New Roman font family includes regular, bold, italic, and bold italic.


FontFamily Constructors

This topic lists the constructors of the FontFamily class. For a complete class listing, see FontFamily Class.

  • FontFamily()
  • FontFamily(name, fontCollection)


FontFamily::FontFamily()

Creates an empty FontFamily object.

FontFamily(void);

Parameters

This method has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.


FontFamily::FontFamily(name, fontCollection)

Creates a FontFamily object based on a specified font family.

FontFamily(
  const WCHAR* name,
  const FontCollection* fontCollection
);

Parameters

name
[in] Name of the font family. For example, Arial.ttf is the name of the Arial font family.
fontCollection
[in] Optional. Pointer to a FontCollection object that specifies the collection that the font family belongs to. If fontCollection is NULL, this font family is not part of a collection. The default value is NULL.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
InstalledFontCollection, PrivateFontCollection
Tasks and Examples
Using Text and Fonts


FontFamily Methods

This topic lists the methods of the FontFamily class. For a complete class listing, see FontFamily Class.

  • Clone()
  • GenericMonospace()
  • GenericSansSerif()
  • GenericSerif()
  • GetCellAscent
  • GetCellDescent(style)
  • GetEmHeight(style)
  • GetFamilyName(name, language)
  • GetLastStatus()
  • GetLineSpacing(style)
  • IsAvailable()
  • IsStyleAvailable(style)


FontFamily::Clone()

The Clone method creates a new FontFamily object based on this FontFamily object.

FontFamily* Clone(void) const;

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new FontFamily object.

Example Code [C++]

The following example creates a FontFamily object, clones that object, and then creates a Font object from the clone. It then uses the Font object to draw text.

VOID Example_Clone(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a FontFamily object.
   FontFamily arialFontFamily(L"arial");

   // Clone the FontFamily object and use it to create a Font object.
   FontFamily* cloneFontFamily = arialFontFamily.Clone();
   Font arialFont(cloneFontFamily, 16);

   // Draw text using the new font.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   graphics.DrawString(L"This is an Arial font",
                        21, &arialFont, PointF(0, 0), &solidbrush);

   // Delete the clone.
   delete cloneFontFamily;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Font
Tasks and Examples
Using Text and Fonts


FontFamily::GenericMonospace()

The GenericMonospace method gets a FontFamily object that specifies a generic monospace typeface.

static const FontFamily* GenericMonospace(void);

Parameters

This method has no parameters.

Return Values

This method returns a pointer to a FontFamily object that specifies a generic monospace typeface.

Example Code [C++]

The following example creates a Font object by using a generic monospace FontFamily object and then uses that Font object to draw text.

VOID Example_GenericMonospace(HDC hdc)
{
   Graphics graphics(hdc);

   // Use a generic monospace FontFamily object to create a Font object.
   Font genericMonoFont(FontFamily::GenericMonospace(), 16);

   // Draw text using the new font.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   graphics.DrawString(L"This is a generic monospace font", 32,
                       &genericMonoFont, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Font
Tasks and Examples
Using Text and Fonts


FontFamily::GenericSansSerif()

The GenericSansSerif method gets a FontFamily object that specifies a generic sans serif typeface.

static const FontFamily* GenericSansSerif(void);

Parameters

This method has no parameters.

Return Values

This method returns a pointer to a FontFamily object that specifies a generic sans serif typeface.

Example Code [C++]

The following example creates a Font object by using a generic sans serif FontFamily object and then uses that Font object to draw text.

VOID Example_GenericSansSerif(HDC hdc)
{
   Graphics graphics(hdc);

   // Use a generic sans serif FontFamily object to create a Font object.
   Font genericSansSerifFont(FontFamily::GenericSansSerif(), 16);

   // Draw text using the new font.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   graphics.DrawString(L"This is a generic sans serif font", 33,
                       &genericSansSerifFont, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Font
Tasks and Examples
Using Text and Fonts


FontFamily::GenericSerif()

The GenericSerif method gets a FontFamily object that represents a generic serif typeface.

static const FontFamily* GenericSerif(void);

Parameters

This method has no parameters.

Return Values

This method returns a pointer to a FontFamily object that represents a generic serif typeface.

Example Code [C++]

The following example creates a Font object by using a generic serif FontFamily object and then uses that font to draw text.

VOID Example_GenericSerif(HDC hdc)
{
   Graphics graphics(hdc);

   // Use a generic serif FontFamily object to create a Font object.
   Font genericSerifFont(FontFamily::GenericSerif(), 16);

   // Draw text using the new font.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   graphics.DrawString(L"This is a generic serif font", 28,
                       &genericSerifFont, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Font
Tasks and Examples
Using Text and Fonts


FontFamily::GetCellAscent(style)

The GetCellAscent method gets the cell ascent, in design units, of this font family for the specified style or style combination.

UINT16 GetCellAscent(
   INT style
) const;

Parameters

style
[in] Integer that specifies the style of the typeface. This value must be an element of the FontStyle enumeration or the result of a bitwise OR applied to two or more of these elements. For example, FontStyleBold | FontStyleUnderline | FontStyleStrikeout specifies a combination of the three styles.

Return Values

This method returns the cell ascent, in design units, of this font family for the specified style or style combination.

Example Code [C++]

The following example creates a FontFamily object, gets the cell ascent in design units, and outputs the value as text.

VOID Example_GetCellAscent(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a FontFamily object.
   FontFamily ascentFontFamily(L"arial");

   // Get the cell ascent of the font family in design units.
   int cellAscent = ascentFontFamily.GetCellAscent(FontStyleRegular);

   // Copy the cell ascent into a string and draw the string.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   Font       font(&ascentFontFamily, 16);
   WCHAR      string[100];
   swprintf(string,
            L"ascentFontFamily.GetCellAscent() returns %d.", cellAscent);
   graphics.DrawString(string, wcslen(string),
            &font, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetCellDescent, GetEmHeight, GetLineSpacing, FontStyle
Tasks and Examples
Obtaining Font Metrics


FontFamily::GetCellDescent(style)

The GetCellDescent method gets the cell descent, in design units, of this font family for the specified style or style combination.

UINT16 GetCellDescent(
  INT style
) const;

Parameters

style
[in] Integer that specifies the style of the typeface. This value must be an element of the FontStyle enumeration or the result of a bitwise OR applied to two or more of these elements. For example, FontStyleBold | FontStyleUnderline | FontStyleStrikeout specifies a combination of the three styles.

Return Values

This method returns the cell descent, in design units, of this font family for the specified style or style combination.

Example Code [C++]

The following example creates a FontFamily object, gets the cell descent in design units, and outputs the value as text.

VOID Example_GetCellDescent(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a FontFamily object.
   FontFamily descentFontFamily(L"arial");

   // Get the cell ascent of the font family in design units.
   int cellDescent = descentFontFamily.GetCellDescent(FontStyleRegular);

   // Copy the cell ascent into a string and draw the string.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   Font       font(&descentFontFamily, 16);
   WCHAR      string[100];
   swprintf(string,
            L"descentFontFamily.GetCellDescent() returns %d.", cellDescent);
   graphics.DrawString(string,
            wcslen(string), &font, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetCellDescent, GetEmHeight, GetLineSpacing, FontStyle
Tasks and Examples
Obtaining Font Metrics


FontFamily::GetEmHeight(style)

The GetEmHeight method gets the size (commonly called em height), in design units, of this font family.

UINT16 GetEmHeight(
  INT style
) const;

Parameters

style
[in] Integer that specifies the style of the typeface. This value must be an element of the FontStyle enumeration or the result of a bitwise OR applied to two or more of these elements. For example, FontStyleBold | FontStyleUnderline | FontStyleStrikeout specifies a combination of the three styles.

Return Values

This method returns the size, in design units, of this font family.

Example Code [C++]

The following example creates a FontFamily object, gets the em height in design units, and outputs the value as text.

VOID Example_GetEmHeight(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a FontFamily object.
   FontFamily emHeightFontFamily(L"arial");

   // Get the cell ascent of the font family in design units.
   int emHeight = emHeightFontFamily.GetEmHeight(FontStyleRegular);

   // Copy the cell ascent into a string and draw the string.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   Font       font(&emHeightFontFamily, 16);
   WCHAR      string[100];
   swprintf(string,
            L"emHeightFontFamily.GetEmHeight() returns %d.", emHeight);
   graphics.DrawString(string,
            wcslen(string), &font, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetCellDescent, GetEmHeight, GetLineSpacing, FontStyle
Tasks and Examples
Obtaining Font Metrics


FontFamily::GetFamilyName(name, language)

The GetFamilyName method gets the name of this font family.

Status GetFamilyName(
  WCHAR name[LF_FACESIZE],
  LANGID language
) const;

Parameters

name[LF_FACESIZE]
[out] Name of this font family.
language
[in] Optional. Sixteen-bit value that specifies the language to use. The default value is LANG_NEUTRAL, which is the user's default language.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

When specifying LANG_NEUTRAL as the language ID, it is common practice to pass just LANG_NEUTRAL as in the following example:

stat = FontFamily.GetFamilyName(name, LANG_NEUTRAL);

If you are specifying a language other than LANG_NEUTRAL, use MAKELANGID to create the language and sublanguage combination as in the following example:

LANGID language = MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL);

For a listing of the available languages and sublanguages, see Winnt.h.

Example Code [C++]

The following example creates a FontFamily object, gets the family name, and outputs the name as text.

VOID Example_GetFamilyName(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a FontFamily object.
   FontFamily nameFontFamily(L"arial");

   // Get the cell ascent of the font family in design units.
   WCHAR      familyName[100];
   nameFontFamily.GetFamilyName(familyName);

   // Copy the cell ascent into a string and draw the string.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   Font       font(&nameFontFamily, 16);
   graphics.DrawString(familyName,
                       wcslen(familyName), &font, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Language Identifiers
Tasks and Examples
Constructing Font Families and Fonts, Enumerating Installed Fonts


FontFamily::GetLastStatus()

The GetLastStatus method returns a value that indicates the nature of this FontFamily object's most recent method failure.

Status GetLastStatus(void) const;

Parameters

This method has no parameters.

Return Values

The GetLastStatus method returns an element of the Status enumeration.

If no methods invoked on this FontFamily object have failed since the previous call to GetLastStatus, then GetLastStatus returns Ok.

If at least one method invoked on this FontFamily object has failed since the previous call to GetLastStatus, then GetLastStatus returns a value that indicates the nature of the most recent failure.

Remarks

You can call GetLastStatus immediately after constructing a FontFamily object to determine whether the constructor succeeded.

The first time you call the GetLastStatus method of a FontFamily object, it returns Ok if the constructor succeeded and all methods invoked so far on the FontFamily object succeeded. Otherwise, it returns a value that indicates the nature of the most recent failure.

Example Code [C++]

The following example creates a FontFamily object and then checks the status of the call to create the object. If the call was successful, the example draws text.

VOID Example_GetLastStatus(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a FontFamily object.
   FontFamily myFontFamily(L"arial");

   // Check the status of the last call.
   Status status = myFontFamily.GetLastStatus();

   // If the last call succeeded, draw text.
   if (status ==Ok)
   {
       SolidBrush solidbrush(Color(255, 0, 0, 0));
       Font       font(&myFontFamily, 16);
       WCHAR      string[100] = L"status = Ok";
       graphics.DrawString(string,
                           wcslen(string), &font, PointF(0, 0), &solidbrush);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Status
Tasks and Examples
Constructing Font Families and Fonts


FontFamily::GetLineSpacing(style)

The GetLineSpacing method gets the distance between two consecutive lines of text drawn with fonts from this FontFamily object.

UINT16 GetLineSpacing(
  INT style
) const;

Parameters

style
[in] Integer that specifies the style of the typeface. This value must be an element of the FontStyle enumeration or the result of a bitwise OR applied to two or more of these elements. For example, FontStyleBold | FontStyleUnderline | FontStyleStrikeout specifies a combination of the three styles.

Return Values

This method returns the base distance between two consecutive lines.

Example Code [C++]

The following example creates a FontFamily object, gets the line spacing in design units, and outputs the value as text.

VOID Example_GetLineSpacing(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a FontFamily object.
   FontFamily lineSpacingFontFamily(L"arial");

   // Get the cell ascent of the font family in design units.
   int lineSpacing = lineSpacingFontFamily.GetLineSpacing(FontStyleRegular);

   // Copy the cell ascent into a string and draw the string.
   SolidBrush solidbrush(Color(255, 0, 0, 0));
   Font       font(&lineSpacingFontFamily, 16);
   WCHAR      string[100];
   swprintf(string, L"lineSpacingFontFamily.GetLineSpacing() returns %d.",
            lineSpacing);
   graphics.DrawString(string,
            wcslen(string), &font, PointF(0, 0), &solidbrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetCellAscent, GetCellDescent, GetEmHeight, FontStyle
Tasks and Examples
Obtaining Font Metrics


FontFamily::IsAvailable()

The IsAvailable method determines whether this FontFamily object was created successfully.

BOOL IsAvailable(void) const;

Parameters

This method has no parameters.

Return Values

If this FontFamily object was created successfully, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a FontFamily object. If the FontFamily object is created successfully, the example draws text.

VOID Example_IsAvailable(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a FontFamily object.
   FontFamily myFontFamily(L"arial");

   // Check to see if myFontFamily is available.
   BOOL isAvailable = myFontFamily.IsAvailable();

   // If myFontFamily is available, draw text.
   if (isAvailable)
   {
       SolidBrush solidbrush(Color(255, 0, 0, 0));
       Font       font(&myFontFamily, 16);
       WCHAR      string[100];
       swprintf(string, L"myFontFamily is available");
       graphics.DrawString(string,
                           wcslen(string), &font, PointF(0, 0), &solidbrush);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetLastStatus
Tasks and Examples
Constructing Font Families and Fonts


FontFamily::IsStyleAvailable(style)

The IsStyleAvailable method determines whether the specified style is available for this font family.

BOOL IsStyleAvailable(
  INT style
) const;

Parameters

style
[in] Integer that specifies the style of the typeface. This value must be an element of the FontStyle enumeration or the result of a bitwise OR applied to two or more of these elements. For example, FontStyleBold | FontStyleUnderline | FontStyleStrikeout specifies a combination of the three styles.

Return Values

If the style or combination of styles is available, this method returns TRUE; otherwise, it returns FALSE.

Remarks

This method returns a misleading result on some third-party fonts. For example, IsStyleAvailable(FontStyleUnderline) may return FALSE because it is really testing for a regular style font that also is an underlined font: (FontStyleRegular | FontStyleUnderline). If the font does not have a regular style, the IsStyleAvailable method returns FALSE.

Example Code [C++]

The following example creates a FontFamily object. If the font family has a regular style available, the example draws text.

VOID Example_IsStyleAvailable(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a FontFamily object.
   FontFamily myFontFamily(L"arial");

   // Check to see if the regular style is available.
   BOOL isStyleAvailable = myFontFamily.IsStyleAvailable(FontStyleRegular);

   // If regular style is available, draw text.
   if (isStyleAvailable)
   {
       SolidBrush solidbrush(Color(255, 0, 0, 0));
       Font       font(&myFontFamily, 16);
       WCHAR      string[100];
       swprintf(string, L"myFontFamily is available in regular style");
       graphics.DrawString(string,
                           wcslen(string), &font, PointF(0, 0), &solidbrush);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
FontStyle
Tasks and Examples
Creating a Private Font Collection


GdiplusBase Class

The GdiplusBase class provides memory allocation and deallocation for GDI+ objects. GdiplusBase serves as a base class for all other GDI+ classes, so you never need to create an instance of GdiplusBase.

Methods

Method | Description
operator delete | Deallocates memory for one GDI+ object.
operator delete[] | Deallocates memory for an array of GDI+ objects.
operator new | Allocates memory for one GDI+ object.
operator new[] | Allocates memory for an array of GDI+ objects.


GdiplusBase Methods

This topic lists the methods of the GdiplusBase class. For a complete class listing, see GdiplusBase Class.

  • operator delete(in_pVoid)
  • operator delete[](in_pVoid)
  • operator new(in_size)
  • operator new[](in_size)


GdiplusBase::operator delete(in_pVoid)

The operator delete method deallocates memory for one GDI+ object.

void
  operator delete(void* in_pVoid
);

Parameters

in_pVoid
[in] Pointer to the object to be deallocated.

Return Values

This method does not return a value.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbase.h; include Gdiplus.h.


GdiplusBase::operator delete[](in_pVoid)

The operator delete method deallocates memory for an array of GDI+ objects.

void
  operator delete[](void* in_pVoid
);

Parameters

in_pVoid
[in] Pointer to the array of objects to be deallocated.

Return Values

This method does not return a value.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbase.h; include Gdiplus.h.


GdiplusBase::operator new(in_size)

The operator new method allocates memory for one GDI+ object.

void*
  operator new(size_t in_size
);

Parameters

in_size
[in] Size of the object for which memory is to be allocated.

Return Values

This method returns a pointer to the object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbase.h; include Gdiplus.h.


GdiplusBase::operator new[](in_size)

The operator new method allocates memory for an array of GDI+ objects.

void*
  operator new[](size_t in_size
);

Parameters

in_size
[in] Size of the array of objects for which memory is to be allocated.

Return Values

This method returns a pointer to the array of objects.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbase.h; include Gdiplus.h.


Graphics Class

The Graphics class provides methods for drawing lines, curves, figures, images, and text. A Graphics object stores attributes of the display device and attributes of the items to be drawn.

Inheritance

GdiplusBase
Graphics

Constructors

Constructor | Description
Graphics | Overloaded. Creates and initializes a new Graphics object.

Methods

Method | Description
AddMetaFileComment | Adds a text comment to an existing metafile.
BeginContainer | Overloaded. Begins a new graphics container.
Clear | Clears a Graphics object to a specified color.
DrawArc | Overloaded. Draws an arc.
DrawBezier | Overloaded. Draws a Bézier spline.
DrawBeziers | Overloaded. Draws a sequence of connected Bézier splines.
DrawCachedBitmap | Draws a cached bitmap.
DrawClosedCurve | Overloaded. Draws a closed cardinal spline.
DrawCurve | Overloaded. Draws a cardinal spline.
DrawDriverString | Draws the specified Unicode or glyph text at a specified position.
DrawEllipse | Overloaded. Draws an ellipse.
DrawImage | Overloaded. Draws an image.
DrawLine | Overloaded. Draws a line.
DrawLines | Overloaded. Draws a sequence of connected lines.
DrawPath | Draws a sequence of lines and curves defined by a GraphicsPath object.
DrawPie | Overloaded. Draws a pie.
DrawPolygon | Overloaded. Draws a polygon.
DrawRectangle | Overloaded. Draws a rectangle.
DrawRectangles | Overloaded. Draws a sequence of rectangles.
DrawString | Overloaded. Draws a string.
EndContainer | Ends a graphics container.
EnumerateMetafile | Overloaded. Plays an EMF+ file to a graphics display device by using the enumeration interface.
ExcludeClip | Overloaded. Updates the interior part of the clipping region that does not overlap the rectangle.
FillClosedCurve | Overloaded. Fills the interior of a closed curve by using a brush.
FillEllipse | Overloaded. Fills the interior of an ellipse by using a brush.
FillPath | Fills the interior of a graphics path by using a brush.
FillPie | Overloaded. Fills the interior of a pie by using a brush.
FillPolygon | Overloaded. Fills the interior of a polygon by using a brush.
FillRectangle | Overloaded. Fills the interior of a rectangle by using a brush.
FillRectangles | Overloaded. Fills a series of rectangles by using a brush.
FillRegion | Fills the interior of a region by using a brush.
Flush | Flushes any pending rendering.
FromHDC | Overloaded. Creates a Graphics object that is associated with a specified device context.
FromHWND | Creates a Graphics object that is associated with a specified window.
FromImage | Creates a Graphics object that is associated with a specified Image object.
GetClip | Gets the clipping region.
GetClipBounds | Overloaded. Gets the bounding rectangle for the clipping region.
GetCompositingMode | Gets the compositing mode.
GetCompositingQuality | Gets the compositing quality.
GetDpiX | Gets the horizontal dots per inch.
GetDpiY | Gets the vertical dots per inch.
GetHalftonePalette | Gets a Windows all purpose halftone palette.
GetHDC | Gets a handle to the device context that is associated with this Graphics object.
GetInterpolationMode | Gets the interpolation mode.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetNearestColor | Gets the color that is nearest to a specified color.
GetPageScale | Gets the page transformation's scaling factor.
GetPageUnit | Gets the page transformation's unit of measure.
GetPixelOffsetMode | Gets the pixel offset mode.
GetRenderingOrigin | Gets the rendering origin.
GetSmoothingMode | Gets the smoothing mode, which influences how the edges of lines and curves are rendered.
GetTextContrast | Gets the contrast value used for antialiasing text.
GetTextRenderingHint | Gets the text rendering mode.
GetTransform | Gets the world transformation matrix.
GetVisibleClipBounds | Overloaded. Gets a rectangle that bounds the visible clipping region.
IntersectClip | Overloaded. Updates the clipping region with the intersection of its interior and the specified rectangle or region.
IsClipEmpty | Determines whether the clipping region is empty.
IsVisible | Overloaded. Checks whether a point is inside the visible clipping region.
IsVisibleClipEmpty | Determines whether the visible clipping region of a Graphics object is empty.
MeasureCharacterRanges | Gets a set of regions each of which bounds a range of character positions within a string.
MeasureDriverString | Measures the bounding box for the text string.
MeasureString | Overloaded. Measures the string in the specified font and layout rectangle.
MultiplyTransform | Updates the world transformation matrix with the product of itself and another matrix.
ReleaseHDC | Releases a device context handle that was obtained by a previous call to GetHDC.
ResetClip | Sets the clipping region to infinity.
ResetTransform | Replaces the world transformation matrix with the identity matrix.
Restore | Sets the state of this Graphics object to the state stored by a previous call to the Save method.
RotateTransform | Updates the world transformation matrix with the product of itself and a rotation matrix.
Save | Saves the current state of this Graphics object.
ScaleTransform | Updates the world transformation matrix with the product of itself and a scaling matrix.
SetClip | Overloaded. Sets the clipping region.
SetCompositingMode | Sets the compositing mode.
SetCompositingQuality | Sets the compositing quality.
SetInterpolationMode | Sets the interpolation mode.
SetPageScale | Sets the page transformation's scaling factor.
SetPageUnit | Sets the page transformation's unit of measure.
SetPixelOffsetMode | Sets the pixel offset mode.
SetRenderingOrigin | Sets the rendering origin.
SetSmoothingMode | Sets the smoothing mode, which influences how the edges of lines and curves are rendered.
SetTextContrast | Sets the contrast value for antialiasing text.
SetTextRenderingHint | Sets the rendering mode for the text to some level of antialiasing.
SetTransform | Sets the elements of the world transformation matrix.
TransformPoints | Converts an array of points from one coordinate space to another.
TranslateClip | Overloaded. Translates the clipping region.
TranslateTransform | Updates the world transformation matrix with the product of itself and a translation matrix.
~Graphics | Graphics object destructor.


Graphics Constructors

This topic lists the constructors of the Graphics class. For a complete class listing, see Graphics Class.

  • Graphics(hdc)
  • Graphics(hdc, hdevice)
  • Graphics(hwnd, icm)
  • Graphics(image)


Graphics::Graphics(hdc)

Creates a Graphics object that is associated with a specified device context.

Graphics(
  HDC hdc
);

Parameters

hdc
[in] Handle to a device context that will be associated with the new Graphics object.

Remarks

When you use this constructor to create a Graphics object, make sure that the Graphics object is deleted or goes out of scope before the device context is released.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Graphics Constructors
Tasks and Examples
Getting Started
Concepts
Changes in the Programming Model


Graphics::Graphics(hdc, hdevice)

Creates a Graphics object that is associated with a specified device context and a specified device.

Graphics(
  HDC hdc,
  HANDLE hdevice
);

Parameters

hdc
[in] Handle to a device context that will be associated with the new Graphics object.
hdevice
[in] Handle to a device that will be associated with the new Graphics object.

Remarks

When you use this constructor to create a Graphics object, make sure that the Graphics object is deleted or goes out of scope before the device context is released.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Graphics Constructors
Tasks and Examples
Optimizing Printing by Providing a Printer Handle
Concepts
Changes in the Programming Model


Graphics::Graphics(hwnd, icm)

Creates a Graphics object that is associated with a specified window.

Graphics(
  HWND hwnd,
  BOOL icm
);

Parameters

hwnd
[in] Handle to a window that will be associated with the new Graphics object.
icm
[in] Optional. Boolean value that specifies whether the new Graphics object applies color adjustment according to the International Color Consortium (ICC) profile associated with the display device. TRUE specifies that color adjustment is applied, and FALSE specifies that color adjustment is not applied. The default value is FALSE.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Graphics Constructors
Tasks and Examples
Getting Started
Concepts
Changes in the Programming Model


Graphics::Graphics(image)

Creates a Graphics object that is associated with an Image object.

Graphics(
  Image* image
);

Parameters

image
[in] Pointer to an Image object that will be associated with the new Graphics object.

Remarks

This constructor fails if the Image object is based on a metafile that was opened for reading. The Image::Image(file) and Metafile::Metafile(file) constructors open a metafile for reading. To open a metafile for recording, use a Metafile constructor that receives a device context handle.

This constructor also fails if the image uses one of the following pixel formats:

  • PixelFormatUndefined
  • PixelFormatDontCare
  • PixelFormat1bppIndexed
  • PixelFormat4bppIndexed
  • PixelFormat8bppIndexed
  • PixelFormat16bppGrayScale
  • PixelFormat16bppARGB1555

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Graphics Constructors, Image
Tasks and Examples
Getting Started
Concepts
Changes in the Programming Model


Graphics Methods

This topic lists the methods of the Graphics class. For a complete class listing, see Graphics Class.

  • AddMetaFileComment(data, sizeData)
  • BeginContainer()
  • BeginContainer(Rect& dstrect, Rect& srcrect, Unit unit)
  • BeginContainer(RectF& dstrect, RectF& srcrect, Unit unit)
  • Clear(color)
  • DrawArc(Pen* pen, Rect& rect, REAL startAngle, REAL sweepAngle)
  • DrawArc(Pen* pen, RectF& rect, REAL startAngle, REAL sweepAngle)
  • DrawArc(Pen* pen, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
  • DrawArc(Pen* pen, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)
  • DrawBezier(Pen* pen, Point& pt1, Point& pt2, Point& pt3, Point& pt4)
  • DrawBezier(Pen* pen, PointF& pt1, PointF& pt2, PointF& pt3, PointF& pt4)
  • DrawBezier(Pen* pen, INT x1, INT y1, INT x2, INT y2, INT x3, INT y3, INT x4, INT y4)
  • DrawBezier(Pen* pen, REAL x1, REAL y1, REAL x2, REAL y2, REAL x3, REAL y3, REAL x4, REAL y4)
  • DrawBeziers(Pen* pen, Point* points, INT count)
  • DrawBeziers(Pen* pen, PointF* points, INT count)
  • DrawCachedBitmap(cb, x, y)
  • DrawClosedCurve(Pen* pen, Point* points, INT count)
  • DrawClosedCurve(Pen* pen, PointF* points, INT count)
  • DrawClosedCurve(Pen* pen, Point* points, INT count, REAL tension)
  • DrawClosedCurve(Pen* pen, PointF* points, INT count, REAL tension)
  • DrawCurve(Pen* pen, Point* points, INT count)
  • DrawCurve(Pen* pen, PointF* points, INT count)
  • DrawCurve(Pen* pen, Point* points, INT count, INT offset, INT numberOfSegments, REAL tension)
  • DrawCurve(Pen* pen, PointF* points, INT count, INT offset, INT numberOfSegments, REAL tension)
  • DrawCurve(Pen* pen, Point* points, INT count, REAL tension)
  • DrawCurve(Pen* pen, PointF* points, INT count, REAL tension)
  • DrawDriverString(text, length, font, brush, positions, flags, matrix)
  • DrawEllipse(Pen* pen, Rect& rect)
  • DrawEllipse(Pen* pen, RectF& rect)
  • DrawEllipse(Pen* pen, INT x, INT y, INT width, INT height)
  • DrawEllipse(Pen* pen, REAL x, REAL y, REAL width, REAL height)
  • DrawImage(Image* image, Point* destPoints, INT count)
  • DrawImage(Image* image, PointF* destPoints, INT count)
  • DrawImage(Image* image, Point* destPoints, INT count, INT srcx, INT srcy, INT srcwidth, INT srcheight, Unit srcUnit, ImageAttributes* imageAttributes, DrawImageAbort callback, Void* callbackData)
  • DrawImage(Image* image, PointF* destPoints, INT count, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, Unit srcUnit, ImageAttributes* imageAttributes, DrawImageAbort callback, VOID* callbackData)
  • DrawImage(Image* image, Rect& destRect, INT srcx, INT srcy, INT srcwidth, INT srcheight, Unit srcUnit, ImageAttributes* imageAttributes, DrawImageAbort callback, VOID* callbackData)
  • DrawImage(Image* image, RectF& destRect, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, Unit srcUnit, ImageAttributes* imageAttributes, DrawImageAbort callback, VOID* callbackData)
  • DrawImage(Image* image, Point& point)
  • DrawImage(Image* image, PointF& point)
  • DrawImage(Image* image, Rect& rect)
  • DrawImage(Image* image, RectF& rect)
  • DrawImage(Image* image, INT x, INT y)
  • DrawImage(Image* image, REAL x, REAL y)
  • DrawImage(Image* image, INT x, INT y, INT srcx, INT srcy, INT srcwidth, INT srcheight, Unit srcUnit)
  • DrawImage(Image* image, REAL x, REAL y, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, Unit srcUnit)
  • DrawImage(Image* image, INT x, INT y, INT width, INT height)
  • DrawImage(Image* image, REAL x, REAL y, REAL width, REAL height)
  • DrawLine(Pen* pen, Point& pt1, Point& pt2)
  • DrawLine(Pen* pen, PointF& pt1, PointF& pt2)
  • DrawLine(Pen* pen, INT x1, INT y1, INT x2, INT y2)
  • DrawLine(Pen* pen, REAL x1, REAL y1, REAL x2, REAL y2)
  • DrawLines(Pen* pen, Point* points, INT count)
  • DrawLines(Pen* pen, PointF* points, INT count)
  • DrawPath(pen, path)
  • DrawPie(Pen* pen, Rect& rect, REAL startAngle, REAL sweepAngle)
  • DrawPie(Pen* pen, RectF& rect, REAL startAngle, REAL sweepAngle)
  • DrawPie(Pen* pen, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
  • DrawPie(Pen* pen, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)
  • DrawPolygon(Pen* pen, Point* points, INT count)
  • DrawPolygon(Pen* pen, PointF* points, INT count)
  • DrawRectangle(Pen* pen, Rect& rect)
  • DrawRectangle(Pen* pen, RectF& rect)
  • DrawRectangle(Pen* pen, INT x, INT y, INT width, INT height)
  • DrawRectangle(Pen* pen, REAL x, REAL y, REAL width, REAL height)
  • DrawRectangles(Pen* pen, Rect* rects, INT count)
  • DrawRectangles(Pen* pen, RectF* rects, INT count)
  • DrawString(string, length, font, layoutRect, stringFormat, brush)
  • DrawString(string, length, font, origin, brush)
  • DrawString(string, length, font, origin, stringFormat, brush)
  • EndContainer(state)
  • EnumerateMetafile(Metafile* metafile, Point& destPoint, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, PointF& destPoint, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, Point& destPoint, Rect& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, PointF& destPoint, RectF& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, Point* destPoints, INT count, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, PointF* destPoints, INT count, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, Point* destPoints, INT count, Rect& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, PointF* destPoints, INT count, RectF& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, Rect& destRect, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, RectF& destRect, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, Rect& destRect, Rect& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, RectF& destRect, RectF& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • ExcludeClip(Rect& rect)
  • ExcludeClip(RectF& rect)
  • ExcludeClip(region)
  • FillClosedCurve(Brush* brush, Point* points, INT count)
  • FillClosedCurve(Brush* brush, PointF* points, INT count)
  • FillClosedCurve(Brush* brush, Point* points, INT count, FillMode fillMode, REAL tension)
  • FillClosedCurve(Brush* brush, PointF* points, INT count, FillMode fillMode, REAL tension)
  • FillEllipse(Brush* brush, Rect& rect)
  • FillEllipse(Brush* brush, RectF& rect)
  • FillEllipse(Brush* brush, INT x, INT y, INT width, INT height)
  • FillEllipse(Brush* brush, REAL x, REAL y, REAL width, REAL height)
  • FillPath(brush, path)
  • FillPie(Brush* brush, Rect& rect, REAL startAngle, REAL sweepAngle)
  • FillPie(Brush* brush, RectF& rect, REAL startAngle, REAL sweepAngle)
  • FillPie(Brush* brush, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
  • FillPie(Brush* brush, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)
  • FillPolygon(Brush* brush, Point* points, INT count)
  • FillPolygon(Brush* brush, PointF* points, INT count)
  • FillPolygon(Brush* brush, Point* points, INT count, FillMode fillMode)
  • FillPolygon(Brush* brush, PointF* points, INT count, FillMode fillMode)
  • FillRectangle(Brush* brush, Rect& rect)
  • FillRectangle(Brush* brush, RectF& rect)
  • FillRectangle(Brush* brush, INT x, INT y, INT width, INT height)
  • FillRectangle(Brush* brush, REAL x, REAL y, REAL width, REAL height)
  • FillRectangles(Brush* brush, Rect* rects, INT count)
  • FillRectangles(Brush* brush, RectF* rects, INT count)
  • FillRegion(brush, region)
  • Flush(intention)
  • FromHDC(hdc)
  • FromHDC(hdc, hdevice)
  • FromHWND(hwnd, icm)
  • FromImage(image)
  • GetClip(region)
  • GetClipBounds(Rect* rect)
  • GetClipBounds(RectF* rect)
  • GetCompositingMode()
  • GetCompositingQuality()
  • GetDpiX()
  • GetDpiY()
  • GetHalftonePalette()
  • GetHDC()
  • GetInterpolationMode()
  • GetLastStatus()
  • GetNearestColor(color)
  • GetPageScale()
  • GetPageUnit()
  • GetPixelOffsetMode()
  • GetRenderingOrigin(x, y)
  • GetSmoothingMode()
  • GetTextContrast()
  • GetTextRenderingHint()
  • GetTransform(matrix)
  • GetVisibleClipBounds(Rect* rect)
  • GetVisibleClipBounds(RectF* rect)
  • IntersectClip(Rect& rect)
  • IntersectClip(RectF& rect)
  • IntersectClip(region)
  • IsClipEmpty()
  • IsVisible(Point& point)
  • IsVisible(PointF& point)
  • IsVisible(Rect& rect)
  • IsVisible(RectF& rect)
  • IsVisible(INT x, INT y)
  • IsVisible(REAL x, REAL y)
  • IsVisible(INT x, INT y, INT width, INT height)
  • IsVisible(REAL x, REAL y, REAL width, REAL height)
  • IsVisibleClipEmpty()
  • MeasureCharacterRanges(string, length, font, layoutRect, stringFormat, regionCount, regions)
  • MeasureDriverString(text, length, font, positions, flags, matrix, boundingBox)
  • MeasureString(string, length, font, layoutRect, boundingBox)
  • MeasureString(string, length, font, layoutRect, stringFormat, boundingBox, codepointsFitted, linesFilled)
  • MeasureString(string, length, font, layoutRectSize, stringFormat, size, codepointsFitted, linesFilled)
  • MeasureString(string, length, font, origin, boundingBox)
  • MeasureString(string, length, font, origin, stringFormat, boundingBox)
  • MultiplyTransform(matrix, order)
  • ReleaseHDC(hdc)
  • ResetClip()
  • ResetTransform()
  • Restore(gstate)
  • RotateTransform(angle, order)
  • Save()
  • ScaleTransform(sx, sy, order)
  • SetClip(g, combineMode)
  • SetClip(hRgn, combineMode)
  • SetClip(path, combineMode)
  • SetClip(Rect& rect, CombineMode combineMode)
  • SetClip(RectF& rect, CombineMode combineMode)
  • SetClip(region, combineMode)
  • SetCompositingMode(compositingMode)
  • SetCompositingQuality(compositingQuality)
  • SetInterpolationMode(interpolationMode)
  • SetPageScale(scale)
  • SetPageUnit(unit)
  • SetPixelOffsetMode(pixelOffsetMode)
  • SetRenderingOrigin(x, y)
  • SetSmoothingMode(smoothingMode)
  • SetTextContrast(contrast)
  • SetTextRenderingHint(newMode)
  • SetTransform(matrix)
  • TransformPoints(destSpace, srcSpace, pts, count)
  • TranslateClip(INT dx, INT dy)
  • TranslateClip(REAL dx, REAL dy)
  • TranslateTransform(dx, dy, order)


Graphics::AddMetafileComment(data, sizeData)

The AddMetafileComment method adds a text comment to an existing metafile.

Status AddMetafileComment(
  const BYTE* data,
  UINT sizeData
);

Parameters

data
[in] Pointer to a buffer that contains the comment.
sizeData
[in] Integer that specifies the number of bytes in the value of the data parameter.

Return Values

If the method is successful, it returns Ok, which is a element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object, adds a comment to the metafile, and then draws the metafile.

VOID Example_AddMetafileComment(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Metafile object.
   Metafile metaFile(L"sampleMeta.emf", hdc);

   {
   //Create a Graphics object to record metaFile.
   Graphics metaGraphics(&metaFile);

   //Draw a rectangle in metaFile.
   metaGraphics.DrawRectangle(&Pen(Color::Black, 5), 0, 0, 100, 100);

   //Create a comment, and add it to metaFile.
   BYTE  metaComment[4] = {(BYTE)'T', (BYTE)'e', (BYTE)'s', (BYTE)'t'};
   BYTE* pMetaComment = metaComment;
   metaGraphics.AddMetafileComment(pMetaComment, 4);
   }

   //Draw metaFile.
   graphics.DrawImage(&metaFile, Point(0, 0));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
MetafileHeader, Metafile
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


Graphics::BeginContainer Methods

This topic lists the BeginContainer methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • BeginContainer()
  • BeginContainer(Rect& dstrect, Rect& srcrect, Unit unit)
  • BeginContainer(RectF& dstrect, RectF& srcrect, Unit unit)


Graphics::BeginContainer()

The BeginContainer method begins a new graphics container.

GraphicsContainer BeginContainer(void)

Parameters

This method has no parameters.

Return Values

This method returns a value that identifies the container.

Remarks

Use this method to create nested graphics containers. Graphics containers are used to retain graphics state, such as transformations, clipping regions, and various rendering properties.

The BeginContainer method returns a value of type GraphicsContainer. When you have finished using a container, pass that value to the EndContainer method. The GraphicsContainer data type is defined in Gdiplusenums.h.

When you call the BeginContainer method of a Graphics object, an information block that holds the state of the Graphics object is put on a stack. The BeginContainer method returns a value that identifies that information block. When you pass the identifying value to the EndContainer method, the information block is removed from the stack and is used to restore the Graphics object to the state it was in at the time of the BeginContainer call.

Containers can be nested; that is, you can call the BeginContainer method several times before you call the EndContainer method. Each time you call the BeginContainer method, an information block is put on the stack, and you receive an identifier for the information block. When you pass one of those identifiers to the EndContainer method, the Graphics object is returned to the state it was in at the time of the BeginContainer call that returned that particular identifier. The information block placed on the stack by that BeginContainer call is removed from the stack, and all information blocks placed on that stack after that BeginContainer call are also removed.

Calls to the Save method place information blocks on the same stack as calls to the BeginContainer method. Just as an EndContainer call is paired with a BeginContainer call, a Restore call is paired with a Save call.

Caution When you call EndContainer, all information blocks placed on the stack (by Save or by BeginContainer) after the corresponding call to BeginContainer are removed from the stack. Likewise, when you call Restore, all information blocks placed on the stack (by Save or by BeginContainer) after the corresponding call to Save are removed from the stack.

For more information about graphics containers, see Nested Graphics Containers.

Example Code [C++]

The following example sets a clipping region for a Graphics object and begins a graphics container. It then sets an additional clipping region for the container and draws rectangles that demonstrate the effective clipping region inside the container.

VOID Example_BeginContainer(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the clipping region for the Graphics object.
   graphics.SetClip(Rect(10, 10, 150, 150));

   // Begin a graphics container.
   GraphicsContainer container = graphics.BeginContainer();

   // Set an additional clipping region for the container.
   graphics.SetClip(Rect(100, 50, 100, 75));

   // Fill a red rectangle in the container.
   SolidBrush redBrush(Color(255, 255, 0, 0));
   graphics.FillRectangle(&redBrush, 0, 0, 400, 400);

   // End the container, and fill the same rectangle with blue.
   graphics.EndContainer(container);
   SolidBrush blueBrush(Color(128, 0, 0, 255));
   graphics.FillRectangle(&blueBrush, 0, 0, 400, 400);

   // Set the clipping region to infinite, and draw the outlines
   // of the two previous clipping regions.
   graphics.ResetClip();
   Pen blackPen(Color(255, 0, 0, 0), 2.0f);
   graphics.DrawRectangle(&blackPen, 10, 10, 150, 150);
   graphics.DrawRectangle(&blackPen, 100, 50, 100, 75);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
EndContainer, Restore, Save
Tasks and Examples
Using Graphics Containers
Concepts
Graphics Containers


Graphics::BeginContainer(Rect& dstrect, Rect& srcrect, Unit unit)

The BeginContainer method begins a new graphics container.

GraphicsContainer BeginContainer(
  const Rect& dstrect,
  const Rect& srcrect,
  Unit unit
);

Parameters

dstrect
[in] Reference to a rectangle that, together with srcrect, specifies a transformation for the container.
srcrect
[in] Reference to a rectangle that, together with dstrect, specifies a transformation for the container.
unit
[in] Unit of measure for the container.

Return Values

This method returns a value that identifies the container.

Remarks

Use this method to create nested graphics containers. Graphics containers are used to retain graphics state, such as transformations, clipping regions, and various rendering properties.

The BeginContainer method returns a value of type GraphicsContainer. When you have finished using a container, pass that value to the EndContainer method. The GraphicsContainer data type is defined in Gdiplusenums.h.

The dstrect and srcrect parameters specify a transformation. It is the transformation that, when applied to srcrect, results in dstrect.

When you call the BeginContainer method of a Graphics object, an information block that holds the state of the Graphics object is put on a stack. The BeginContainer method returns a value that identifies that information block. When you pass the identifying value to the EndContainer method, the information block is removed from the stack and is used to restore the Graphics object to the state it was in at the time of the BeginContainer call.

Containers can be nested; that is, you can call the BeginContainer method several times before you call the EndContainer method. Each time you call the BeginContainer method, an information block is put on the stack, and you receive an identifier for the information block. When you pass one of those identifiers to the EndContainer method, the Graphics object is returned to the state it was in at the time of the BeginContainer call that returned that particular identifier. The information block placed on the stack by that BeginContainer call is removed from the stack, and all information blocks placed on that stack after that BeginContainer call are also removed.

Calls to the Save method place information blocks on the same stack as calls to the BeginContainer method. Just as an EndContainer call is paired with a BeginContainer call, a Restore call is paired with a Save call.

Caution When you call EndContainer, all information blocks placed on the stack (by Save or by BeginContainer) after the corresponding call to BeginContainer are removed from the stack. Likewise, when you call Restore, all information blocks placed on the stack (by Save or by BeginContainer) after the corresponding call to Save are removed from the stack.

For more information about graphics containers, see Nested Graphics Containers.

Example Code [C++]

The following example calls the BeginContainer method to create a graphics container. The code specifies a transformation for the container by passing two rectangles to the BeginContainer method. The code calls Graphics::FillEllipse twice: once inside the container and once outside the container (after the call to EndContainer).

VOID Example_BeginContainer2(HDC hdc)
{
   Graphics graphics(hdc);

   // Define a translation and scale transformation for the container.
   Rect srcRect(0, 0, 200, 100);
   Rect destRect(100, 100, 200, 200);

   // Create a graphics container with a (100, 100) translation
   // and (1, 2) scale.
   GraphicsContainer container;
   container = graphics.BeginContainer(destRect, srcRect, UnitPixel);

   // Fill an ellipse in the container.
   SolidBrush redBrush(Color(255, 255, 0, 0));
   graphics.FillEllipse(&redBrush, 0, 0, 100, 60);

   // End the container.
   graphics.EndContainer(container);

   // Fill the same ellipse outside the container.
   SolidBrush blueBrush(Color(255, 0, 0, 255));
   graphics.FillEllipse(&blueBrush, 0, 0, 100, 60);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
EndContainer, Restore, Save
Tasks and Examples
Using Graphics Containers
Concepts
Graphics Containers


Graphics::BeginContainer(RectF& dstrect, RectF& srcrect, Unit unit)

The BeginContainer method begins a new graphics container.

GraphicsContainer BeginContainer(
  const RectF& dstrect,
  const RectF& srcrect,
  Unit unit
);

Parameters

dstrect
[in] Reference to a rectangle that, together with srcrect, specifies a transformation for the container.
srcrect
[in] Reference to a rectangle that, together with dstrect, specifies a transformation for the container.
unit
[in] Unit of measure for the container.

Return Values

This method returns a value that identifies the container.

Remarks

Use this method to create nested graphics containers. Graphics containers are used to retain graphics state, such as transformations, clipping regions, and various rendering properties.

The BeginContainer method returns a value of type GraphicsContainer. When you have finished using a container, pass that value to the EndContainer method. The GraphicsContainer data type is defined in Gdiplusenums.h.

The dstrect and srcrect parameters specify a transformation. It is the transformation that, when applied to srcrect, results in dstrect.

When you call the BeginContainer method of a Graphics object, an information block that holds the state of the Graphics object is put on a stack. The BeginContainer method returns a value that identifies that information block. When you pass the identifying value to the EndContainer method, the information block is removed from the stack and is used to restore the Graphics object to the state it was in at the time of the BeginContainer call.

Containers can be nested; that is, you can call the BeginContainer method several times before you call the EndContainer method. Each time you call the BeginContainer method, an information block is put on the stack, and you receive an identifier for the information block. When you pass one of those identifiers to the EndContainer method, the Graphics object is returned to the state it was in at the time of the BeginContainer call that returned that particular identifier. The information block placed on the stack by that BeginContainer call is removed from the stack, and all information blocks placed on that stack after that BeginContainer call are also removed.

Calls to the Save method place information blocks on the same stack as calls to the BeginContainer method. Just as an EndContainer call is paired with a BeginContainer call, a Restore call is paired with a Save call.

Caution When you call EndContainer, all information blocks placed on the stack (by Save or by BeginContainer) after the corresponding call to BeginContainer are removed from the stack. Likewise, when you call Restore, all information blocks placed on the stack (by Save or by BeginContainer) after the corresponding call to Save are removed from the stack.

For more information about graphics containers, see Nested Graphics Containers.

Example Code [C++]

The following example calls the BeginContainer method to create a graphics container. The code specifies a transformation for the container by passing two rectangles to the BeginContainer method. The code calls Graphics::FillEllipse twice: once inside the container and once outside the container (after the call to EndContainer).

VOID Example_BeginContainer3(HDC hdc)
{
   Graphics graphics(hdc);

   // Define a translation and scale transform for the container.
   RectF srcRect(0, 0, 200, 100);
   RectF destRect(100, 100, 200, 200);

   // Create a graphics container with a (100, 100) translation
   // and (1, 2) scale.
   GraphicsContainer container;
   container = graphics.BeginContainer(destRect, srcRect, UnitPixel);

   // Fill a rectangle in the container.
   SolidBrush redBrush(Color(255, 255, 0, 0));
   graphics.FillEllipse(&redBrush, 0, 0, 100, 60);

   // End the container.
   graphics.EndContainer(container);

   // Fill a rectangle outside the container.
   SolidBrush blueBrush(Color(255, 0, 0, 255));
   graphics.FillEllipse(&blueBrush, 0, 0, 100, 60);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
EndContainer, Restore, Save
Tasks and Examples
Using Graphics Containers
Concepts
Graphics Containers


Graphics::Clear(color)

The Clear method clears a Graphics object to a specified color.

Status Clear(
  const Color& color
);

Parameters

color
[in] Reference to the Color object that specifies the color to paint the background.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Graphics object and a Color object. The code then clears the Graphics object to a color specified by the Color object.

VOID Example_Clear(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Color object.
   Color blueColor(255, 0, 0, 255);

   // Clear the screen with a blue background.
   graphics.Clear(blueColor);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, DrawRectangle


Graphics::DrawArc Methods

This topic lists the DrawArc methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • DrawArc(Pen* pen, Rect& rect, REAL startAngle, REAL sweepAngle)
  • DrawArc(Pen* pen, RectF& rect, REAL startAngle, REAL sweepAngle)
  • DrawArc(Pen* pen, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
  • DrawArc(Pen* pen, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)


Graphics::DrawArc(Pen* pen, Rect& rect, REAL startAngle, REAL sweepAngle)

The DrawArc method draws an arc. The arc is part of an ellipse.

Status DrawArc(
  const Pen* pen,
  const Rect& rect,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

pen
[in] Pointer to a pen that is used to draw the arc.
rect
[in] Reference to the rectangle that bounds the ellipse that contains the arc.
startAngle
[in] Real number that specifies the angle between the x-axis and the starting point of the arc.
sweepAngle
[in] Real number that specifies the angle between the starting and ending points of the arc.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a 90-degree arc.

VOID Example_DrawArc(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the arc.
   Pen redPen(Color::Red, 3);
   Rect ellipseRect(0, 0, 200, 100);
   REAL startAngle = 0.0f;
   REAL sweepAngle = 90.0f;

   // Draw the arc.
   graphics.DrawArc(&redPen, ellipseRect, startAngle, sweepAngle);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawArc Methods, DrawEllipse Methods, Pen, Rect
Tasks and Examples
Creating Figures from Lines, Curves, and Shapes
Concepts
Ellipses and Arcs


Graphics::DrawArc(Pen* pen, RectF& rect, REAL startAngle, REAL sweepAngle)

The DrawArc method draws an arc. The arc is part of an ellipse.

Status DrawArc(
  const Pen* pen,
  const RectF& rect,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

pen
[in] Pointer to a pen that is used to draw the arc.
rect
[in] Reference to the rectangle that bounds the ellipse that contains the arc.
startAngle
[in] Real number that specifies the angle between the x-axis and the starting point of the arc.
sweepAngle
[in] Real number that specifies the angle between the starting and ending points of the arc.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a 90-degree arc.

VOID Example_DrawArc2(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the arc.
   Pen redPen(Color::Red, 3);
   RectF ellipseRect(0, 0, 200, 100);
   REAL startAngle = 0.0f;
   REAL sweepAngle = 90.0f;

   // Draw the arc.
   graphics.DrawArc(&redPen, ellipseRect, startAngle, sweepAngle);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawArc Methods, DrawEllipse Methods, Pen, RectF
Tasks and Examples
Creating Figures from Lines, Curves, and Shapes
Concepts
Ellipses and Arcs


Graphics::DrawArc(Pen* pen, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)

The DrawArc method draws an arc. The arc is part of an ellipse.

Status DrawArc(
  const Pen* pen,
  INT x,
  INT y,
  INT width,
  INT height,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

pen
[in] Pointer to a pen that is used to draw the arc.
x
[in] Integer that specifies the x-coordinate of the upper-left corner of the bounding rectangle for the ellipse that contains the arc.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the bounding rectangle for the ellipse that contains the arc.
width
[in] Integer that specifies the width of the ellipse that contains the arc.
height
[in] Integer that specifies the height of the ellipse that contains the arc.
startAngle
[in] Real number that specifies the angle between the x-axis and the starting point of the arc.
sweepAngle
[in] Real number that specifies the angle between the starting and ending points of the arc.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a 90-degree arc.

VOID Example_DrawArc3(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the arc.
   Pen redPen(Color::Red, 3);
   int x = 0;
   int y = 0;
   int width = 200;
   int height = 100;
   REAL startAngle = 0.0f;
   REAL sweepAngle = 90.0f;

   // Draw the arc.
   graphics.DrawArc(&redPen, x, y, width, height, startAngle, sweepAngle);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawArc Methods, DrawEllipse Methods, Pen, Rect
Tasks and Examples
Creating Figures from Lines, Curves, and Shapes
Concepts
Ellipses and Arcs


Graphics::DrawArc(Pen* pen, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)

The DrawArc method draws an arc. The arc is part of an ellipse.

Status DrawArc(
  const Pen* pen,
  REAL x,
  REAL y,
  REAL width,
  REAL height,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

pen
[in] Pointer to a pen that is used to draw the arc.
x
[in] Real number that specifies the x-coordinate of the upper-left corner of the bounding rectangle for the ellipse that contains the arc.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the bounding rectangle for the ellipse that contains the arc.
width
[in] Real number that specifies the width of the ellipse that contains the arc.
height
[in] Real number that specifies the height of the ellipse that contains the arc.
startAngle
[in] Real number that specifies the angle between the x-axis and the starting point of the arc.
sweepAngle
[in] Real number that specifies the angle between the starting and ending points of the arc.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a 90-degree arc.

VOID Example_DrawArc4(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the arc.
   Pen redPen(Color::Red, 3);
   REAL x = 0;
   REAL y = 0;
   REAL width = 200.0f;
   REAL height = 100.0f;
   REAL startAngle = 0.0f;
   REAL sweepAngle = 90.0f;

   // Draw the arc.
   graphics.DrawArc(&redPen, x, y, width, height, startAngle, sweepAngle);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawArc Methods, DrawEllipse Methods, Pen, Rect
Tasks and Examples
Creating Figures from Lines, Curves, and Shapes
Concepts
Ellipses and Arcs


Graphics::DrawBezier Methods

This topic lists the DrawBezier methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • DrawBezier(Pen* pen, Point& pt1, Point& pt2, Point& pt3, Point& pt4)
  • DrawBezier(Pen* pen, PointF& pt1, PointF& pt2, PointF& pt3, PointF& pt4)
  • DrawBezier(Pen* pen, INT x1, INT y1, INT x2, INT y2, INT x3, INT y3, INT x4, INT y4)
  • DrawBezier(Pen* pen, REAL x1, REAL y1, REAL x2, REAL y2, REAL x3, REAL y3, REAL x4, REAL y4)


Graphics::DrawBezier(Pen* pen, Point& pt1, Point& pt2, Point& pt3, Point& pt4)

The DrawBezier method draws a Bézier spline.

Status DrawBezier(
  const Pen* pen,
  const Point& pt1,
  const Point& pt2,
  const Point& pt3,
  const Point& pt4
);

Parameters

pen
[in] Pointer to a pen that is used to draw the Bézier spline.
pt1
[in] Reference to the starting point of the Bézier spline.
pt2
[in] Reference to the first control point of the Bézier spline.
pt3
[in] Reference to the second control point of the Bézier spline.
pt4
[in] Reference to the ending point of the Bézier spline.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A Bézier spline does not pass through its control points. The control points act as magnets, pulling the curve in certain directions to influence the way the Bézier spline bends.

Example Code [C++]

The following example draws a Bézier curve.

VOID Example_DrawBezier(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the pen and curve points.
   Pen greenPen(Color::Green);
   Point startPoint(100, 100);
   Point controlPoint1(200, 10);
   Point controlPoint2(350, 50);
   Point endPoint(500, 100);

   //Draw the curve.
   graphics.DrawBezier(&greenPen, startPoint, controlPoint1, controlPoint2, endPoint);

   //Draw the end points and control points.
   graphics.FillEllipse(&SolidBrush(Color::Red), 100, 100, 10, 10);
   graphics.FillEllipse(&SolidBrush(Color::Red), 500, 100, 10, 10);
   graphics.FillEllipse(&SolidBrush(Color::Blue), 200, 10, 10, 10);
   graphics.FillEllipse(&SolidBrush(Color::Blue), 350, 50, 10, 10);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawBezier Methods, DrawBeziers Methods, Pen, Point
Tasks and Examples
Drawing Bézier Splines
Concepts
Bézier Splines


Graphics::DrawBezier(Pen* pen, PointF& pt1, PointF& pt2, PointF& pt3, PointF& pt4)

The DrawBezier method draws a Bézier spline.

Status DrawBezier(
  const Pen* pen,
  const PointF& pt1,
  const PointF& pt2,
  const PointF& pt3,
  const PointF& pt4
);

Parameters

pen
[in] Pointer to a pen that is used to draw the Bézier spline.
pt1
[in] Reference to the starting point of the Bézier spline.
pt2
[in] Reference to the first control point of the Bézier spline.
pt3
[in] Reference to the second control point of the Bézier spline.
pt4
[in] Reference to the ending point of the Bézier spline.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A Bézier spline does not pass through its control points. The control points act as magnets, pulling the curve in certain directions to influence the way the Bézier spline bends.

Example Code [C++]

The following example draws a Bézier curve.

VOID Example_DrawBezier2(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the pen and curve points.
   Pen greenPen(Color::Green);
   PointF startPoint(100.0f, 100.0f);
   PointF controlPoint1(200.0f, 10.0f);
   PointF controlPoint2(350.0f, 50.0f);
   PointF endPoint(500.0f, 100.0f);

   //Draw the curve.
   graphics.DrawBezier(&greenPen, startPoint, controlPoint1, controlPoint2, endPoint);

   //Draw the end points and control points.
   graphics.FillEllipse(&SolidBrush(Color::Red), 100, 100, 10, 10);
   graphics.FillEllipse(&SolidBrush(Color::Red), 500, 100, 10, 10);
   graphics.FillEllipse(&SolidBrush(Color::Blue), 200, 10, 10, 10);
   graphics.FillEllipse(&SolidBrush(Color::Blue), 350, 50, 10, 10);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawBezier Methods, DrawBeziers Methods, Pen, PointF
Tasks and Examples
Drawing Bézier Splines
Concepts
Bézier Splines


Graphics::DrawBezier(Pen* pen, INT x1, INT y1, INT x2, INT y2, INT x3, INT y3, INT x4, INT y4)

The DrawBezier method draws a Bézier spline.

Status DrawBezier(
  const Pen* pen,
  INT x1,
  INT y1,
  INT x2,
  INT y2,
  INT x3,
  INT y3,
  INT x4,
  INT y4
);

Parameters

pen
[in] Pointer to a pen that is used to draw the Bézier spline.
x1
[in] Integer that specifies the x-coordinate of the starting point of the Bézier spline.
y1
[in] Integer that specifies the y-coordinate of the starting point of the Bézier spline.
x2
[in] Integer that specifies the x-coordinate of the first control point of the Bézier spline.
y2
[in] Integer that specifies the y-coordinate of the first control point of the Bézier spline
x3
[in] Integer that specifies the x-coordinate of the second control point of the Bézier spline.
y3
[in] Integer that specifies the y-coordinate of the second control point of the Bézier spline.
x4
[in] Integer that specifies the x-coordinate of the ending point of the Bézier spline.
y4
[in] Integer that specifies the y-coordinate of the ending point of the Bézier spline

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A Bézier spline does not pass through its control points. The control points act as magnets, pulling the curve in certain directions to influence the way the Bézier spline bends.

Example Code [C++]

The following example draws a Bézier curve.

VOID Example_DrawBezier3(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the pen and curve points.
   Pen greenPen(Color::Green);
   int startPointx = 100;
   int startPointy = 100;
   int ctrlPoint1x = 200;
   int ctrlPoint1y = 10;
   int ctrlPoint2x = 350;
   int ctrlPoint2y = 50;
   int endPointx = 500;
   int endPointy = 100;

   //Draw the curve.
   graphics.DrawBezier(
   &greenPen,
   startPointx,
   startPointy,
   ctrlPoint1x,
   ctrlPoint1y,
   ctrlPoint2x,
   ctrlPoint2y,
   endPointx,
   endPointy);

   //Draw the end points and control points.
   graphics.FillEllipse(&SolidBrush(Color::Red), 100, 100, 10, 10);
   graphics.FillEllipse(&SolidBrush(Color::Red), 500, 100, 10, 10);
   graphics.FillEllipse(&SolidBrush(Color::Blue), 200, 10, 10, 10);
   graphics.FillEllipse(&SolidBrush(Color::Blue), 350, 50, 10, 10);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawBezier Methods, DrawBeziers Methods, Pen
Tasks and Examples
Drawing Bézier Splines
Concepts
Bézier Splines


Graphics::DrawBezier(Pen* pen, REAL x1, REAL y1, REAL x2, REAL y2, REAL x3, REAL y3, REAL x4, REAL y4)

The DrawBezier method draws a Bézier spline.

Status DrawBezier(
  const Pen* pen,
  REAL x1,
  REAL y1,
  REAL x2,
  REAL y2,
  REAL x3,
  REAL y3,
  REAL x4,
  REAL y4
);

Parameters

pen
[in] Pointer to a pen that is used to draw the Bézier spline.
x1
[in] Real number that specifies the x-coordinate of the starting point of the Bézier spline.
y1
[in] Real number that specifies the y-coordinate of the starting point of the Bézier spline.
x2
[in] Real number that specifies the x-coordinate of the first control point of the Bézier spline.
y2
[in] Real number that specifies the y-coordinate of the first control point of the Bézier spline
x3
[in] Real number that specifies the x-coordinate of the second control point of the Bézier spline.
y3
[in] Real number that specifies the y-coordinate of the second control point of the Bézier spline.
x4
[in] Real number that specifies the x-coordinate of the ending point of the Bézier spline.
y4
[in] Real number that specifies the y-coordinate of the ending point of the Bézier spline

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A Bézier spline does not pass through its control points. The control points act as magnets, pulling the curve in certain directions to influence the way the Bézier spline bends.

Example Code [C++]

The following example draws a Bézier curve.

VOID Example_DrawBezier4(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the pen and curve points.
   Pen greenPen(Color::Green);
   REAL startPointx = 100.0f;
   REAL startPointy = 100.0f;
   REAL ctrlPoint1x = 200.0f;
   REAL ctrlPoint1y = 10.0f;
   REAL ctrlPoint2x = 350.0f;
   REAL ctrlPoint2y = 50.0f;
   REAL endPointx = 500.0f;
   REAL endPointy = 100.0f;

   //Draw the curve.
   graphics.DrawBezier(
   &greenPen,
   startPointx,
   startPointy,
   ctrlPoint1x,
   ctrlPoint1y,
   ctrlPoint2x,
   ctrlPoint2y,
   endPointx,
   endPointy);

   //Draw the end points and control points.
   graphics.FillEllipse(&SolidBrush(Color::Red), 100, 100, 10, 10);
   graphics.FillEllipse(&SolidBrush(Color::Red), 500, 100, 10, 10);
   graphics.FillEllipse(&SolidBrush(Color::Blue), 200, 10, 10, 10);
   graphics.FillEllipse(&SolidBrush(Color::Blue), 350, 50, 10, 10);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawBezier Methods, DrawBeziers Methods, Pen
Tasks and Examples
Drawing Bézier Splines
Concepts
Bézier Splines


Graphics::DrawBeziers Methods

This topic lists the DrawBeziers methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • DrawBeziers(Pen* pen, Point* points, INT count)
  • DrawBeziers(Pen* pen, PointF* points, INT count)


Graphics::DrawBeziers(Pen* pen, Point* points, INT count)

The DrawBeziers method draws a sequence of connected Bézier splines.

Status DrawBeziers(
  const Pen* pen,
  const Point* points,
  INT count
);

Parameters

pen
[in] Pointer to a pen that is used to draw the Bézier splines.
points
[in] Pointer to an array of Point objects that specify the starting, ending, and control points of the Bézier splines. The ending coordinate of one Bézier spline is the starting coordinate of the next Bézier spline.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A Bézier spline does not pass through its control points. The control points act as magnets, pulling the curve in certain directions to influence the way the Bézier splines bend.

Example Code [C++]

The following example draws a pair of Bézier curves.

VOID Example_DrawBeziers(HDC hdc)
{
   Graphics graphics(hdc);

   // Define a Pen object and an array of Point objects.
   Pen greenPen(Color::Green, 3);
   Point startPoint(100, 100);
   Point ctrlPoint1(200, 50);
   Point ctrlPoint2(400, 10);
   Point endPoint1(500, 100);
   Point ctrlPoint3(600, 200);
   Point ctrlPoint4(700, 400);
   Point endPoint2(500, 500);

   Point curvePoints[7] = {
   startPoint,
   ctrlPoint1,
   ctrlPoint2,
   endPoint1,
   ctrlPoint3,
   ctrlPoint4,
   endPoint2};

   Point* pcurvePoints = curvePoints;

   // Draw the Bezier curves.
   graphics.DrawBeziers(&greenPen, curvePoints, 7);

   //Draw the control and end points.
   SolidBrush redBrush(Color::Red);
   graphics.FillEllipse(&redBrush, Rect(100, 100, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(500, 100, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(500, 500, 10, 10));
   SolidBrush blueBrush(Color::Blue);
   graphics.FillEllipse(&blueBrush, Rect(200, 50, 10, 10));
   graphics.FillEllipse(&blueBrush, Rect(400, 10, 10, 10));
   graphics.FillEllipse(&blueBrush, Rect(600, 200, 10, 10));
   graphics.FillEllipse(&blueBrush, Rect(700, 400, 10, 10));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawBezier Methods, DrawBeziers Methods, Pen, Point
Tasks and Examples
Drawing Bézier Splines
Concepts
Bézier Splines


Graphics::DrawBeziers(Pen* pen, PointF* points, INT count)

The DrawBeziers method draws a sequence of connected Bézier splines.

Status DrawBeziers(
  const Pen* pen,
  const PointF* points,
  INT count
);

Parameters

pen
[in] Pointer to a pen that is used to draw the Bézier splines.
points
[in] Pointer to an array of PointF objects that specify the starting, ending, and control points of the Bézier splines.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A Bézier spline does not pass through its control points. The control points act as magnets, pulling the curve in certain directions to influence the way a Bézier spline bends. Each Bézier spline requires a starting point and an ending point. Each ending point is the starting point for the next Bézier spline.

Example Code [C++]

The following example draws a pair of Bézier curves.

VOID Example_DrawBeziers2(HDC hdc)
{
   Graphics graphics(hdc);

   // Define a Pen object and an array of PointF objects.
   Pen greenPen(Color::Green, 3);
   PointF startPoint(100.0f, 100.0f);
   PointF ctrlPoint1(200.0f, 50.0f);
   PointF ctrlPoint2(400.0f, 10.0f);
   PointF endPoint1(500.0f, 100.0f);
   PointF ctrlPoint3(600.0f, 200.0f);
   PointF ctrlPoint4(700.0f, 400.0f);
   PointF endPoint2(500.0f, 500.0f);

   PointF curvePoints[7] = {
   startPoint,
   ctrlPoint1,
   ctrlPoint2,
   endPoint1,
   ctrlPoint3,
   ctrlPoint4,
   endPoint2};

   PointF* pcurvePoints = curvePoints;

   // Draw the Bezier curves.
   graphics.DrawBeziers(&greenPen, curvePoints, 7);

   //Draw the control and end points.
   SolidBrush redBrush(Color::Red);
   graphics.FillEllipse(&redBrush, Rect(100, 100, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(500, 100, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(500, 500, 10, 10));
   SolidBrush blueBrush(Color::Blue);
   graphics.FillEllipse(&blueBrush, Rect(200, 50, 10, 10));
   graphics.FillEllipse(&blueBrush, Rect(400, 10, 10, 10));
   graphics.FillEllipse(&blueBrush, Rect(600, 200, 10, 10));
   graphics.FillEllipse(&blueBrush, Rect(700, 400, 10, 10));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawBezier Methods, DrawBeziers Methods, Pen, PointF
Tasks and Examples
Drawing Bézier Splines
Concepts
Bézier Splines


Graphics::DrawCachedBitmap(cb, x, y)

The DrawCachedBitmap method draws the image stored in a CachedBitmap object.

Status DrawCachedBitmap(
  CachedBitmap* cb,
  INT x,
  INT y
);

Parameters

cb
[in] Pointer to a CachedBitmap object that contains the image to be drawn.
x
[in] Integer that specifies the x-coordinate of the upper-left corner of the image.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the image.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A CachedBitmap object stores an image in a format that is optimized for a particular display screen. You cannot draw a cached bitmap to a printer or to a metafile.

Cached bitmaps will not work with any transformations other than translation.

When you construct a CachedBitmap object, you must pass the address of a Graphics object to the constructor. If the screen associated with that Graphics object has its bit depth changed after the cached bitmap is constructed, then the DrawCachedBitmap method will fail, and you should reconstruct the cached bitmap. Alternatively, you can hook the display change notification message and reconstruct the cached bitmap at that time.

Example Code [C++]

The following example calls DrawCachedBitmap to draw the image stored in a CachedBitmap object.

VOID Example_DrawCachedBitmap(HDC hdc)
{
   Graphics graphics(hdc);

   // Create Bitmap object.
   Bitmap bitmap(L"Climber.jpg");

   // Use the Bitmap object to create a CachedBitmap object.
   CachedBitmap cachedBitmap(&bitmap, &graphics);

   // Draw the cached bitmap.
   graphics.DrawCachedBitmap(&cachedBitmap, 20, 10);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Bitmap
Tasks and Examples
Using a Cached Bitmap to Improve Performance
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawClosedCurve Methods

This topic lists the DrawClosedCurve methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • DrawClosedCurve(Pen* pen, Point* points, INT count)
  • DrawClosedCurve(Pen* pen, PointF* points, INT count)
  • DrawClosedCurve(Pen* pen, Point* points, INT count, REAL tension)
  • DrawClosedCurve(Pen* pen, PointF* points, INT count, REAL tension)


Graphics::DrawClosedCurve(Pen* pen, Point* points, INT count)

The DrawClosedCurve method draws a closed cardinal spline.

Status DrawClosedCurve(
  const Pen* pen,
  const Point* points,
  INT count
);

Parameters

pen
[in] Pointer to a pen that is used to draw the closed cardinal spline.
points
[in] Pointer to an array of Point objects that specify the coordinates of the closed cardinal spline. The array of Point objects must contain a minimum of three elements.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

In a closed cardinal spline, the curve continues through the last point in the points array and connects with the first point in the array.

Example Code [C++]

The following example draws a closed cardinal spline.

VOID Example_DrawClosedCurve(HDC hdc)
{
   Graphics graphics(hdc);

   // Define a Pen object and an array of Point objects.
   Pen greenPen(Color::Green, 3);
   Point point1(100, 100);
   Point point2(200, 50);
   Point point3(400, 10);
   Point point4(500, 100);
   Point point5(600, 200);
   Point point6(700, 400);
   Point point7(500, 500);

   Point curvePoints[7] = {
   point1,
   point2,
   point3,
   point4,
   point5,
   point6,
   point7};

   Point* pcurvePoints = curvePoints;

   // Draw the closed curve.
   graphics.DrawClosedCurve(&greenPen, curvePoints, 7);

   //Draw the points in the curve.
   SolidBrush redBrush(Color::Red);
   graphics.FillEllipse(&redBrush, Rect(95, 95, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(495, 95, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(495, 495, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(195, 45, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(395, 5, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(595, 195, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(695, 395, 10, 10));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawCurve Methods, FillClosedCurve Methods, Pen, Point
Tasks and Examples
Drawing Cardinal Splines
Concepts
Cardinal Splines


Graphics::DrawClosedCurve(Pen* pen, PointF* points, INT count)

The DrawClosedCurve method draws a closed cardinal spline.

Status DrawClosedCurve(
  const Pen* pen,
  const PointF* points,
  INT count
);

Parameters

pen
[in] Pointer to a pen that is used to draw the closed cardinal spline.
points
[in] Pointer to an array of PointF objects that specify the coordinates of the closed cardinal spline. The array of PointF objects must contain a minimum of three elements.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Each ending point is the starting point for the next cardinal spline. In a closed cardinal spline, the curve continues through the last point in the points array and connects with the first point in the array.

Example Code [C++]

The following example draws a closed cardinal spline.

VOID Example_DrawClosedCurve3(HDC hdc)
{
   Graphics graphics(hdc);

   // Define a Pen object and an array of PointF objects.
   Pen greenPen(Color::Green, 3);
   PointF point1(100.0f, 100.0f);
   PointF point2(200.0f, 50.0f);
   PointF point3(400.0f, 10.0f);
   PointF point4(500.0f, 100.0f);
   PointF point5(600.0f, 200.0f);
   PointF point6(700.0f, 400.0f);
   PointF point7(500.0f, 500.0f);

   PointF curvePoints[7] = {
   point1,
   point2,
   point3,
   point4,
   point5,
   point6,
   point7};

   PointF* pcurvePoints = curvePoints;

   // Draw the closed curve.
   graphics.DrawClosedCurve(&greenPen, curvePoints, 7);

   //Draw the points in the curve.
   SolidBrush redBrush(Color::Red);
   graphics.FillEllipse(&redBrush, Rect(95, 95, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(495, 95, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(495, 495, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(195, 45, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(395, 5, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(595, 195, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(695, 395, 10, 10));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawCurve Methods, FillClosedCurve Methods, Pen, PointF
Tasks and Examples
Drawing Cardinal Splines
Concepts
Cardinal Splines


Graphics::DrawClosedCurve(Pen* pen, Point* points, INT count, REAL tension)

The DrawClosedCurve method draws a closed cardinal spline.

Status DrawClosedCurve(
  const Pen* pen,
  const Point* points,
  INT count,
  REAL tension
);

Parameters

pen
[in] Pointer to a pen that is used to draw the closed cardinal spline.
points
[in] Pointer to an array of Point objects that specify the coordinates of the closed cardinal spline. The array of Point objects must contain a minimum of three elements.
count
[in] Integer that specifies the number of elements in the points array.
tension
[in] Real number that specifies how tightly the curve bends through the coordinates of the closed cardinal spline.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Each ending point is the starting point for the next cardinal spline. In a closed cardinal spline, the curve continues through the last point in the points array and connects with the first point in the array.

Example Code [C++]

The following example draws a closed cardinal spline.

VOID Example_DrawClosedCurve2(HDC hdc)
{
   Graphics graphics(hdc);

   // Define a Pen object and an array of Point objects.
   Pen greenPen(Color::Green, 3);
   Point point1(100, 100);
   Point point2(200, 50);
   Point point3(400, 10);
   Point point4(500, 100);
   Point point5(600, 200);
   Point point6(700, 400);
   Point point7(500, 500);

   Point curvePoints[7] = {
   point1,
   point2,
   point3,
   point4,
   point5,
   point6,
   point7};

   Point* pcurvePoints = curvePoints;

   // Draw the closed curve.
   graphics.DrawClosedCurve(&greenPen, curvePoints, 7, 1.0);

   //Draw the points in the curve.
   SolidBrush redBrush(Color::Red);
   graphics.FillEllipse(&redBrush, Rect(95, 95, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(495, 95, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(495, 495, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(195, 45, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(395, 5, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(595, 195, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(695, 395, 10, 10));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawCurve Methods, FillClosedCurve Methods, Pen, Point
Tasks and Examples
Drawing Cardinal Splines
Concepts
Cardinal Splines


Graphics::DrawClosedCurve(Pen* pen, PointF* points, INT count, REAL tension)

The DrawClosedCurve method draws a closed cardinal spline.

Status DrawClosedCurve(
  const Pen* pen,
  const PointF* points,
  INT count,
  REAL tension
);

Parameters

pen
[in] Pointer to a pen that is used to draw the closed cardinal spline.
points
[in] Pointer to an array of PointF objects that specify the coordinates of the closed cardinal spline. The array of PointF objects must contain a minimum of three elements.
count
[in] Integer that specifies the number of elements in the points array.
tension
[in] Real number that specifies how tightly the curve bends though the coordinates of the closed cardinal spline.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Each ending point is the starting point for the next cardinal spline. In a closed cardinal spline, the curve continues through the last point in the points array and connects with the first point in the array.

Example Code [C++]

The following example draws a closed cardinal spline.

VOID Example_DrawClosedCurve4(HDC hdc)
{
   Graphics graphics(hdc);

   // Define a Pen object and an array of PointF objects.
   Pen greenPen(Color::Green, 3);
   PointF point1(100.0f, 100.0f);
   PointF point2(200.0f, 50.0f);
   PointF point3(400.0f, 10.0f);
   PointF point4(500.0f, 100.0f);
   PointF point5(600.0f, 200.0f);
   PointF point6(700.0f, 400.0f);
   PointF point7(500.0f, 500.0f);

   PointF curvePoints[7] = {
   point1,
   point2,
   point3,
   point4,
   point5,
   point6,
   point7};

   PointF* pcurvePoints = curvePoints;

   // Draw the closed curve.
   graphics.DrawClosedCurve(&greenPen, curvePoints, 7, 1.0);

   //Draw the points in the curve.
   SolidBrush redBrush(Color::Red);
   graphics.FillEllipse(&redBrush, Rect(95, 95, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(495, 95, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(495, 495, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(195, 45, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(395, 5, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(595, 195, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(695, 395, 10, 10));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawCurve Methods, FillClosedCurve Methods, Pen, PointF
Tasks and Examples
Drawing Cardinal Splines
Concepts
Cardinal Splines


Graphics::DrawCurve Methods

This topic lists the DrawCurve methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • DrawCurve(Pen* pen, Point* points, INT count)
  • DrawCurve(Pen* pen, PointF* points, INT count)
  • DrawCurve(Pen* pen, Point* points, INT count, INT offset, INT numberOfSegments, REAL tension)
  • DrawCurve(Pen* pen, PointF* points, INT count, INT offset, INT numberOfSegments, REAL tension)
  • DrawCurve(Pen* pen, Point* points, INT count, REAL tension)
  • DrawCurve(Pen* pen, PointF* points, INT count, REAL tension)


Graphics::DrawCurve(Pen* pen, Point* points, INT count)

The DrawCurve method draws a cardinal spline.

Status DrawCurve(
  const Pen* pen,
  const Point* points,
  INT count
);

Parameters

pen
[in] Pointer to a pen that is used to draw the cardinal spline.
points
[in] Pointer to an array of Point objects that specify the coordinates that the cardinal spline passes through.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A segment is defined as a curve that connects two consecutive points in the cardinal spline. The ending point of each segment is the starting point for the next.

Example Code [C++]

The following example draws a cardinal spline.

VOID Example_DrawCurve(HDC hdc)
{
   Graphics graphics(hdc);

   // Define a Pen object and an array of Point objects.
   Pen greenPen(Color::Green, 3);
   Point point1(100, 100);
   Point point2(200, 50);
   Point point3(400, 10);
   Point point4(500, 100);

   Point curvePoints[4] = {
   point1,
   point2,
   point3,
   point4};

   Point* pcurvePoints = curvePoints;

   // Draw the curve.
   graphics.DrawCurve(&greenPen, curvePoints, 4);

   //Draw the points in the curve.
   SolidBrush redBrush(Color::Red);
   graphics.FillEllipse(&redBrush, Rect(95, 95, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(195, 45, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(395, 5, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(495, 95, 10, 10));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawClosedCurve Methods, Pen, Point
Tasks and Examples
Drawing Cardinal Splines
Concepts
Cardinal Splines


Graphics::DrawCurve(Pen* pen, PointF* points, INT count)

The DrawCurve method draws a cardinal spline.

Status DrawCurve(
  const Pen* pen,
  const PointF* points,
  INT count
);

Parameters

pen
[in] Pointer to a pen used to draw the cardinal spline.
points
[in] Pointer to an array of PointF objects that specify the coordinates that the cardinal spline passes through.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A segment is defined as a curve that connects two consecutive points in the cardinal spline. The ending point of each segment is the starting point for the next.

Example Code [C++]

The following example draws a cardinal spline.

VOID Example_DrawCurve4(HDC hdc)
{
   Graphics graphics(hdc);

   // Define a Pen object and an array of Point objects.
   Pen greenPen(Color::Green, 3);
   PointF point1(100.0f, 100.0f);
   PointF point2(200.0f, 50.0f);
   PointF point3(400.0f, 10.0f);
   PointF point4(500.0f, 100.0f);

   PointF curvePoints[4] = {
   point1,
   point2,
   point3,
   point4};

   PointF* pcurvePoints = curvePoints;

   // Draw the curve.
   graphics.DrawCurve(&greenPen, curvePoints, 4);

   //Draw the points in the curve.
   SolidBrush redBrush(Color::Red);
   graphics.FillEllipse(&redBrush, Rect(95, 95, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(195, 45, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(395, 5, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(495, 95, 10, 10));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawClosedCurve Methods, Pen, Point
Tasks and Examples
Drawing Cardinal Splines
Concepts
Cardinal Splines


Graphics::DrawCurve(Pen* pen, Point* points, INT count, INT offset, INT numberOfSegments, REAL tension)

The DrawCurve method draws a cardinal spline.

Status DrawCurve(
  const Pen* pen,
  const Point* points,
  INT count,
  INT offset,
  INT numberOfSegments,
  REAL tension
);

Parameters

pen
[in] Pointer to a pen that is used to draw the cardinal spline.
points
[in] Pointer to an array of Point objects that specify the coordinates that the cardinal spline passes through.
count
[in] Integer that specifies the number of elements in the points array.
offset
[in] Integer that specifies the element in the points array that specifies the point at which the cardinal spline begins.
numberOfSegments
[in] Integer that specifies the number of segments in the cardinal spline.
tension
[in] Real number that specifies how tightly the curve bends through the coordinates of the cardinal spline.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A segment is defined as a curve that connects two consecutive points in the cardinal spline. The ending point of each segment is the starting point for the next. The numberOfSegments parameter must not be greater than the count parameter minus the offset parameter plus one.

Example Code [C++]

The following example draws a cardinal spline.

VOID Example_DrawCurve2(HDC hdc)
{
   Graphics graphics(hdc);

   // Define a Pen object and an array of Point objects.
   Pen greenPen(Color::Green, 3);
   Point point1(100, 100);
   Point point2(200, 50);
   Point point3(400, 10);
   Point point4(500, 100);

   Point curvePoints[4] = {
   point1,
   point2,
   point3,
   point4};

   Point* pcurvePoints = curvePoints;

   // Specify offset, number of segments to draw, and tension.
   int offset = 1;
   int segments = 2;
   REAL tension = 1.0;

   // Draw the curve.
   graphics.DrawCurve(&greenPen, curvePoints, 4, offset, segments, tension);

   //Draw the points in the curve.
   SolidBrush redBrush(Color::Red);
   graphics.FillEllipse(&redBrush, Rect(95, 95, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(195, 45, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(395, 5, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(495, 95, 10, 10));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawClosedCurve Methods, Pen, Point
Tasks and Examples
Drawing Cardinal Splines
Concepts
Cardinal Splines


Graphics::DrawCurve(Pen* pen, PointF* points, INT count, INT offset, INT numberOfSegments, REAL tension)

The DrawCurve method draws a cardinal spline.

Status DrawCurve(
  const Pen* pen,
  const PointF* points,
  INT count,
  INT offset,
  INT numberOfSegments,
  REAL tension
);

Parameters

pen
[in] Pointer to a pen that is used to draw the cardinal spline.
points
[in] Pointer to an array of PointF objects that specify the coordinates that the cardinal spline passes through.
count
[in] Integer that specifies the number of elements in the points array.
offset
[in] Integer that specifies the element in the points array that specifies the point at which the cardinal spline begins.
numberOfSegments
[in] Integer that specifies the number of segments in the cardinal spline.
tension
[in] Real number that specifies how tightly the curve bends through the coordinates of the cardinal spline.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A segment is defined as a curve that connects two consecutive points in the cardinal spline. The ending point of each segment is the starting point for the next. The numberOfSegments parameter must not be greater than the count parameter minus the offset parameter plus one.

Example Code [C++]

The following example draws a cardinal spline.

VOID Example_DrawCurve5(HDC hdc)
{
   Graphics graphics(hdc);

   // Define a Pen object and an array of PointF objects.
   Pen greenPen(Color::Green, 3);
   PointF point1(100.0f, 100.0f);
   PointF point2(200.0f, 50.0f);
   PointF point3(400.0f, 10.0f);
   PointF point4(500.0f, 100.0f);

   PointF curvePoints[4] = {
   point1,
   point2,
   point3,
   point4};

   PointF* pcurvePoints = curvePoints;

   // Specify offset, number of segments to draw, and tension.
   int offset = 1;
   int segments = 2;
   REAL tension = 1.0f;

   // Draw the curve.
   graphics.DrawCurve(&greenPen, curvePoints, 4, offset, segments, tension);

   //Draw the points in the curve.
   SolidBrush redBrush(Color::Red);
   graphics.FillEllipse(&redBrush, Rect(95, 95, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(195, 45, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(395, 5, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(495, 95, 10, 10));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawClosedCurve Methods, Pen, Point
Tasks and Examples
Drawing Cardinal Splines
Concepts
Cardinal Splines


Graphics::DrawCurve(Pen* pen, Point* points, INT count, REAL tension)

The DrawCurve method draws a cardinal spline.

Status DrawCurve(
  const Pen* pen,
  const Point* points,
  INT count,
  REAL tension
);

Parameters

pen
[in] Pointer to a pen that is used to draw the cardinal spline.
points
[in] Pointer to an array of Point objects that specify the coordinates that the cardinal spline passes through.
count
[in] Integer that specifies the number of elements in the points array.
tension
[in] Real number that specifies how tightly the curve bends through the coordinates of the cardinal spline.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A segment is defined as a curve that connects two consecutive points in the cardinal spline. The ending point of each segment is the starting point for the next.

Example Code [C++]

The following example draws a cardinal spline.

VOID Example_DrawCurve3(HDC hdc)
{
   Graphics graphics(hdc);

   // Define a Pen object and an array of Point objects.
   Pen greenPen(Color::Green, 3);
   Point point1(100, 100);
   Point point2(200, 50);
   Point point3(400, 10);
   Point point4(500, 100);

   Point curvePoints[4] = {
   point1,
   point2,
   point3,
   point4};

   Point* pcurvePoints = curvePoints;

   // Draw the curve.
   graphics.DrawCurve(&greenPen, curvePoints, 4, 1.0);

   //Draw the points in the curve.
   SolidBrush redBrush(Color::Red);
   graphics.FillEllipse(&redBrush, Rect(95, 95, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(195, 45, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(395, 5, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(495, 95, 10, 10));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawClosedCurve Methods, Pen, Point
Tasks and Examples
Drawing Cardinal Splines
Concepts
Cardinal Splines


Graphics::DrawCurve(Pen* pen, PointF* points, INT count, REAL tension)

The DrawCurve method draws a cardinal spline.

Status DrawCurve(
  const Pen* pen,
  const PointF* points,
  INT count,
  REAL tension
);

Parameters

pen
[in] Pointer to a pen that is used to draw the cardinal spline.
points
[in] Pointer to an array of PointF objects that specify the coordinates that the cardinal spline passes through.
count
[in] Integer that specifies the number of elements in the points array.
tension
[in] Real number that specifies how tightly the curve bends through the coordinates of the cardinal spline.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A segment is defined as a curve that connects two consecutive points in the cardinal spline. The ending point of each segment is the starting point for the next.

Example Code [C++]

The following example draws a cardinal spline.

VOID Example_DrawCurve6(HDC hdc)
{
   Graphics graphics(hdc);

   // Define a Pen object and an array of PointF objects.
   Pen greenPen(Color::Green, 3);
   PointF point1(100.0f, 100.0f);
   PointF point2(200.0f, 50.0f);
   PointF point3(400.0f, 10.0f);
   PointF point4(500.0f, 100.0f);

   PointF curvePoints[4] = {
   point1,
   point2,
   point3,
   point4};

   PointF* pcurvePoints = curvePoints;

   // Draw the curve.
   graphics.DrawCurve(&greenPen, curvePoints, 4, 1.0);

   //Draw the points in the curve.
   SolidBrush redBrush(Color::Red);
   graphics.FillEllipse(&redBrush, Rect(95, 95, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(195, 45, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(395, 5, 10, 10));
   graphics.FillEllipse(&redBrush, Rect(495, 95, 10, 10));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawClosedCurve Methods, Pen, PointF
Tasks and Examples
Drawing Cardinal Splines
Concepts
Cardinal Splines


Graphics::DrawDriverString(text, length, font, brush, positions, flags, matrix)

The DrawDriverString method draws characters at the specified positions. The method gives the client complete control over the appearance of text. The method assumes that the client has already set up the format and layout to be applied.

Status DrawDriverString(
  const UINT16* text,
  INT length,
  const Font* font,
  const Brush* brush,
  const PointF* positions,
  INT flags,
  const Matrix* matrix
);

Parameters

text
[in] Pointer to an array of 16-bit values. If the DriverStringOptionsCmapLookup flag is set, each value specifies a Unicode character to be displayed. Otherwise, each value specifies an index to a font glyph that defines a character to be displayed.
length
[in] Integer that specifies the number of values in the text array. The length parameter can be set to –1 if the string is null terminated.
font
[in] Pointer to a Font object that specifies the family name, size, and style of the font that is to be applied to the string.
brush
[in] Pointer to a Brush object that is used to fill the string.
positions
[in] If the DriverStringOptionsRealizedAdvance flag is set, positions is a pointer to a PointF object that specifies the position of the first glyph. Otherwise, positions is an array of PointF objects, each of which specifies the origin of an individual glyph.
flags
[in] Integer that specifies the options for the appearance of the string. This value must be an element of the DriverStringOptions enumeration or the result of a bitwise OR applied to two or more of these elements.
matrix
[in] Pointer to a Matrix object that specifies the transformation matrix to apply to each value in the text array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

This method does not support the handling of complex scripts and assumes that the client has set up all text layout in some other way. This method is useful for creating owner-drawn menu items. The client should use the DrawString method for general purposes.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Brush, DriverStringOptions, Font, Matrix, PointF, DrawString Methods, MeasureDriverString
Concepts
Owner-Drawn Menu Items


Graphics::DrawEllipse Methods

This topic lists the DrawEllipse methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • DrawEllipse(Pen* pen, Rect& rect)
  • DrawEllipse(Pen* pen, RectF& rect)
  • DrawEllipse(Pen* pen, INT x, INT y, INT width, INT height)
  • DrawEllipse(Pen* pen, REAL x, REAL y, REAL width, REAL height)


Graphics::DrawEllipse(Pen* pen, Rect& rect)

The DrawEllipse method draws an ellipse.

Status DrawEllipse(
  const Pen* pen,
  const Rect& rect
);

Parameters

pen
[in] Pointer to a pen that is used to draw the ellipse.
rect
[in] Reference to a rectangle that bounds the ellipse.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws an ellipse.

VOID Example_DrawEllipse(HDC hdc
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen bluePen(Color(255, 0, 0, 255));

   // Create a Rect object that bounds the ellipse.
   Rect ellipseRect(0, 0, 200, 100);

   // Draw the ellipse.
   graphics.DrawEllipse(&bluePen, ellipseRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
FillEllipse Methods, Pen, Rect
Concepts
Ellipses and Arcs


Graphics::DrawEllipse(Pen* pen, RectF& rect)

The DrawEllipse method draws an ellipse.

Status DrawEllipse(
  const Pen* pen,
  const RectF& rect
);

Parameters

pen
[in] Pointer to a pen that is used to draw the ellipse.
rect
[in] Reference to a rectangle that bounds the ellipse.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws an ellipse.

VOID Example_DrawEllipse2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen bluePen(Color(255, 0, 0, 255));

   // Create a Rect object that bounds the ellipse.
   RectF ellipseRect(0.0f, 0.0f, 200.0f, 100.0f);

   // Draw the ellipse.
   graphics.DrawEllipse(&bluePen, ellipseRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
FillEllipse Methods, Pen, RectF
Concepts
Ellipses and Arcs


Graphics::DrawEllipse(Pen* pen, INT x, INT y, INT width, INT height)

The DrawEllipse method draws an ellipse.

Status DrawEllipse(
  const Pen* pen,
  INT x,
  INT y,
  INT width,
  INT height
);

Parameters

pen
[in] Pointer to a pen that is used to draw the ellipse.
x
[in] Integer that specifies the x-coordinate of the upper-left corner of the rectangle that bounds the ellipse.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the rectangle that bounds the ellipse.
width
[in] Integer that specifies the width of the rectangle that bounds the ellipse.
height
[in] Integer that specifies the height of the rectangle that bounds the ellipse.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws an ellipse.

VOID Example_DrawEllipse3(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen bluePen(Color(255, 0, 0, 255));

   // Initialize the variables that define the ellipse.
   int x = 0;
   int y =0;
   int width = 200;
   int height = 100;

   // Draw the ellipse.
   graphics.DrawEllipse(&bluePen, x, y, width, height);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
FillEllipse Methods, Pen
Concepts
Ellipses and Arcs


Graphics::DrawEllipse(Pen* pen, REAL x, REAL y, REAL width, REAL height)

The DrawEllipse method draws an ellipse.

Status DrawEllipse(
  const Pen* pen,
  REAL x,
  REAL y,
  REAL width,
  REAL height
);

Parameters

pen
[in] Pointer to a pen that is used to draw the ellipse.
x
[in] Real number that specifies the x-coordinate of the upper-left corner of the rectangle that bounds the ellipse.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the rectangle that bounds the ellipse.
width
[in] Real number that specifies the width of the rectangle that bounds the ellipse.
height
[in] Real number that specifies the height of the rectangle that bounds the ellipse.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws an ellipse.

VOID Example_DrawEllipse4(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen bluePen(Color(255, 0, 0, 255));

   // Initialize the variables that define the ellipse.
   REAL x = 0.0f;
   REAL y =0.0f;
   REAL width = 200.0f;
   REAL height = 100.0f;

   // Draw the ellipse.
   graphics.DrawEllipse(&bluePen, x, y, width, height);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
FillEllipse Methods, Pen
Concepts
Ellipses and Arcs


Graphics::DrawImage Methods

This topic lists the DrawImage methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • DrawImage(Image* image, Point* destPoints, INT count)
  • DrawImage(Image* image, PointF* destPoints, INT count)
  • DrawImage(Image* image, Point* destPoints, INT count, INT srcx, INT srcy, INT srcwidth, INT srcheight, Unit srcUnit, ImageAttributes* imageAttributes, DrawImageAbort callback, VOID* callbackData)
  • DrawImage(Image* image, PointF* destPoints, INT count, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, Unit srcUnit, ImageAttributes* imageAttributes, DrawImageAbort callback, VOID* callbackData)
  • DrawImage(Image* image, Rect& destRect, INT srcx, INT srcy, INT srcwidth, INT srcheight, Unit srcUnit, ImageAttributes* imageAttributes, DrawImageAbort callback, VOID* callbackData)
  • DrawImage(Image* image, RectF& destRect, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, Unit srcUnit, ImageAttributes* imageAttributes, DrawImageAbort callback, VOID* callbackData)
  • DrawImage(Image* image, Point& point)
  • DrawImage(Image* image, PointF& point)
  • DrawImage(Image* image, Rect& rect)
  • DrawImage(Image* image, RectF& rect)
  • DrawImage(Image* image, INT x, INT y)
  • DrawImage(Image* image, REAL x, REAL y)
  • DrawImage(Image* image, INT x, INT y, INT srcx, INT srcy, INT srcwidth, INT srcheight, Unit srcUnit)
  • DrawImage(Image* image, REAL x, REAL y, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, Unit srcUnit)
  • DrawImage(Image* image, INT x, INT y, INT width, INT height)
  • DrawImage(Image* image, REAL x, REAL y, REAL width, REAL height)


Graphics::DrawImage(Image* image, Point* destPoints, INT count)

The DrawImage method draws an image.

Status DrawImage(
  Image* image,
  const Point* destPoints,
  INT count
);

Parameters

image
[in] Pointer to an Image object that specifies the source image.
destPoints
[in] Pointer to an array of Point objects that specify the area, in a parallelogram, in which to draw the image.
count
[in] Integer that specifies the number of elements in the destPoints array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns InvalidParameter.

Remarks

The value of the count parameter must equal 3 to specify the three corners of the parallelogram. The fourth corner of the parallelogram is calculated using the vectors of the first and second coordinates and the first and third coordinates. The image is scaled to fit the parallelogram.

Example Code [C++]

The following example draws an image.

VOID Example_DrawImage(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"climber.jpg");

   // Create an array of Point objects that specify the destination of the image.
   Point destPoints[3] = {
   Point(30, 30),
   Point(250, 50),
   Point(175, 120)};

   Point* pdestPoints = destPoints;

   // Draw the image.
   graphics.DrawImage(&image, pdestPoints, 3);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image, Point
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, PointF* destPoints, INT count)

The DrawImage method draws an image.

Status DrawImage(
  Image* image,
  const PointF* destPoints,
  INT count
);

Parameters

image
[in] Pointer to an Image object that specifies the source image.
destPoints
[in] Pointer to an array of PointF objects that specify the area, in a parallelogram, in which to draw the image.
count
[in] Integer that specifies the number of elements in the destPoints array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The value of the count parameter must equal 3 to specify the coordinates of the upper-left corner, upper-right corner, and lower-left corner of the parallelogram. The coordinate of the lower-right corner is calculated using the three given coordinates, the width, and the height of the image. The image is scaled to fit the parallelogram.

Example Code [C++]

The following example draws an image.

VOID Example_DrawImage3(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"climber.jpg");

   // Create an array of PointF objects that specify the destination of the image.
   PointF destPoints[3] = {
   PointF(30.0f, 30.0f),
   PointF(250.0f, 50.0f),
   PointF(175.0f, 120.0f)};

   PointF* pdestPoints = destPoints;

   // Draw the image.
   graphics.DrawImage(&image, pdestPoints, 3);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image, Point
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, Point* destPoints, INT count, INT srcx, INT srcy, INT srcwidth, INT srcheight, Unit srcUnit, ImageAttributes* imageAttributes, DrawImageAbort callback, VOID* callbackData)

The DrawImage method draws an image.

Status DrawImage(
  Image* image,
  const Point* destPoints,
  INT count,
  INT srcx,
  INT srcy,
  INT srcwidth,
  INT srcheight,
  Unit srcUnit,
  ImageAttributes* imageAttributes,
  DrawImageAbort callback,
  VOID* callbackData
);

Parameters

image
[in] Pointer to an Image object that specifies the source image.
destPoints
[in] Pointer to an array of Point objects that specify the area, in a parallelogram, in which to draw the image.
count
[in] Integer that specifies the number of elements in the destPoints array.
srcx
[in] Integer that specifies the x-coordinate of the upper-left corner of the portion of the source image to be drawn.
srcy
[in] Integer that specifies the y-coordinate of the upper-left corner of the portion of the source image to be drawn.
srcwidth
[in] Integer that specifies the width of the portion of the source image to be drawn,
srcheight
[in] Integer that specifies the height of the portion of the source image to be drawn,
srcUnit
[in] Element of the Unit enumeration that specifies the unit of measurement for the image. The default value is UnitPixel.
imageAttributes
[in] Pointer to an ImageAttributes object that specifies the color and size attributes of the image to be drawn. The default value is NULL.
callback
[in] Callback method used to cancel the drawing in progress. The default value is NULL.
callbackData
[in] Pointer to additional data used by the method specified by the callback parameter. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The value of the count parameter must equal 3 to specify the three corners of the parallelogram. The fourth corner of the parallelogram is calculated using the vectors of the first and second coordinates and the first and third coordinates. The portion of the source image to be drawn is scaled to fit the parallelogram.

Example Code [C++]

The following example draws the original source image and then draws a portion of the image in a specified parallelogram.

VOID Example_DrawImage2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"pattern.png");

   // Draw the original source image.
   graphics.DrawImage(&image, 10, 10);

   // Define the portion of the image to draw.
   int srcX = 70;
   int srcY = 20;
   int srcWidth = 100;
   int srcHeight = 100;

   // Create an array of Point objects that specify the destination of the cropped image.
   Point destPoints[3] = {
   Point(230, 30),
   Point(350, 50),
   Point(275, 120)};

   Point* pdestPoints = destPoints;

   // Create an ImageAttributes object that specifies a recoloring from red to blue.
   ImageAttributes remapAttributes;
   ColorMap redToBlue;
   redToBlue.oldColor = Color(255, 255, 0, 0);
   redToBlue.newColor = Color(255, 0, 0, 255);
   remapAttributes.SetRemapTable(1, &redToBlue);

   // Draw the cropped image.
   graphics.DrawImage(
   &image,
   pdestPoints,
   3,
   srcX,
   srcY,
   srcWidth,
   srcHeight,
   UnitPixel,
   &remapAttributes,
   NULL,
   NULL);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image, ImageAttributes, Point, SetRemapTable
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, PointF* destPoints, INT count, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, Unit srcUnit, ImageAttributes* imageAttributes, DrawImageAbort callback, VOID* callbackData)

The DrawImage method draws an image.

Status DrawImage(
  Image* image,
  const PointF* destPoints,
  INT count,
  REAL srcx,
  REAL srcy,
  REAL srcwidth,
  REAL srcheight,
  Unit srcUnit,
  ImageAttributes* imageAttributes,
  DrawImageAbort callback,
  VOID* callbackData
);

Parameters

image
[in] Pointer to an Image object that specifies the source image.
destPoints
[in] Pointer to an array of PointF objects that specify the area, in a parallelogram, in which to draw the image.
count
[in] Integer that specifies the number of elements in the destPoints array.
srcx
[in] Real number that specifies the x-coordinate of the upper-left corner of the portion of the source image to be drawn.
srcy
[in] Real number that specifies the y-coordinate of the upper-left corner of the portion of the source image to be drawn.
srcwidth
[in] Real number that specifies the width of the portion of the source image to be drawn.
srcheight
[in] Real number that specifies the height of the portion of the source image to be drawn.
srcUnit
[in] Element of the Unit enumeration that specifies the unit of measure for the image. The default value is UnitPixel.
imageAttributes
[in] Pointer to an ImageAttributes object that specifies the color and size attributes of the image to be drawn. The default value is NULL.
callback
[in] Callback method used to cancel the drawing in progress. The default value is NULL.
callbackData
[in] Pointer to additional data used by the method specified by the callback parameter. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The value of the count parameter must equal 3 to specify the coordinates of the upper-left corner, upper-right corner, and lower-left corner of the parallelogram. The coordinate of the lower-right corner is calculated using the three given coordinates, the width, and the height of the image. The portion of the source image to be drawn is scaled to fit the parallelogram.

Example Code [C++]

The following example draws the original source image and then draws a portion of the image in a specified parallelogram.

VOID Example_DrawImage4(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"pattern.png");

   // Draw the original source image.
   graphics.DrawImage(&image, 10, 10);

   // Define the portion of the image to draw.
   REAL srcX = 70.0f;
   REAL srcY = 20.0f;
   REAL srcWidth = 100.0f;
   REAL srcHeight = 100.0f;

   // Create an array of Point objects that specify the destination of the cropped image.
   PointF destPoints[3] = {
   PointF(230.0f, 30.0f),
   PointF(350.0f, 50.0f),
   PointF(275.0f, 120.0f)};

   Point* pdestPoints = destPoints;

   // Create an ImageAttributes object that specifies a recoloring from red to blue.
   ImageAttributes remapAttributes;
   ColorMap redToBlue;
   redToBlue.oldColor = Color(255, 255, 0, 0);
   redToBlue.newColor = Color(255, 0, 0, 255);
   remapAttributes.SetRemapTable(1, &redToBlue);

   // Draw the cropped image.
   graphics.DrawImage(
   &image,
   pdestPoints,
   3,
   srcX,
   srcY,
   srcWidth,
   srcHeight,
   UnitPixel,
   &remapAttributes,
   NULL,
   NULL);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image, ImageAttributes, Point, SetRemapTable, Unit
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, Rect& destRect, INT srcx, INT srcy, INT srcwidth, INT srcheight, Unit srcUnit, ImageAttributes* imageAttributes, DrawImageAbort callback, VOID* callbackData)

The DrawImage method draws an image.

Status DrawImage(
  Image* image,
  const Rect& destRect,
  INT srcx,
  INT srcy,
  INT srcwidth,
  INT srcheight,
  Unit srcUnit,
  ImageAttributes* imageAttributes,
  DrawImageAbort callback,
  VOID* callbackData
);

Parameters

image
[in] Pointer to an Image object that specifies the source image.
destRect
[in] Reference to a rectangle that bounds the drawing area for the image.
srcx
[in] Integer that specifies the x-coordinate of the upper-left corner of the portion of the source image to be drawn.
srcy
[in] Integer that specifies the y-coordinate of the upper-left corner of the portion of the source image to be drawn.
srcwidth
[in] Integer that specifies the width of the portion of the source image to be drawn.
srcheight
[in] Integer that specifies the height of the portion of the source image to be drawn.
srcUnit
[in] Element of the Unit enumeration that specifies the unit of measure for the image. The default value is UnitPixel.
imageAttributes
[in] Pointer to an ImageAttributes object that specifies the color and size attributes of the image to be drawn. The default value is NULL.
callback
[in] Callback method used to cancel the drawing in progress. The default value is NULL.
callbackData
[in] Pointer to additional data used by the method specified by the callback parameter. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The portion of the source image to be drawn is scaled to fit the rectangle.

Example Code [C++]

The following example draws the original source image and then draws a portion of the image in a specified rectangle.

VOID Example_DrawImage5(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"pattern.png");

   // Draw the original source image.
   graphics.DrawImage(&image, 10, 10);

   // Define the portion of the image to draw.
   int srcX = 70;
   int srcY = 20;
   int srcWidth = 100;
   int srcHeight = 100;

   // Create a Rect object that specifies the destination of the image.
   Rect destRect(200, 10, image.GetWidth(), image.GetHeight());

   // Create an ImageAttributes object that specifies a recoloring from red to blue.
   ImageAttributes remapAttributes;
   ColorMap redToBlue;
   redToBlue.oldColor = Color(255, 255, 0, 0);
   redToBlue.newColor = Color(255, 0, 0, 255);
   remapAttributes.SetRemapTable(1, &redToBlue);

   // Draw the resized image.
   graphics.DrawImage(
   &image,
   destRect,
   srcX,
   srcY,
   srcWidth,
   srcHeight,
   UnitPixel,
   &remapAttributes,
   NULL,
   NULL);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image, ImageAttributes, Point, SetRemapTable, Unit
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, RectF& destRect, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, Unit srcUnit, ImageAttributes* imageAttributes, DrawImageAbort callback, VOID* callbackData)

The DrawImage method draws an image.

Status DrawImage(
  Image* image,
  const RectF& destRect,
  REAL srcx,
  REAL srcy,
  REAL srcwidth,
  REAL srcheight,
  Unit srcUnit,
  ImageAttributes* imageAttributes,
  DrawImageAbort callback,
  VOID* callbackData
);

Parameters

image
[in] Pointer to an Image object that specifies the source image.
destRect
[in] Reference to a rectangle that bounds the drawing area for the image.
srcx
[in] Real number that specifies the x-coordinate of the upper-left corner of the portion of the source image to be drawn.
srcy
[in] Real number that specifies the y-coordinate of the upper-left corner of the portion of the source image to be drawn.
srcwidth
[in] Real number that specifies the width of the portion of the source image to be drawn.
srcheight
[in] Real number that specifies the height of the portion of the source image to be drawn.
srcUnit
[in] Element of the Unit enumeration that specifies the unit of measure for the image. The default value is UnitPixel.
imageAttributes
[in] Pointer to an ImageAttributes object that specifies the color and size attributes of the image to be drawn. The default value is NULL.
callback
[in] Callback method used to cancel the drawing in progress. The default value is NULL.
callbackData
[in] Pointer to additional data used by the method specified by the callback parameter. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The portion of the source image to be drawn is scaled to fit the rectangle.

Example Code [C++]

The following example draws the original source image and then draws a portion of the image in a specified rectangle.

VOID Example_DrawImage6(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"pattern.png");

   // Draw the original source image.
   graphics.DrawImage(&image, 10, 10);

   // Define the portion of the image to draw.
   REAL srcX = 70.0f;
   REAL srcY = 20.0f;
   REAL srcWidth = 100.0f;
   REAL srcHeight = 100.0f;

   // Create a RectF object that specifies the destination of the image.
   RectF destRect(200.0f, 10.0f, <REAL>image.GetWidth(), <REAL>image.GetHeight());

   // Create an ImageAttributes object that specifies a recoloring from red to blue.
   ImageAttributes remapAttributes;
   ColorMap redToBlue;
   redToBlue.oldColor = Color(255, 255, 0, 0);
   redToBlue.newColor = Color(255, 0, 0, 255);
   remapAttributes.SetRemapTable(1, &redToBlue);

   // Draw the resized image.
   graphics.DrawImage(
   &image,
   destRect,
   srcX,
   srcY,
   srcWidth,
   srcHeight,
   UnitPixel,
   &remapAttributes,
   NULL,
   NULL);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image, ImageAttributes, Point, SetRemapTable, Unit
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, Point& point)

The DrawImage method draws an image.

Status DrawImage(
  Image* image,
  const Point& point
);

Parameters

image
[in] Pointer to an Image object that specifies the source image.
point
[in] Reference to a Point object that specifies the coordinates of the upper-left corner of the destination position at which to draw the image.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws an image. The image is drawn with the upper-left corner at the coordinate specified by the point parameter.

VOID Example_DrawImage7(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"climber.jpg");

   // Draw the image.
   graphics.DrawImage(&image, Point(0, 0));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image, Point
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, PointF& point)

The DrawImage method draws an image.

Status DrawImage(
  Image* image,
  const PointF& point
);

Parameters

image
[in] Pointer to an Image object that specifies the source image.
point
[in] Reference to a PointF object that specifies the coordinates of the upper-left corner of the destination position at which to draw the image.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws an image. The image is drawn with the upper-left corner at the coordinate specified by the point parameter.

VOID Example_DrawImage8(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"climber.jpg");

   // Draw the image.
   graphics.DrawImage(&image, PointF(0.0f, 0.0f));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image, PointF
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, Rect& rect)

The DrawImage method draws an image.

Status DrawImage(
  Image* image,
  const Rect& rect
);

Parameters

image
[in] Pointer to an Image object that specifies the source image.
rect
[in] Reference to a rectangle that bounds the drawing area for the image.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The image is scaled to fit the rectangle.

Example Code [C++]

The following example draws the source image, the rectangle that bounds the resized image, and then draws the resized image to fit the rectangle.

VOID Example_DrawImage9(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"climber.jpg");

   // Create a Pen object.
   Pen pen (Color(255, 255, 0, 0), 2);

   // Draw the original source image.
   graphics.DrawImage(&image, 10, 10);

   // Create a Rect object that specifies the destination of the image.
   Rect destRect(200, 50, 150, 75);

   // Draw the rectangle that bounds the image.
   graphics.DrawRectangle(&pen, destRect);

   // Draw the image.
   graphics.DrawImage(&image, destRect);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image, Rect
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, RectF& rect)

The DrawImage method draws an image.

Status DrawImage(
  Image* image,
  const RectF& rect
);

Parameters

image
[in] Pointer to an Image object that specifies the source image.
rect
[in] Reference to a rectangle that bounds the drawing area for the image.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The image is scaled to fit the rectangle.

Example Code [C++]

The following example draws the source image, the rectangle that bounds the resized image, and then draws the resized image to fit the rectangle.

VOID Example_DrawImage10(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"climber.jpg");

   // Create a Pen object.
   Pen pen (Color(255, 255, 0, 0), 2);

   // Draw the original source image.
   graphics.DrawImage(&image, 10, 10);

   // Create a RectF object that specifies the destination of the image.
   RectF destRect(200, 50, 150, 75);

   // Draw the rectangle that bounds the image.
   graphics.DrawRectangle(&pen, destRect);

   // Draw the image.
   graphics.DrawImage(&image, destRect);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image, RectF
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, INT x, INT y)

The DrawImage method draws an image at a specified location.

Status DrawImage(
  Image* image,
  INT x,
  INT y
);

Parameters

image
[in] Pointer to an Image object that specifies the image to be drawn.
x
[in] Integer that specifies the x-coordinate of the upper-left corner of the rendered image.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the rendered image.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws an image with its upper-left corner at (0, 0).

VOID Example_DrawImage11(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"climber.jpg");

   // Draw the image.
   graphics.DrawImage(&image, 0, 0);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, REAL x, REAL y)

The DrawImage method draws an image at a specified location.

Status DrawImage(
  Image* image,
  REAL x,
  REAL y
);

Parameters

image
[in] Pointer to an Image object that specifies the image to be drawn.
x
[in] Real number that specifies the x-coordinate of the upper-left corner of the rendered image.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the rendered image.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws an image with its upper-left corner at (0, 0).

VOID Example_DrawImage14(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"snow.jpg");

   // Draw the image.
   graphics.DrawImage(&image, 0.0f, 0.0f);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, INT x, INT y, INT srcx, INT srcy, INT srcwidth, INT srcheight, Unit srcUnit)

The DrawImage method draws an image.

Status DrawImage(
  Image* image,
  INT x,
  INT y,
  INT srcx,
  INT srcy,
  INT srcwidth,
  INT srcheight,
  Unit srcUnit
);

Parameters

image
[in] Pointer to an Image object that specifies the source image.
x
[in] Integer that specifies the x-coordinate of the upper-left corner of the destination position at which to draw the image.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the destination position at which to draw the image.
srcx
[in] Integer that specifies the x-coordinate of the upper-left corner of the portion of the source image to be drawn.
srcy
[in] Integer that specifies the y-coordinate of the upper-left corner of the portion of the source image to be drawn.
srcwidth
[in] Integer that specifies the width of the portion of the source image to be drawn.
srcheight
[in] Integer that specifies the height of the portion of the source image to be drawn.
srcUnit
[in] Element of the Unit enumeration that specifies the unit of measure for the image. The default value is UnitPixel.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a portion of an image. The portion of the source image to be drawn is scaled to fit a specified parallelogram.

VOID Example_DrawImage12(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"climber.jpg");

   // Draw the original source image.
   graphics.DrawImage(&image, 10, 10);

   // Set up the location for the image and the portion of the source to draw.
   int x = 200;
   int y = 30;
   int srcx = 70;
   int srcy = 20;
   int srcwidth = 100;
   int srcheight = 200;
   Unit srcunit = UnitPixel;

   // Draw the image.
   graphics.DrawImage(&image, x, y, srcx, srcy, srcwidth, srcheight, srcunit);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, REAL x, REAL y, REAL srcx, REAL srcy, REAL srcwidth, REAL srcheight, Unit srcUnit)

The DrawImage method draws an image.

Status DrawImage(
  Image* image,
  REAL x,
  REAL y,
  REAL srcx,
  REAL srcy,
  REAL srcwidth,
  REAL srcheight,
  Unit srcUnit
);

Parameters

image
[in] Pointer to an Image object that specifies the source image.
x
[in] Real number that specifies the x-coordinate of the upper-left corner of the destination position at which to draw the image.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the destination position at which to draw the image.
srcx
[in] Real number that specifies the x-coordinate of the upper-left corner of the portion of the source image to be drawn.
srcy
[in] Real number that specifies the y-coordinate of the upper-left corner of the portion of the source image to be drawn.
srcwidth
[in] Real number that specifies the width of the portion of the source image to be drawn.
srcheight
[in] Real number that specifies the height of the portion of the source image to be drawn.
srcUnit
[in] Element of the Unit enumeration that specifies the unit of measure for the image. The default value is UnitPixel.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a portion of an image. The portion of the source image to be drawn is scaled to fit the rectangle.

VOID Example_DrawImage15(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"climber.jpg");

   // Draw the original source image.
   graphics.DrawImage(&image, 10, 10);

   // Set up the location for the image and the portion of the source to draw.
   REAL x = 200.0f;
   REAL y = 30.0f;
   REAL srcx = 70.0f;
   REAL srcy = 20.0f;
   REAL srcwidth = 100.0f;
   REAL srcheight = 200.0f;
   Unit srcunit = UnitPixel;

   // Draw the image.
   graphics.DrawImage(&image, x, y, srcx, srcy, srcwidth, srcheight, srcunit);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, INT x, INT y, INT width, INT height)

The DrawImage method draws an image.

Status DrawImage(
  Image* image,
  INT x,
  INT y,
  INT width,
  INT height
);

Parameters

image
[in] Pointer to an Image object that specifies the source image.
x
[in] Integer that specifies the x-coordinate of the upper-left corner of the destination rectangle at which to draw the image.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the destination rectangle at which to draw the image.
width
[in] Integer that specifies the width of the destination rectangle at which to draw the image.
height
[in] Integer that specifies the height of the destination rectangle at which to draw the image.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws an image.

VOID Example_DrawImage13(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"climber.jpg");

   // Draw the original source image.
   graphics.DrawImage(&image, 10, 10);

   // Draw the scaled image.
   graphics.DrawImage(&image, 200, 50, 150, 175);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawImage(Image* image, REAL x, REAL y, REAL width, REAL height)

The DrawImage method draws an image.

Status DrawImage(
  Image* image,
  REAL x,
  REAL y,
  REAL width,
  REAL height
);

Parameters

image
[in] Pointer to an Image object that specifies the source image.
x
[in] Real number that specifies the x-coordinate of the upper-left corner of the destination rectangle at which to draw the image.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the destination rectangle at which to draw the image.
width
[in] Real number that specifies the width of the destination rectangle at which to draw the image.
height
[in] Real number that specifies the height of the destination rectangle at which to draw the image.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws an image.

VOID Example_DrawImage16(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object.
   Image image(L"climber.jpg");

   // Draw the original source image.
   graphics.DrawImage(&image, 10, 10);

   // Draw the scaled image.
   graphics.DrawImage(&image, 200.0f, 50.0f, 150.0f, 175.0f);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Graphics::DrawLine Methods

This topic lists the DrawLine methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • DrawLine(Pen* pen, Point& pt1, Point& pt2)
  • DrawLine(Pen* pen, PointF& pt1, PointF& pt2)
  • DrawLine(Pen* pen, INT x1, INT y1, INT x2, INT y2)
  • DrawLine(Pen* pen, REAL x1, REAL y1, REAL x2, REAL y2)


Graphics::DrawLine(Pen* pen, Point& pt1, Point& pt2)

The DrawLine method draws a line that connects two points.

Status DrawLine(
  const Pen* pen,
  const Point& pt1,
  const Point& pt2
);

Parameters

pen
[in] Pointer to a pen that is used to draw the line.
pt1
[in] Reference to a Point object that specifies the start of the line.
pt2
[in] Reference to a Point object that specifies the end of the line.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a line.

VOID Example_DrawLine(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Create two Point objects that define the line.
   Point point1(100, 100);
   Point point2(500, 100);

   // Draw the line.
   graphics.DrawLine(&blackPen, point1, point2);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawLines Methods, Point
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Graphics::DrawLine(Pen* pen, PointF& pt1, PointF& pt2)

The DrawLine method draws a line that connects two points.

Status DrawLine(
  const Pen* pen,
  const PointF& pt1,
  const PointF& pt2
);

Parameters

pen
[in] Pointer to a pen that is used to draw the line.
pt1
[in] Reference to a PointF object that specifies the start of the line.
pt2
[in] Reference to a PointF object that specifies the end of the line.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a line.

VOID Example_DrawLine2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Create two PointF objects that define the line.
   PointF point1(100.0f, 100.0f);
   PointF point2(500.0f, 100.0f);

   // Draw the line.
   graphics.DrawLine(&blackPen, point1, point2);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawLines Methods, PointF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Graphics::DrawLine(Pen* pen, INT x1, INT y1, INT x2, INT y2)

The DrawLine method draws a line that connects two points.

Status DrawLine(
  const Pen* pen,
  INT x1,
  INT y1,
  INT x2,
  INT y2
);

Parameters

pen
[in] Pointer to a pen that is used to draw the line.
x1
[in] Integer that specifies the x-coordinate of the starting point of the line.
y1
[in] Integer that specifies the y-coordinate of the starting point of the line.
x2
[in] Integer that specifies the x-coordinate of the ending point of the line.
y2
[in] Integer that specifies the y-coordinate of the ending point of the line.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a line.

VOID Example_DrawLine3(HDC hdc
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Initialize the coordinates of the points that define the line.
   int x1 = 100;
   int y1 = 100;
   int x2 = 500;
   int y2 = 100;

   // Draw the line.
   graphics.DrawLine(&blackPen, x1, y1, x2, y2);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawLines Methods, Point
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Graphics::DrawLine(Pen* pen, REAL x1, REAL y1, REAL x2, REAL y2)

The DrawLine method draws a line that connects two points.

Status DrawLine(
  const Pen* pen,
  REAL x1,
  REAL y1,
  REAL x2,
  REAL y2
);

Parameters

pen
[in] Pointer to a pen that is used to draw the line.
x1
[in] Real number that specifies the x-coordinate of the starting point of the line.
y1
[in] Real number that specifies the y-coordinate of the starting point of the line.
x2
[in] Real number that specifies the x-coordinate of the ending point of the line.
y2
[in] Real number that specifies the y-coordinate of the ending point of the line.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a line.

VOID Example_DrawLine4(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Initialize the coordinates of the points that define the line.
   REAL x1 = 100.0f;
   REAL y1 = 100.0f;
   REAL x2 = 500.0f;
   REAL y2 = 100.0f;

   // Draw the line.
   graphics.DrawLine(&blackPen, x1, y1, x2, y2);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawLines Methods, PointF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Graphics::DrawLines Methods

This topic lists the DrawLines methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • DrawLines(Pen* pen, Point* points, INT count)
  • DrawLines(Pen* pen, PointF* points, INT count)


Graphics::DrawLines(Pen* pen, Point* points, INT count)

The DrawLines method draws a sequence of connected lines.

Status DrawLines(
  const Pen* pen,
  const Point* points,
  INT count
);

Parameters

pen
[in] Pointer to a pen that is used to draw the lines.
points
[in] Pointer to an array of Point objects that specify the starting and ending points of the lines.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Each line requires a starting point and an ending point. The ending point of each line is the starting point for the next.

Example Code [C++]

The following example draws a sequence of connected lines.

VOID Example_DrawLines(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Create an array of Point objects that define the lines to draw.
   Point point1(10, 10);
   Point point2(10, 100);
   Point point3(200, 50);
   Point point4(250, 300);

   Point points[4] = {point1, point2, point3, point4};
   Point* pPoints = points;

   // Draw the lines.
   graphics.DrawLines(&blackPen, pPoints, 4);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawLine Methods, Point
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Graphics::DrawLines(Pen* pen, PointF* points, INT count)

The DrawLines method draws a sequence of connected lines.

Status DrawLines(
  const Pen* pen,
  const PointF* points,
  INT count
);

Parameters

pen
[in] Pointer to a pen that is used to draw the lines.
points
[in] Pointer to an array of PointF objects that specify the starting and ending points of the lines.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a sequence of connected lines.

VOID Example_DrawLines2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Create an array of PointF objects that define the lines to draw.
   PointF point1(10.0f, 10.0f);
   PointF point2(10.0f, 100.0f);
   PointF point3(200.0f, 50.0f);
   PointF point4(250.0f, 300.0f);

   PointF points[4] = {point1, point2, point3, point4};
   PointF* pPoints = points;

   // Draw the lines.
   graphics.DrawLines(&blackPen, pPoints, 4);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawLine Methods, Point
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Graphics::DrawPath(pen, path)

The DrawPath method draws a sequence of lines and curves defined by a GraphicsPath object.

Status DrawPath(
  const Pen* pen,
  const GraphicsPath* path
);

Parameters

pen
[in] Pointer to a pen that is used to draw the path.
path
[in] Pointer to a GraphicsPath object that specifies the sequence of lines and curves that make up the path.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a GraphicsPath object.

VOID Example_DrawPath(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a GraphicsPath, and add an ellipse.
   GraphicsPath ellipsePath;
   ellipsePath.AddEllipse(Rect(0, 0, 200, 100));

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Draw ellipsePath.
   graphics.DrawPath(&blackPen, &ellipsePath);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
FillPie Methods, GraphicsPath
Tasks and Examples
Creating Figures from Lines, Curves, and Shapes
Concepts
Paths


Graphics::DrawPie Methods

This topic lists the DrawPie methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • DrawPie(Pen* pen, Rect& rect, REAL startAngle, REAL sweepAngle)
  • DrawPie(Pen* pen, RectF& rect, REAL startAngle, REAL sweepAngle)
  • DrawPie(Pen* pen, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
  • DrawPie(Pen* pen, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)


Graphics::DrawPie(Pen* pen, Rect& rect, REAL startAngle, REAL sweepAngle)

The DrawPie method draws a pie.

Status DrawPie(
  const Pen* pen,
  const Rect& rect,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

pen
[in] Pointer to a pen that is used to draw the pie.
rect
[in] Reference to a rectangle that bounds the ellipse in which to draw the pie.
startAngle
[in] Real number that specifies the angle, in degrees, between the x-axis and the starting point of the arc that defines the pie. A positive value specifies clockwise rotation.
sweepAngle
[in] Real number that specifies the angle, in degrees, between the starting and ending points of the arc that defines the pie. A positive value specifies clockwise rotation.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The following illustration shows the pie that is drawn in the ellipse that is bounded by the rectangle. The illustration also shows the horizontal axis of the ellipse and the direction of the startAngle and the sweepAngle.

Example Code [C++]

The following example draws a pie.

VOID Example_DrawPie(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Define the pie.
   Rect ellipseRect(0, 0, 200, 100);
   REAL startAngle = 0.0f;
   REAL sweepAngle = 45.0f;

   // Draw the pie.
   graphics.DrawPie(&blackPen, ellipseRect, startAngle, sweepAngle);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawLines Methods, FillPie Methods, Rect
Concepts
Open and Closed Curves


Graphics::DrawPie(Pen* pen, RectF& rect, REAL startAngle, REAL sweepAngle)

The DrawPie method draws a pie.

Status DrawPie(
  const Pen* pen,
  const RectF& rect,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

pen
[in] Pointer to a pen that is used to draw the pie.
rect
[in] Rectangle that bounds the ellipse in which to draw the pie.
startAngle
[in] Real number that specifies the angle, in degrees, between the x-axis and the starting point of the arc that defines the pie. A positive value specifies clockwise rotation.
sweepAngle
[in] Real number that specifies the angle, in degrees, between the starting and ending points of the arc that defines the pie. A positive value specifies clockwise rotation.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The following illustration shows the pie that is drawn in the ellipse that is bounded by the rectangle. The illustration also shows the horizontal axis of the ellipse and the direction of the startAngle and the sweepAngle.

Example Code [C++]

The following example draws a pie.

VOID Example_DrawPie2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Define the pie.
   RectF ellipseRect(0, 0, 200, 100);
   REAL startAngle = 0.0f;
   REAL sweepAngle = 45.0f;

   // Draw the pie.
   graphics.DrawPie(&blackPen, ellipseRect, startAngle, sweepAngle);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
FillPie Methods, RectF
Concepts
Open and Closed Curves


Graphics::DrawPie(Pen* pen, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)

The DrawPie method draws a pie.

Status DrawPie(
  const Pen* pen,
  INT x,
  INT y,
  INT width,
  INT height,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

pen
[in] Pointer to a pen that is used to draw the pie.
x
[in] Integer that specifies the x-coordinate of the upper-left corner of the rectangle that bounds the ellipse in which to draw the pie.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the rectangle that bounds the ellipse in which to draw the pie.
width
[in] Integer that specifies the width of the rectangle that bounds the ellipse in which to draw the pie.
height
[in] Integer that specifies the height of the rectangle that bounds the ellipse in which to draw the pie.
startAngle
[in] Real number that specifies the angle, in degrees, between the x-axis and the starting point of the arc that defines the pie. A positive value specifies clockwise rotation.
sweepAngle
[in] Real number that specifies the angle, in degrees, between the starting and ending points of the arc that defines the pie. A positive value specifies clockwise rotation.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The following illustration shows the pie that is drawn in the ellipse that is bounded by the rectangle. The illustration also shows the horizontal axis of the ellipse and the direction of the startAngle and the sweepAngle.

Example Code [C++]

The following example draws a pie.

VOID Example_DrawPie3(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Define the pie.
   int x = 0;
   int y = 0;
   int width = 200;
   int height = 100;
   REAL startAngle = 0.0f;
   REAL sweepAngle = 45.0f;

   // Draw the pie.
   graphics.DrawPie(&blackPen, x, y, width, height, startAngle, sweepAngle);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
FillPie Methods, Rect
Concepts
Open and Closed Curves


Graphics::DrawPie(Pen* pen, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)

The DrawPie method draws a pie.

Status DrawPie(
  const Pen* pen,
  REAL x,
  REAL y,
  REAL width,
  REAL height,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

pen
[in] Pointer to a pen that is used to draw the pie.
x
[in] Real number that specifies the x-coordinate of the upper-left corner of the rectangle that bounds the ellipse in which to draw the pie.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the rectangle that bounds the ellipse in which to draw the pie.
width
[in] Real number that specifies the width of the rectangle that bounds the ellipse in which to draw the pie.
height
[in] Real number that specifies the height of the rectangle that bounds the ellipse in which to draw the pie.
startAngle
[in] Real number that specifies the angle, in degrees, between the x-axis and the starting point of the arc that defines the pie. A positive value specifies clockwise rotation.
sweepAngle
[in] Real number that specifies the angle, in degrees, between the starting and ending points of the arc that defines the pie. A positive value specifies clockwise rotation.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The following illustration shows the pie that is drawn in the ellipse that is bounded by the rectangle. The illustration also shows the horizontal axis of the ellipse and the direction of the startAngle and the sweepAngle.

Example Code [C++]

The following example draws a pie.

VOID Example_DrawPie4(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Define the pie.
   REAL x = 0.0f;
   REAL y = 0.0f;
   REAL width = 200.0f;
   REAL height = 100.0f;
   REAL startAngle = 0.0f;
   REAL sweepAngle = 45.0f;

   // Draw the pie.
   graphics.DrawPie(&blackPen, x, y, width, height, startAngle, sweepAngle);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
FillPie Methods, RectF
Concepts
Open and Closed Curves


Graphics::DrawPolygon Methods

This topic lists the DrawPolygon methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • DrawPolygon(Pen* pen, Point* points, INT count)
  • DrawPolygon(Pen* pen, PointF* points, INT count)


Graphics::DrawPolygon(Pen* pen, Point* points, INT count)

The DrawPolygon method draws a polygon.

Status DrawPolygon(
  const Pen* pen,
  const Point* points,
  INT count
);

Parameters

pen
[in] Pointer to a pen that is used to draw the polygon.
points
[in] Pointer to an array of Point objects that specify the vertices of the polygon.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

If the first and last coordinates in the points array are not identical, a line is drawn between them to close the polygon.

Example Code [C++]

The following example draws a polygon, defined by an array of points.

VOID Example_DrawPolygon(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Create an array of Point objects that define the polygon.
   Point point1(100, 100);
   Point point2(200, 130);
   Point point3(150, 200);
   Point point4(50, 200);
   Point point5(0, 130);
   Point points[5] = {point1, point2, point3, point4, point5};
   Point* pPoints = points;

   // Draw the polygon.
   graphics.DrawPolygon(&blackPen, pPoints, 5);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
FillPolygon Methods, Point
Concepts
Polygons


Graphics::DrawPolygon(Pen* pen, PointF* points, INT count)

The DrawPolygon method draws a polygon.

Status DrawPolygon(
  const Pen* pen,
  const PointF* points,
  INT count
);

Parameters

pen
[in] Pointer to a pen that is used to draw the polygon.
points
[in] Pointer to an array of PointF objects that specify the vertices of the polygon.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

If the first and last coordinates in the points array are not identical, a line is drawn between them to close the polygon.

Example Code [C++]

The following example draws a polygon, defined by an array of points.

VOID Example_DrawPolygon2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Create an array of PointF objects that define the polygon.
   PointF point1(100.0f, 100.0f);
   PointF point2(200.0f, 130.0f);
   PointF point3(150.0f, 200.0f);
   PointF point4(50.0f, 200.0f);
   PointF point5(0.0f, 130.0f);
   PointF points[5] = {point1, point2, point3, point4, point5};
   PointF* pPoints = points;

   // Draw the polygon.
   graphics.DrawPolygon(&blackPen, pPoints, 5);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
FillPolygon Methods, PointF
Concepts
Polygons


Graphics::DrawRectangle Methods

This topic lists the DrawRectangle methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • DrawRectangle(Pen* pen, Rect& rect)
  • DrawRectangle(Pen* pen, RectF& rect)
  • DrawRectangle(Pen* pen, INT x, INT y, INT width, INT height)
  • DrawRectangle(Pen* pen, REAL x, REAL y, REAL width, REAL height)


Graphics::DrawRectangle(Pen* pen, Rect& rect)

The DrawRectangle method draws a rectangle.

Status DrawRectangle(
  const Pen* pen,
  const Rect& rect
);

Parameters

pen
[in] Pointer to a pen that is used to draw a rectangle.
rect
[in] Reference to the rectangle to be drawn.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a rectangle.

VOID Example_DrawRectangle(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Create a Rect object.
   Rect rect(0, 0, 200, 200);

   // Draw rect.
   graphics.DrawRectangle(&blackPen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawRectangles Methods, FillRectangle Methods, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Graphics::DrawRectangle(Pen* pen, RectF& rect)

The DrawRectangle method draws a rectangle.

Status DrawRectangle(
  const Pen* pen,
  const RectF& rect
);

Parameters

pen
[in] Pointer to a pen that is used to draw the rectangle.
rect
[in] Reference to the rectangle to be drawn.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a rectangle.

VOID Example_DrawRectangle2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Create a RectF object.
   RectF rect(0.0f, 0.0f, 200.0f, 200.0f);

   // Draw rect.
   graphics.DrawRectangle(&blackPen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawRectangles Methods, FillRectangle Methods, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Graphics::DrawRectangle(Pen* pen, INT x, INT y, INT width, INT height)

The DrawRectangle method draws a rectangle.

Status DrawRectangle(
  const Pen* pen,
  INT x,
  INT y,
  INT width,
  INT height
);

Parameters

pen
[in] Pointer to a pen that is used to draw the rectangle.
x
[in] Integer that specifies the x-coordinate of the upper-left corner of the rectangle.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the rectangle.
width
[in] Integer that specifies the width of the rectangle.
height
[in] Integer that specifies the height of the rectangle.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a rectangle.

VOID Example_DrawRectangle3(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Define the rectangle.
   int x = 0;
   int y = 0;
   int width = 200;
   int height = 200;

   // Draw the rectangle.
   graphics.DrawRectangle(&blackPen, x, y, width, height);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawRectangles Methods, FillRectangle Methods, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Graphics::DrawRectangle(Pen* pen, REAL x, REAL y, REAL width, REAL height)

The DrawRectangle method draws a rectangle.

Status DrawRectangle(
  const Pen* pen,
  REAL x,
  REAL y,
  REAL width,
  REAL height
);

Parameters

pen
[in] Pointer to a pen that is used to draw the rectangle.
x
[in] Real number that specifies the x-coordinate of the upper-left corner of the rectangle.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the rectangle.
width
[in] Real number that specifies the width of the rectangle.
height
[in] Real number that specifies the height of the rectangle.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a rectangle.

VOID Example_DrawRectangle4(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color::Black, 3);

   // Define the rectangle.
   REAL x = 0.0f;
   REAL y = 0.0f;
   REAL width = 200.0f;
   REAL height = 200.0f;

   // Draw the rectangle.
   graphics.DrawRectangle(&blackPen, x, y, width, height);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawRectangles Methods, FillRectangle Methods, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Graphics::DrawRectangles Methods

This topic lists the DrawRectangles methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • DrawRectangles(Pen* pen, Rect* rects, INT count)
  • DrawRectangles(Pen* pen, RectF* rects, INT count)


Graphics::DrawRectangles(Pen* pen, Rect* rects, INT count)

The DrawRectangles method draws a sequence of rectangles.

Status DrawRectangles(
  const Pen* pen,
  const Rect* rects,
  INT count
);

Parameters

pen
[in] Pointer to a pen that is used to draw the rectangles.
rects
[in] Pointer to an array of Rect objects that specify the coordinates of the rectangles to be drawn.
count
[in] Integer that specifies the number of elements in the rects array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a group of rectangles.

VOID Example_DrawRectangles(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Create an array of Rect objects.
   Rect rect1(0, 0, 100, 200);
   Rect rect2(100, 200, 250, 50);
   Rect rect3(300, 0, 50, 100);
   Rect rects[] = {rect1, rect2, rect3};
   Rect* pRects = rects;

   // Draw the rectangles.
   graphics.DrawRectangles(&blackPen, pRects, 3);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawRectangles Methods, FillRectangle Methods, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Graphics::DrawRectangles(Pen* pen, RectF* rects, INT count)

The DrawRectangles method draws a sequence of rectangles.

Status DrawRectangles(
  const Pen* pen,
  const RectF* rects,
  INT count
);

Parameters

pen
[in] Pointer to a pen that is used to draw the rectangles.
rects
[in] Pointer to an array of RectF objects that specify the coordinates of the rectangles to be drawn.
count
[in] Integer that specifies the number of elements in the rects array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a group of rectangles.

VOID Example_DrawRectangles2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen blackPen(Color(255, 0, 0, 0), 3);

   // Create an array of RectF objects.
   RectF rect1(0.0f, 0.0f, 100.0f, 200.0f);
   RectF rect2(100.0f, 200.0f, 250.0f, 50.0f);
   RectF rect3(300.0f, 0.0f, 50.0f, 100.0f);
   RectF rects[] = {rect1, rect2, rect3};
   RectF* pRects = rects;

   // Draw the rectangles.
   graphics.DrawRectangles(&blackPen, pRects, 3);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawRectangles Methods, FillRectangle Methods, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Graphics::DrawString Methods

This topic lists the DrawString methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • DrawString(string, length, font, layoutRect, stringFormat, brush)
  • DrawString(string, length, font, origin, brush)
  • DrawString(string, length, font, origin, stringFormat, brush)


Graphics::DrawString(string, length, font, layoutRect, stringFormat, brush)

The DrawString method draws a string based on a font, a layout rectangle, and a format.

Status DrawString(
  const WCHAR* string,
  INT length,
  const Font* font,
  const RectF& layoutRect,
  const StringFormat* stringFormat,
  const Brush* brush
);

Parameters

string
[in] Pointer to a wide-character string to be drawn.
length
[in] Integer that specifies the number of characters in the string array. The length parameter can be set to –1 if the string is null terminated.
font
[in] Pointer to a Font object that specifies the font attributes (the family name, the size, and the style of the font) to use.
layoutRect
[in] Reference to a rectangle that bounds the string.
stringFormat
[in] Pointer to a StringFormat object that specifies text layout information and display manipulations to be applied to the string.
brush
[in] Pointer to a Brush object that is used to fill the string.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example uses the specified formatting to draw a string in a layout rectangle.

VOID Example_DrawString(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a string.
   WCHAR string[256];
   wcscpy(string, L"Sample Text");

   // Initialize arguments.
   Font myFont(L"Arial", 16);
   RectF layoutRect(0.0f, 0.0f, 200.0f, 50.0f);
   StringFormat format;
   format.SetAlignment(StringAlignmentCenter);
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Draw string.
   graphics.DrawString(
   string,
   wcslen(string),
   &myFont,
   layoutRect,
   &format,
   &blackBrush);

   // Draw layoutRect.
   graphics.DrawRectangle(&Pen(Color::Black, 3), layoutRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Font, Pen, RectF, StringFormat


Graphics::DrawString(string, length, font, origin, brush)

The DrawString method draws a string based on a font and an origin for the string.

Status DrawString(
  const WCHAR* string,
  INT length,
  const Font* font,
  const PointF& origin,
  const Brush* brush
);

Parameters

string
[in] Pointer to a wide-character string to be drawn.
length
[in] Integer that specifies the number of characters in the string array. The length parameter can be set to –1 if the string is null terminated.
font
[in] Pointer to a Font object that specifies the font attributes (the family name, the size, and the style of the font) to use.
origin
[in] Reference to a PointF object that specifies the starting point for the string.
brush
[in] Pointer to a Brush object that is used to fill the string.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws a string at the specified origin.

VOID Example_DrawString2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a string.
   WCHAR string[256];
   wcscpy(string, L"Sample Text");

   // Initialize arguments.
   Font myFont(L"Arial", 16);
   PointF origin(0.0f, 0.0f);
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Draw string.
   graphics.DrawString(
   string,
   wcslen(string),
   &myFont,
   origin,
   &blackBrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Font, GraphicsPath, SolidBrush


Graphics::DrawString(string, length, font, origin, stringFormat, brush)

The DrawString method draws a string based on a font, a string origin, and a format.

Status DrawString(
  const WCHAR* string,
  INT length,
  const Font* font,
  const PointF& origin,
  const StringFormat* stringFormat,
  const Brush* brush
);

Parameters

string
[in] Pointer to a wide-character string to be drawn.
length
[in] Integer that specifies the number of characters in the string array. The length parameter can be set to –1 if the string is null terminated.
font
[in] Pointer to a Font object that specifies the font attributes (the family name, the size, and the style of the font) to use.
origin
[in] Reference to a PointF object that specifies the starting point for the string.
stringFormat
[in] Pointer to a StringFormat object that specifies text layout information and display manipulations to be applied to the string.
brush
[in] Pointer to a Brush object that is used to fill the string.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example uses the specified formatting to draw a string at the specified origin.

VOID Example_DrawString3(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a string.
   WCHAR string[256];
   wcscpy(string, L"Sample Text");

   // Initialize arguments.
   Font myFont(L"Arial", 16);
   PointF origin(0.0f, 0.0f);
   SolidBrush blackBrush(Color(255, 0, 0, 0));
   StringFormat format;
   format.SetAlignment(StringAlignmentCenter);

   // Draw string.
   graphics.DrawString(
   string,
   wcslen(string),
   &myFont,
   origin,
   &format,
   &blackBrush);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Font, Pen, PointF, StringFormat


Graphics::EndContainer(state)

The EndContainer method closes a graphics container that was previously opened by the BeginContainer method.

Status EndContainer(
  GraphicsContainer state
);

Parameters

state
[in] Value (previously returned by BeginContainer) that identifies the container to be closed.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

When you call the BeginContainer method of a Graphics object, an information block that holds the state of the Graphics object is put on a stack. The BeginContainer method returns a value that identifies that information block. When you pass the identifying value to the EndContainer method, the information block is removed from the stack and is used to restore the Graphics object to the state it was in at the time of the BeginContainer call.

Containers can be nested; that is, you can call the BeginContainer method several times before you call the EndContainer method. Each time you call the BeginContainer method, an information block is put on the stack, and you receive an identifier for the information block. When you pass one of those identifiers to the EndContainer method, the Graphics object is returned to the state it was in at the time of the BeginContainer call that returned that particular identifier. The information block placed on the stack by that BeginContainer call is removed from the stack, and all information blocks placed on that stack after that BeginContainer call are also removed.

Calls to the Save method place information blocks on the same stack as calls to the BeginContainer method. Just as an EndContainer call is paired with a BeginContainer call, a Restore call is paired with a Save call.

Caution When you call EndContainer, all information blocks placed on the stack (by Save or by BeginContainer) after the corresponding call to BeginContainer are removed from the stack. Likewise, when you call Restore, all information blocks placed on the stack (by Save or by BeginContainer) after the corresponding call to Save are removed from the stack.

Example Code [C++]

The following example creates a Graphics object and sets its clipping region. The code begins a container and sets an additional clipping region for the container. The code fills a rectangle twice: once inside the container, and once outside the container (after the call to EndContainer).

VOID Example_EndContainer(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the clipping region for the Graphics object.
   graphics.SetClip(Rect(10, 10, 150, 150));

   // Begin a graphics container.
   GraphicsContainer container = graphics.BeginContainer();

   // Set an additional clipping region for the container.
   graphics.SetClip(Rect(100, 50, 100, 75));

   // Fill a red rectangle in the container.
   SolidBrush redBrush(Color(255, 255, 0, 0));
   graphics.FillRectangle(&redBrush, 0, 0, 200, 200);

   // End the container, and fill the same rectangle with blue.
   graphics.EndContainer(container);
   SolidBrush blueBrush(Color(128, 0, 0, 255));
   graphics.FillRectangle(&blueBrush, 0, 0, 200, 200);

   // Set the clipping region to infinite, and draw
   // the two previous clipping regions.
   graphics.ResetClip();
   Pen blackPen(Color(255, 0, 0, 0), 2.0f);
   graphics.DrawRectangle(&blackPen, 10, 10, 150, 150);
   graphics.DrawRectangle(&blackPen, 100, 50, 100, 75);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
BeginContainer, Restore, Save
Tasks and Examples
Using Graphics Containers
Concepts
Graphics Containers


Graphics::EnumerateMetafile Methods

This topic lists the EnumerateMetafile methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • EnumerateMetafile(Metafile* metafile, Point& destPoint, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, PointF& destPoint, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, Point& destPoint, Rect& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, PointF& destPoint, RectF& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, Point* destPoints, INT count, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, PointF* destPoints, INT count, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, Point* destPoints, INT count, Rect& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, PointF* destPoints, INT count, RectF& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, Rect& destRect, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, RectF& destRect, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, Rect& destRect, Rect& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)
  • EnumerateMetafile(Metafile* metafile, RectF& destRect, RectF& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)


Graphics::EnumerateMetafile(Metafile* metafile, Point& destPoint, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)

The EnumerateMetafile method calls an application-defined callback function for each record in a specified metafile. You can use this method to display a metafile by calling Metafile::PlayRecord in the callback function.

Status EnumerateMetafile(
  const Metafile* metafile,
  const Point& destPoint,
  EnumerateMetafileProc callback,
  VOID* callbackData,
  ImageAttributes* imageAttributes
);

Parameters

metafile
[in] Pointer to a metafile to be enumerated.
destPoint
[in] Reference to a point that specifies the upper-left corner of the displayed metafile.
callback
[in] Pointer to an application-defined callback function. The prototype for the callback function is given in Gdiplustypes.h.
callbackData
[in] Optional. Pointer to a block of data that is passed to the callback function. The default value is NULL.
imageAttributes
[in] Optional. Pointer to an ImageAttributes object that specifies color adjustments for the displayed metafile. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object and writes two records to the metafile. Then the code passes the address of that Metafile object to the EnumerateMetafile method. The EnumerateMetafile method calls the callback function (metaCallback) for each of the records in the metafile. The callback function plays only one of the two records in the metafile, namely the one that has a record type of EmfPlusRecordTypeFillEllipse.

Note that the argument passed to the callbackData parameter is the address of the Metafile object that is being enumerated. The callback function must have that pointer so that it can call the PlayRecord method of the Metafile object that is being enumerated.

BOOL CALLBACK metaCallback(
   EmfPlusRecordType recordType,
   unsigned int flags,
   unsigned int dataSize,
   const unsigned char* pStr,
   void* callbackData)
{
   // Play only EmfPlusRecordTypeFillEllipse records.
   if (recordType == EmfPlusRecordTypeFillEllipse)
   {
   // Explicitly cast callbackData as a metafile pointer, and use it to call
   // the PlayRecord method.
   static_cast < Metafile* > (callbackData)->PlayRecord(recordType, flags, dataSize, pStr);
   }

   return TRUE;
}

VOID Example_EnumerateMetafile(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Metafile object from an existing disk metafile.
   Metafile* pMeta = new Metafile(L"SampleMetafile.emf", hdc);
   {
      // Fill a rectangle and an ellipse in pMeta.
      Graphics metaGraphics(pMeta);
      SolidBrush blackBrush(Color(255, 0, 0, 0));
      SolidBrush redBrush(Color(255, 255, 0, 0));
      metaGraphics.FillRectangle(&blackBrush 0, 0, 100, 100);
  metaGraphics.FillEllipse(&redBrush 100, 0, 200, 100);
   }
   // Enumerate pMeta, passing pMeta as the callback data.
   graphics.EnumerateMetafile(pMeta, Point(0, 0), metaCallback, pMeta);
   graphics.DrawImage(pMeta, Point(0, 150));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::EnumerateMetafile(Metafile* metafile, PointF& destPoint, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)

The EnumerateMetafile method calls an application-defined callback function for each record in a specified metafile. You can use this method to display a metafile by calling Metafile::PlayRecord in the callback function.

Status EnumerateMetafile(
  const Metafile* metafile,
  const PointF& destPoint,
  EnumerateMetafileProc callback,
  VOID* callbackData,
  ImageAttributes* imageAttributes
);

Parameters

metafile
[in] Pointer to a metafile to be enumerated.
destPoint
[in] Reference to a point that specifies the upper-left corner of the displayed metafile.
callback
[in] Pointer to an application-defined callback function. The prototype for the callback function is given in Gdiplustypes.h.
callbackData
[in] Optional. Pointer to a block of data that is passed to the callback function. The default value is NULL.
imageAttributes
[in] Optional. Pointer to an ImageAttributes object that specifies color adjustments for the displayed metafile. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object and writes two records to the metafile. Then the code passes the address of that Metafile object to the EnumerateMetafile method. The EnumerateMetafile method calls the callback function (metaCallback) for each of the records in the metafile. The callback function plays only one of the two records in the metafile, namely the one that has a record type of EmfPlusRecordTypeFillEllipse.

Note that the argument passed to the callbackData parameter is the address of the Metafile object that is being enumerated. The callback function must have that pointer so that it can call the PlayRecord method of the Metafile object that is being enumerated.

BOOL CALLBACK metaCallback(
   EmfPlusRecordType recordType,
   unsigned int flags,
   unsigned int dataSize,
   const unsigned char* pStr,
   void* callbackData)
{
   // Play only EmfPlusRecordTypeFillEllipse records.
   if (recordType == EmfPlusRecordTypeFillEllipse)
   {
   // Explicitly cast callbackData as a metafile pointer, and use it to call
   // the PlayRecord method.
   static_cast < Metafile* > (callbackData)->PlayRecord(recordType, flags, dataSize, pStr);
   }

   return TRUE;
}

VOID Example_EnumerateMetafile3(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Metafile object from an existing disk metafile.
   Metafile* pMeta = new Metafile(L"SampleMetafile.emf", hdc);
   {
      // Fill a rectangle and an ellipse in pMeta.
      Graphics metaGraphics(pMeta);
      metaGraphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 100, 100);
  metaGraphics.FillEllipse(&SolidBrush(Color(255, 255, 0, 0)), 100, 0, 200, 100);
   }
   // Enumerate pMeta, passing pMeta as the callback data.
   graphics.EnumerateMetafile(pMeta, PointF(0.0f, 0.0f), metaCallback, pMeta);
   graphics.DrawImage(pMeta, Point(0, 150));

   delete pMeta;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::EnumerateMetafile(Metafile* metafile, Point& destPoint, Rect& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)

The EnumerateMetafile method calls an application-defined callback function for each record in a specified metafile. You can use this method to display a metafile by calling Metafile::PlayRecord in the callback function.

Status EnumerateMetafile(
  const Metafile* metafile,
  const Point& destPoint,
  const Rect& srcRect,
  Unit srcUnit,
  EnumerateMetafileProc callback,
  VOID* callbackData,
  ImageAttributes* imageAttributes
);

Parameters

metafile
[in] Pointer to a metafile to be enumerated.
destPoint
[in] Reference to a point that specifies the upper-left corner of the displayed metafile.
srcRect
[in] Reference to a rectangle that specifies the portion of the metafile that is displayed.
srcUnit
[in] Element of the Unit enumeration that specifies the unit of measure for the source rectangle.
callback
[in] Pointer to an application-defined callback function. The prototype for the callback function is given in Gdiplustypes.h.
callbackData
[in] Optional. Pointer to a block of data that is passed to the callback function. The default value is NULL.
imageAttributes
[in] Optional. Pointer to an ImageAttributes object that specifies color adjustments for the displayed metafile. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object and writes two records to the metafile. Then the code passes the address of that Metafile object to the EnumerateMetafile method. The EnumerateMetafile method calls the callback function (metaCallback) for each of the records in the metafile. The callback function plays only one of the two records in the metafile, namely the one that has a record type of EmfPlusRecordTypeFillEllipse.

Note that the argument passed to the callbackData parameter is the address of the Metafile object that is being enumerated. The callback function must have that pointer so that it can call the PlayRecord method of the Metafile object that is being enumerated.

BOOL CALLBACK metaCallback(
   EmfPlusRecordType recordType,
   unsigned int flags,
   unsigned int dataSize,
   const unsigned char* pStr,
   void* callbackData)
{
   // Play only EmfPlusRecordTypeFillEllipse records.
   if (recordType == EmfPlusRecordTypeFillEllipse)
   {
   // Explicitly cast callbackData as a metafile pointer, and use it to call
   // the PlayRecord method.
   static_cast < Metafile* > (callbackData)->PlayRecord(recordType, flags, dataSize, pStr);
   }

   return TRUE;
}

VOID Example_EnumerateMetafile2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Metafile object from an existing disk metafile.
   Metafile* pMeta = new Metafile(L"SampleMetafile.emf", hdc);
   {
      // Fill a rectangle and an ellipse in pMeta.
      Graphics metaGraphics(pMeta);
      metaGraphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 100, 100);
      metaGraphics.FillEllipse(&SolidBrush(Color(255, 255, 0, 0)), 100, 0, 200, 100);
   }
   // Enumerate a portion of pMeta, passing pMeta as the callback data.
   graphics.EnumerateMetafile(
   pMeta,
   Point(0, 0),
   Rect(0, 0, 300, 50),
   UnitPixel,
   metaCallback,
   pMeta);

   // Draw pMeta as an image.
   graphics.DrawImage(pMeta, Point(0, 150));

   delete pMeta;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::EnumerateMetafile(Metafile* metafile, PointF& destPoint, RectF& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)

The EnumerateMetafile method calls an application-defined callback function for each record in a specified metafile. You can use this method to display a metafile by calling Metafile::PlayRecord in the callback function.

Status EnumerateMetafile(
  const Metafile* metafile,
  const PointF& destPoint,
  const RectF& srcRect,
  Unit srcUnit,
  EnumerateMetafileProc callback,
  VOID* callbackData,
  ImageAttributes* imageAttributes
);

Parameters

metafile
[in] Pointer to a metafile to be enumerated.
destPoint
[in] Reference to a point that specifies the upper-left corner of the displayed metafile.
srcRect
[in] Reference to a rectangle that specifies the portion of the metafile that is displayed.
srcUnit
[in] Element of the Unit enumeration that specifies the unit of measure for the source rectangle.
callback
[in] Pointer to an application-defined callback function. The prototype for the callback function is given in Gdiplustypes.h.
callbackData
[in] Optional. Pointer to a block of data that is passed to the callback function. The default value is NULL.
imageAttributes
[in] Optional. Pointer to an ImageAttributes object that specifies color adjustments for the displayed metafile. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object and writes two records to the metafile. Then the code passes the address of that Metafile object to the EnumerateMetafile method. The EnumerateMetafile method calls the callback function (metaCallback) for each of the records in the metafile. The callback function plays only one of the two records in the metafile, namely the one that has a record type of EmfPlusRecordTypeFillEllipse.

Note that the argument passed to the callbackData parameter is the address of the Metafile object that is being enumerated. The callback function must have that pointer so that it can call the PlayRecord method of the Metafile object that is being enumerated.

BOOL CALLBACK metaCallback(
   EmfPlusRecordType recordType,
   unsigned int flags,
   unsigned int dataSize,
   const unsigned char* pStr,
   void* callbackData)
{
   // Play only EmfPlusRecordTypeFillEllipse records.
   if (recordType == EmfPlusRecordTypeFillEllipse)
   {
   // Explicitly cast callbackData as a metafile pointer, and use it to call
   // the PlayRecord method.
   static_cast < Metafile* > (callbackData)->PlayRecord(recordType, flags, dataSize, pStr);
   }

   return TRUE;
}

VOID Example_EnumerateMetafile4(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Metafile object from an existing disk metafile.
   Metafile* pMeta = new Metafile(L"SampleMetafile.emf", hdc);
   {
      // Fill a rectangle and an ellipse in pMeta.
      Graphics metaGraphics(pMeta);
      metaGraphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 100, 100);
  metaGraphics.FillEllipse(&SolidBrush(Color(255, 255, 0, 0)), 100, 0, 200, 100);
   }
   // Enumerate a portion of pMeta, passing pMeta as the callback data.
   graphics.EnumerateMetafile(
   pMeta,
   PointF(0.0f, 0.0f),
   RectF(0.0f, 0.0f, 300.0f, 50.0f),
   UnitPixel,
   metaCallback,
   pMeta);

   // Draw pMeta as an image.
   graphics.DrawImage(pMeta, Point(0, 150));

   delete pMeta;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::EnumerateMetafile(Metafile* metafile, Point* destPoints, INT count, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)

The EnumerateMetafile method calls an application-defined callback function for each record in a specified metafile. You can use this method to display a metafile by calling Metafile::PlayRecord in the callback function.

Status EnumerateMetafile(
  const Metafile* metafile,
  const Point* destPoints,
  INT count,
  EnumerateMetafileProc callback,
  VOID* callbackData,
  ImageAttributes* imageAttributes
);

Parameters

metafile
[in] Pointer to a metafile to be enumerated.
destPoints
[in] Pointer to an array of destination points. This is an array of three points that define the destination parallelogram for the displayed metafile.
count
[in] Integer that specifies the number of points in the destPoints array.
callback
[in] Pointer to an application-defined callback function. The prototype for the callback function is given in Gdiplustypes.h.
callbackData
[in] Optional. Pointer to a block of data that is passed to the callback function. The default value is NULL.
imageAttributes
[in] Optional. Pointer to an ImageAttributes object that specifies color adjustments for the displayed metafile. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object and writes two records to the metafile. Then the code passes the address of that Metafile object to the EnumerateMetafile method. The EnumerateMetafile method calls the callback function (metaCallback) for each of the records in the metafile. The callback function plays only one of the two records in the metafile, namely the one that has a record type of EmfPlusRecordTypeFillEllipse.

Note that the argument passed to the callbackData parameter is the address of the Metafile object that is being enumerated. The callback function must have that pointer so that it can call the PlayRecord method of the Metafile object that is being enumerated.

BOOL CALLBACK metaCallback(
   EmfPlusRecordType recordType,
   unsigned int flags,
   unsigned int dataSize,
   const unsigned char* pStr,
   void* callbackData)
{
   // Play only EmfPlusRecordTypeFillEllipse records.
   if (recordType == EmfPlusRecordTypeFillEllipse)
   {
   // Explicitly cast callbackData as a metafile pointer, and use it to call
   // the PlayRecord method.
   static_cast < Metafile* > (callbackData)->PlayRecord(recordType, flags, dataSize, pStr);
   }

   return TRUE;
}

VOID Example_EnumerateMetafile5(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Metafile object from an existing disk metafile.
   Metafile* pMeta = new Metafile(L"SampleMetafile.emf", hdc);
   {
      // Fill a rectangle and an ellipse in pMeta.
      Graphics metaGraphics(pMeta);
      metaGraphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 100, 100);
  metaGraphics.FillEllipse(&SolidBrush(Color(255, 255, 0, 0)), 100, 0, 200, 100);
   }
   // Set up the destination rectangle.
   Point points[] = {Point(0, 0), Point(300, 0), Point(0, 50)};
   Point* pPoints = points;

   // Enumerate pMeta to the destination rectangle, passing pMeta as the callback data.
   graphics.EnumerateMetafile(
   pMeta,
   pPoints,
   3,
   metaCallback,
   pMeta);

   // Draw pMeta as an image.
   graphics.DrawImage(pMeta, Point(0, 150));

   delete pMeta;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::EnumerateMetafile(Metafile* metafile, PointF* destPoints, INT count, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)

The EnumerateMetafile method calls an application-defined callback function for each record in a specified metafile. You can use this method to display a metafile by calling Metafile::PlayRecord in the callback function.

Status EnumerateMetafile(
  const Metafile* metafile,
  const PointF* destPoints,
  INT count,
  EnumerateMetafileProc callback,
  VOID* callbackData,
  ImageAttributes* imageAttributes
);

Parameters

metafile
[in] Pointer to a metafile to be enumerated.
destPoints
[in] Pointer to an array of destination points. This is an array of three points that defines the destination parallelogram for the displayed metafile.
count
[in] Integer that specifies the number of points in the destPoints array.
callback
[in] Pointer to an application-defined callback function. The prototype for the callback function is given in Gdiplustypes.h.
callbackData
[in] Optional. Pointer to a block of data that is passed to the callback function. The default value is NULL.
imageAttributes
[in] Optional. Pointer to an ImageAttributes object that specifies color adjustments for the displayed metafile. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object and writes two records to the metafile. Then the code passes the address of that Metafile object to the EnumerateMetafile method. The EnumerateMetafile method calls the callback function (metaCallback) for each of the records in the metafile. The callback function plays only one of the two records in the metafile, namely the one that has a record type of EmfPlusRecordTypeFillEllipse.

Note that the argument passed to the callbackData parameter is the address of the Metafile object that is being enumerated. The callback function must have that pointer so that it can call the PlayRecord method of the Metafile object that is being enumerated.

BOOL CALLBACK metaCallback(
   EmfPlusRecordType recordType,
   unsigned int flags,
   unsigned int dataSize,
   const unsigned char* pStr,
   void* callbackData)
{
   // Play only EmfPlusRecordTypeFillEllipse records.
   if (recordType == EmfPlusRecordTypeFillEllipse)
   {
   // Explicitly cast callbackData as a metafile pointer, and use it to call
   // the PlayRecord method.
   static_cast < Metafile* > (callbackData)->PlayRecord(recordType, flags, dataSize, pStr);
   }

   return TRUE;
}

VOID Example_EnumerateMetafile7(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Metafile object from an existing disk metafile.
   Metafile* pMeta = new Metafile(L"SampleMetafile.emf", hdc);
   {
      // Fill a rectangle and an ellipse in pMeta.
      Graphics metaGraphics(pMeta);
      metaGraphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 100, 100);
  metaGraphics.FillEllipse(&SolidBrush(Color(255, 255, 0, 0)), 100, 0, 200, 100);
   }
   // Set up the destination rectangle.
   PointF points[] = {PointF(0..0f, 0.0f), PointF(300.0f, 0.0f), PointF(0.0f, 50.0f)};
   PointF* pPoints = points;

   // Enumerate pMeta to the destination rectangle, passing pMeta as the callback data.
   graphics.EnumerateMetafile(
   pMeta,
   pPoints,
   3,
   metaCallback,
   pMeta);

   // Draw pMeta as an image.
   graphics.DrawImage(pMeta, Point(0, 150));

   delete pMeta;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::EnumerateMetafile(Metafile* metafile, Point* destPoints, INT count, Rect& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)

The EnumerateMetafile method calls an application-defined callback function for each record in a specified metafile. You can use this method to display a metafile by calling Metafile::PlayRecord in the callback function.

Status EnumerateMetafile(
  const Metafile* metafile,
  const Point* destPoints,
  INT count,
  const Rect& srcRect,
  Unit srcUnit,
  EnumerateMetafileProc callback,
  VOID* callbackData,
  ImageAttributes* imageAttributes
);

Parameters

metafile
[in] Pointer to a metafile to be enumerated.
destPoints
[in] Pointer to an array of destination points. This is an array of three points that defines the destination parallelogram for the displayed metafile.
count
[in] Integer that specifies the number of points in the destPoints array.
srcRect
[in] Reference to a rectangle that specifies the portion of the metafile that is displayed.
srcUnit
[in] Element of the Unit enumeration that specifies the unit of measure for the source rectangle.
callback
[in] Pointer to an application-defined callback function. The prototype for the callback function is given in Gdiplustypes.h.
callbackData
[in] Optional. Pointer to a block of data that is passed to the callback function. The default value is NULL.
imageAttributes
[in] Optional. Pointer to an ImageAttributes object that specifies color adjustments for the displayed metafile. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object and writes two records to the metafile. Then the code passes the address of that Metafile object to the EnumerateMetafile method. The EnumerateMetafile method calls the callback function (metaCallback) for each of the records in the metafile. The callback function plays only one of the two records in the metafile, namely the one that has a record type of EmfPlusRecordTypeFillEllipse.

Note that the argument passed to the callbackData parameter is the address of the Metafile object that is being enumerated. The callback function must have that pointer so that it can call the PlayRecord method of the Metafile object that is being enumerated.

BOOL CALLBACK metaCallback(
   EmfPlusRecordType recordType,
   unsigned int flags,
   unsigned int dataSize,
   const unsigned char* pStr,
   void* callbackData)
{
   // Play only EmfPlusRecordTypeFillEllipse records.
   if (recordType == EmfPlusRecordTypeFillEllipse)
   {
   // Explicitly cast callbackData as a metafile pointer, and use it to call
   // the PlayRecord method.
   static_cast < Metafile* > (callbackData)->PlayRecord(recordType, flags, dataSize, pStr);
   }

   return TRUE;
}

VOID Example_EnumerateMetafile6(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Metafile object from an existing disk metafile.
   Metafile* pMeta = new Metafile(L"SampleMetafile.emf", hdc);
   {
      // Fill a rectangle and an ellipse in pMeta.
      Graphics metaGraphics(pMeta);
      metaGraphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 100, 100);
  metaGraphics.FillEllipse(&SolidBrush(Color(255, 255, 0, 0)), 100, 0, 200, 100);
   }

   //Set up a destination rectangle.
   Point points[] = {Point(0, 0), Point(300, 0), Point(0, 50)};
   Point* pPoints = points;

   // Enumerate a portion of pMeta, passing pMeta as the callback data.
   graphics.EnumerateMetafile(
   pMeta,
   pPoints,
   3,
   Rect(0, 0, 300, 50),
   UnitPixel,
   metaCallback,
   pMeta);

   // Draw pMeta as an image.
   graphics.DrawImage(pMeta, Point(0, 150));

   delete pMeta;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::EnumerateMetafile(Metafile* metafile, PointF* destPoints, INT count, RectF& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)

The EnumerateMetafile method calls an application-defined callback function for each record in a specified metafile. You can use this method to display a metafile by calling Metafile::PlayRecord in the callback function.

Status EnumerateMetafile(
  const Metafile* metafile,
  const PointF* destPoints,
  INT count,
  const RectF& srcRect,
  Unit srcUnit,
  EnumerateMetafileProc callback,
  VOID* callbackData,
  ImageAttributes* imageAttributes
);

Parameters

metafile
[in] Pointer to a metafile to be enumerated.
destPoints
[in] Pointer to an array of destination points. This is an array of three points that defines the destination parallelogram for the displayed metafile.
count
[in] Integer that specifies the number of points in the destPoints array.
srcRect
[in] Reference to the rectangle that specifies the portion of the metafile that is displayed.
srcUnit
[in] Element of the Unit enumeration that specifies the unit of measure for the source rectangle.
callback
[in] Pointer to an application-defined callback function. The prototype for the callback function is given in Gdiplustypes.h.
callbackData
[in] Optional. Pointer to a block of data that is passed to the callback function. The default value is NULL.
imageAttributes
[in] Optional. Pointer to an ImageAttributes object that specifies color adjustments for the displayed metafile. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object and writes two records to the metafile. Then the code passes the address of that Metafile object to the EnumerateMetafile method. The EnumerateMetafile method calls the callback function (metaCallback) for each of the records in the metafile. The callback function plays only one of the two records in the metafile, namely the one that has a record type of EmfPlusRecordTypeFillEllipse.

Note that the argument passed to the callbackData parameter is the address of the Metafile object that is being enumerated. The callback function must have that pointer so that it can call the PlayRecord method of the Metafile object that is being enumerated.

BOOL CALLBACK metaCallback(
   EmfPlusRecordType recordType,
   unsigned int flags,
   unsigned int dataSize,
   const unsigned char* pStr,
   void* callbackData)
{
   // Play only EmfPlusRecordTypeFillEllipse records.
   if (recordType == EmfPlusRecordTypeFillEllipse)
   {
   // Explicitly cast callbackData as a metafile pointer, and use it to call
   // the PlayRecord method.
   static_cast < Metafile* > (callbackData)->PlayRecord(recordType, flags, dataSize, pStr);
   }

   return TRUE;
}

VOID Example_EnumerateMetafile8(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Metafile object from an existing disk metafile.
   Metafile* pMeta = new Metafile(L"SampleMetafile.emf", hdc);
   {
      // Fill a rectangle and an ellipse in pMeta.
      Graphics metaGraphics(pMeta);
      metaGraphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 100, 100);
  metaGraphics.FillEllipse(&SolidBrush(Color(255, 255, 0, 0)), 100, 0, 200, 100);
   }
   //Set up a destination rectangle.
   PointF points[] = {PointF(0.0f, 0.0f), PointF(300.0f, 0.0f), PointF(0.0f, 50.0f)};
   PointF* pPoints = points;

   // Enumerate a portion of pMeta, passing pMeta as the callback data.
   graphics.EnumerateMetafile(
   pMeta,
   pPoints,
   3,
   RectF(0.0f, 0.0f, 300.0f, 50.0f),
   UnitPixel,
   metaCallback,
   pMeta);

   // Draw pMeta as an image.
   graphics.DrawImage(pMeta, Point(0, 150));

   delete pMeta;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::EnumerateMetafile(Metafile* metafile, Rect& destRect, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)

The EnumerateMetafile method calls an application-defined callback function for each record in a specified metafile. You can use this method to display a metafile by calling Metafile::PlayRecord in the callback function.

Status EnumerateMetafile(
  const Metafile* metafile,
  const Rect& destRect,
  EnumerateMetafileProc callback,
  VOID* callbackData,
  ImageAttributes* imageAttributes
);

Parameters

metafile
[in] Pointer to a metafile to be enumerated.
destRect
[in] Reference to a Rect object that specifies the rectangle in which the metafile is displayed.
callback
[in] Pointer to an application-defined callback function. The prototype for the callback function is given in Gdiplustypes.h.
callbackData
[in] Optional. Pointer to a block of data that is passed to the callback function. The default value is NULL.
imageAttributes
[in] Optional. Pointer to an ImageAttributes object that specifies color adjustments for the displayed metafile. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object and writes two records to the metafile. Then the code passes the address of that Metafile object to the EnumerateMetafile method. The EnumerateMetafile method calls the callback function (metaCallback) for each of the records in the metafile. The callback function plays only one of the two records in the metafile, namely the one that has a record type of EmfPlusRecordTypeFillEllipse.

Note that the argument passed to the callbackData parameter is the address of the Metafile object that is being enumerated. The callback function must have that pointer so that it can call the PlayRecord method of the Metafile object that is being enumerated.

BOOL CALLBACK metaCallback(
   EmfPlusRecordType recordType,
   unsigned int flags,
   unsigned int dataSize,
   const unsigned char* pStr,
   void* callbackData)
{
   // Play only EmfPlusRecordTypeFillEllipse records.
   if (recordType == EmfPlusRecordTypeFillEllipse)
   {
   // Explicitly cast callbackData as a metafile pointer, and use it to call
   // the PlayRecord method.
   static_cast < Metafile* > (callbackData)->PlayRecord(recordType, flags, dataSize, pStr);
   }

   return TRUE;
}

VOID Example_EnumerateMetafile9(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Metafile object from an existing disk metafile.
   Metafile* pMeta = new Metafile(L"SampleMetafile.emf", hdc);
   {
      // Fill a rectangle and an ellipse in pMeta.
      Graphics metaGraphics(pMeta);
      metaGraphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 100, 100);
  metaGraphics.FillEllipse(&SolidBrush(Color(255, 255, 0, 0)), 100, 0, 200, 100);
   }
   // Enumerate pMeta to the destination rectangle, passing pMeta as the callback data.
   graphics.EnumerateMetafile(
   pMeta,
   Rect(0, 0, 300, 50),
   metaCallback,
   pMeta);

   // Draw pMeta as an image.
   graphics.DrawImage(pMeta, Point(0, 150));

   delete pMeta;;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::EnumerateMetafile(Metafile* metafile, RectF& destRect, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)

The EnumerateMetafile method calls an application-defined callback function for each record in a specified metafile. You can use this method to display a metafile by calling Metafile::PlayRecord in the callback function.

Status EnumerateMetafile(
  const Metafile* metafile,
  const RectF& destRect,
  EnumerateMetafileProc callback,
  VOID* callbackData,
  ImageAttributes* imageAttributes
);

Parameters

metafile
[in] Pointer to a metafile to be enumerated.
destRect
[in] Reference to a RectF object that specifies the rectangle in which the metafile is displayed.
callback
[in] Pointer to an application-defined callback function. The prototype for the callback function is given in Gdiplustypes.h.
callbackData
[in] Optional. Pointer to a block of data that is passed to the callback function. The default value is NULL.
imageAttributes
[in] Optional. Pointer to an ImageAttributes object that specifies color adjustments for the displayed metafile. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object and writes two records to the metafile. Then the code passes the address of that Metafile object to the EnumerateMetafile method. The EnumerateMetafile method calls the callback function (metaCallback) for each of the records in the metafile. The callback function plays only one of the two records in the metafile, namely the one that has a record type of EmfPlusRecordTypeFillEllipse.

Note that the argument passed to the callbackData parameter is the address of the Metafile object that is being enumerated. The callback function must have that pointer so that it can call the PlayRecord method of the Metafile object that is being enumerated.

BOOL CALLBACK metaCallback(
   EmfPlusRecordType recordType,
   unsigned int flags,
   unsigned int dataSize,
   const unsigned char* pStr,
   void* callbackData)
{
   // Play only EmfPlusRecordTypeFillEllipse records.
   if (recordType == EmfPlusRecordTypeFillEllipse)
   {
   // Explicitly cast callbackData as a metafile pointer, and use it to call
   // the PlayRecord method.
   static_cast < Metafile* > (callbackData)->PlayRecord(recordType, flags, dataSize, pStr);
   }

   return TRUE;
}

VOID Example_EnumerateMetafile11(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Metafile object from an existing disk metafile.
   Metafile* pMeta = new Metafile(L"SampleMetafile.emf", hdc);
   {
      // Fill a rectangle and an ellipse in pMeta.
      Graphics metaGraphics(pMeta);
      metaGraphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 100, 100);
  metaGraphics.FillEllipse(&SolidBrush(Color(255, 255, 0, 0)), 100, 0, 200, 100);
   }
   // Enumerate pMeta to the destination rectangle, passing pMeta as the callback data.
   graphics.EnumerateMetafile(
   pMeta,
   RectF(0.0f, 0.0f, 300.0f, 50.0f),
   metaCallback,
   pMeta);

   // Draw pMeta as an image.
   graphics.DrawImage(pMeta, Point(0, 150));

   delete pMeta;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::EnumerateMetafile(Metafile* metafile, Rect& destRect, Rect& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)

The EnumerateMetafile method calls an application-defined callback function for each record in a specified metafile. You can use this method to display a metafile by calling Metafile::PlayRecord in the callback function.

Status EnumerateMetafile(
  const Metafile* metafile,
  const Rect& destRect,
  const Rect& srcRect,
  Unit srcUnit,
  EnumerateMetafileProc callback,
  VOID* callbackData,
  ImageAttributes* imageAttributes
);

Parameters

metafile
[in] Pointer to a metafile to be enumerated.
destRect
[in] Reference to a Rect object that specifies the rectangle in which the metafile is displayed.
srcRect
[in] Reference to a Rect object that specifies the portion of the metafile that is displayed.
srcUnit
[in] Element of the Unit enumeration that specifies the unit of measure for the source rectangle.
callback
[in] Pointer to an application-defined callback function. The prototype for the callback function is given in Gdiplustypes.h.
callbackData
[in] Optional. Pointer to a block of data that is passed to the callback function. The default value is NULL.
imageAttributes
[in] Optional. Pointer to an ImageAttributes object that specifies color adjustments for the displayed metafile. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object and writes two records to the metafile. Then the code passes the address of that Metafile object to the EnumerateMetafile method. The EnumerateMetafile method calls the callback function (metaCallback) for each of the records in the metafile. The callback function plays only one of the two records in the metafile, namely the one that has a record type of EmfPlusRecordTypeFillEllipse.

Note that the argument passed to the callbackData parameter is the address of the Metafile object that is being enumerated. The callback function must have that pointer so that it can call the PlayRecord method of the Metafile object that is being enumerated.

BOOL CALLBACK metaCallback(
   EmfPlusRecordType recordType,
   unsigned int flags,
   unsigned int dataSize,
   const unsigned char* pStr,
   void* callbackData)
{
   // Play only EmfPlusRecordTypeFillEllipse records.
   if (recordType == EmfPlusRecordTypeFillEllipse)
   {
   // Explicitly cast callbackData as a metafile pointer, and use it to call
   // the PlayRecord method.
   static_cast < Metafile* > (callbackData)->PlayRecord(recordType, flags, dataSize, pStr);
   }

   return TRUE;
}

VOID Example_EnumerateMetafile10(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Metafile object from an existing disk metafile.
   Metafile* pMeta = new Metafile(L"SampleMetafile.emf", hdc);
   {
      // Fill a rectangle and an ellipse in pMeta.
      Graphics metaGraphics(pMeta);
      metaGraphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 100, 100);
  metaGraphics.FillEllipse(&SolidBrush(Color(255, 255, 0, 0)), 100, 0, 200, 100);
   }
   // Enumerate a portion of pMeta to the destination rectangle, passing pMeta as the callback data.
   graphics.EnumerateMetafile(
   pMeta,
   Rect(0, 0, 300, 50),
   Rect(0, 0, 300, 50),
   UnitPixel,
   metaCallback,
   pMeta);

   // Draw pMeta as an image.
   graphics.DrawImage(pMeta, Point(0, 150));

   delete pMeta;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::EnumerateMetafile(Metafile* metafile, RectF& destRect, RectF& srcRect, Unit srcUnit, EnumerateMetafileProc callback, VOID* callbackData, ImageAttributes* imageAttributes)

The EnumerateMetafile method calls an application-defined callback function for each record in a specified metafile. You can use this method to display a metafile by calling Metafile::PlayRecord in the callback function.

Status EnumerateMetafile(
  const Metafile* metafile,
  const RectF& destRect,
  const RectF& srcRect,
  Unit srcUnit,
  EnumerateMetafileProc callback,
  VOID* callbackData,
  ImageAttributes* imageAttributes
);

Parameters

metafile
[in] Pointer to a metafile to be enumerated.
destRect
[in] Reference to a RectF object that specifies the rectangle in which the metafile is displayed.
srcRect
[in] Reference to a RectF object that specifies the portion of the metafile that is displayed.
srcUnit
[in] Element of the Unit enumeration that specifies the unit of measure for the source rectangle.
callback
[in] Pointer to an application-defined callback function. The prototype for the callback function is given in Gdiplustypes.h.
callbackData
[in] Optional. Pointer to a block of data that is passed to the callback function. The default value is NULL.
imageAttributes
[in] Optional. Pointer to an ImageAttributes object that specifies color adjustments for the displayed metafile. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object and writes two records to the metafile. Then the code passes the address of that Metafile object to the EnumerateMetafile method. The EnumerateMetafile method calls the callback function (metaCallback) for each of the records in the metafile. The callback function plays only one of the two records in the metafile, namely the one that has a record type of EmfPlusRecordTypeFillEllipse.

Note that the argument passed to the callbackData parameter is the address of the Metafile object that is being enumerated. The callback function must have that pointer so that it can call the PlayRecord method of the Metafile object that is being enumerated.

BOOL CALLBACK metaCallback(
   EmfPlusRecordType recordType,
   unsigned int flags,
   unsigned int dataSize,
   const unsigned char* pStr,
   void* callbackData)
{
   // Play only EmfPlusRecordTypeFillEllipse records.
   if (recordType == EmfPlusRecordTypeFillEllipse)
   {
   // Explicitly cast callbackData as a metafile pointer, and use it to call
   // the PlayRecord method.
   static_cast < Metafile* > (callbackData)->PlayRecord(recordType, flags, dataSize, pStr);
   }

   return TRUE;
}

VOID Example_EnumerateMetafile12(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Metafile object from an existing disk metafile.
   Metafile* pMeta = new Metafile(L"SampleMetafile.emf", hdc);
   {
      // Fill a rectangle and an ellipse in pMeta.
      Graphics metaGraphics(pMeta);
      metaGraphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 100, 100);
  metaGraphics.FillEllipse(&SolidBrush(Color(255, 255, 0, 0), 100, 0, 200, 100);
   }

   // Enumerate a portion of pMeta to the destination rectangle, passing pMeta as the callback data.
   graphics.EnumerateMetafile(
   pMeta,
   RectF(0.0f, 0.0f, 300.0f, 50.0f),
   RectF(0.0f, 0.0f, 300.0f, 50.0f),
   UnitPixel,
   metaCallback,
   pMeta);

   // Draw pMeta as an image.
   graphics.DrawImage(pMeta, Point(0, 150));

   delete pMeta;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::ExcludeClip Methods

This topic lists the ExcludeClip methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • ExcludeClip(Rect& rect)
  • ExcludeClip(RectF& rect)
  • ExcludeClip(region)


Graphics::ExcludeClip(Rect& rect)

The ExcludeClip method updates the clipping region to the portion of itself that does not intersect the specified rectangle.

Status ExcludeClip(
  const Rect& rect
);

Parameters

rect
[in] Reference to a rectangle to use to update the clipping region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a clipping region using a rectangle and then draws a rectangle that demonstrates the updated clipping region.

VOID Example_ExcludeClip(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Rect object, and set the clipping region to its exclusion.
   Rect excludeRect(100, 100, 200, 200);
   graphics.ExcludeClip(excludeRect);

   // Fill a rectangle to demonstrate the clipping region.
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 255)), 0, 0, 600, 600);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Graphics::ExcludeClip(RectF& rect)

The ExcludeClip method updates the clipping region to the portion of itself that does not intersect the specified rectangle.

Status ExcludeClip(
  const RectF& rect
);

Parameters

rect
[in] Reference to a rectangle to use to update the clipping region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example uses a rectangle to update a clipping region and then draws a rectangle that demonstrates the updated clipping region.

VOID Example_ExcludeClip2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a RectF object, and set the clipping region to its exclusion.
   RectF excludeRect(100.0f, 100.0f, 200.0f, 200.0f);
   graphics.ExcludeClip(excludeRect);

   // Fill a rectangle to demonstrate the clipping region.
   graphics.FillRectangle(&SolidBrush((255, 0, 0, 255)), 0, 0, 600, 600);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Graphics::ExcludeClip(region)

The ExcludeClip method updates the clipping region with the portion of itself that does not overlap the specified region.

Status ExcludeClip(
  const Region* region
);

Parameters

region
[in] Pointer to the region to use to update the clipping region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example uses a rectangle to update a clipping region and then draws a rectangle that demonstrates the updated clipping region.

VOID Example_ExcludeClip3(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Region object, and set the clipping region to its exclusion.
   Region excludeRegion(Rect(100, 100, 200, 200));
   graphics.ExcludeClip(&excludeRegion);

   // Fill a rectangle to demonstrate the clipping region.
   graphics.FillRectangle(&SolidBrush((255, 0, 0, 255)), 0, 0, 600, 600);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Graphics::FillClosedCurve Methods

This topic lists the FillClosedCurve methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • FillClosedCurve(Brush* brush, Point* points, INT count)
  • FillClosedCurve(Brush* brush, PointF* points, INT count)
  • FillClosedCurve(Brush* brush, Point* points, INT count, FillMode fillMode, REAL tension)
  • FillClosedCurve(Brush* brush, PointF* points, INT count, FillMode fillMode, REAL tension)


Graphics::FillClosedCurve(Brush* brush, Point* points, INT count)

The FillClosedCurve method creates a closed cardinal spline from an array of points and uses a brush to fill the interior of the spline.

Status FillClosedCurve(
  const Brush* brush,
  const Point* points,
  INT count
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the spline.
points
[in] Pointer to an array of points that this method uses to create a closed cardinal spline. Each point in the array is a point on the spline.
count
[in] Integer that specifies the number of points in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example fills a closed cardinal spline.

VOID Example_FillClosedCurve(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   //Create an array of Point objects.
   Point point1(100, 100);
   Point point2(200, 50);
   Point point3(250, 200);
   Point point4(50, 150);
   Point points[4] = {point1, point2, point3, point4};

   //Fill the curve.
   graphics.FillClosedCurve(&blackBrush, points, 4);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Point, SolidBrush
Tasks and Examples
Drawing Cardinal Splines
Concepts
Open and Closed Curves, Cardinal Splines, Brushes and Filled Shapes


Graphics::FillClosedCurve(Brush* brush, PointF* points, INT count)

The FillClosedCurve method creates a closed cardinal spline from an array of points and uses a brush to fill the interior of the spline.

Status FillClosedCurve(
  const Brush* brush,
  const Point* points,
  INT count
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the spline.
points
[in] Pointer to an array of points that this method uses to create a closed cardinal spline. Each point in the array is a point on the spline.
count
[in] Integer that specifies the number of points in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example fills a closed cardinal spline.

VOID Example_FillClosedCurve3(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   //Create an array of PointF objects.
   PointF point1(100.0f, 100.0f);
   PointF point2(200.0f, 50.0f);
   PointF point3(250.0f, 200.0f);
   PointF point4(50.0f, 150.0f);
   PointF points[4] = {point1, point2, point3, point4};

   //Fill the curve.
   graphics.FillClosedCurve(&blackBrush, points, 4);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Point, SolidBrush
Tasks and Examples
Drawing Cardinal Splines
Concepts
Open and Closed Curves, Cardinal Splines, Brushes and Filled Shapes


Graphics::FillClosedCurve(Brush* brush, Point* points, INT count, FillMode fillMode, REAL tension)

The FillClosedCurve method creates a closed cardinal spline from an array of points and uses a brush to fill, according to a specified mode, the interior of the spline.

Status FillClosedCurve(
  const Brush* brush,
  const Point* points,
  INT count,
  FillMode fillMode,
  REAL tension
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the spline.
points
[in] Pointer to an array of points that this method uses to create a closed cardinal spline. Each point in the array is a point on the spline.
count
[in] Integer that specifies the number of points in the points array.
fillMode
[in] Element of the FillMode enumeration that specifies how to fill a closed area that is created when the curve passes over itself.
tension
[in] Optional. Nonnegative real number that specifies how tightly the spline bends as it passes through the points. A value of 0 specifies that the spline is a sequence of straight lines. As the value increases, the curve becomes fuller. The default value is 0.5f.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example fills a closed cardinal spline using FillModeAlternate as the fill mode.

VOID Example_FillClosedCurve2(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   //Create an array of Point objects.
   Point point1(100, 100);
   Point point2(200, 50);
   Point point3(250, 200);
   Point point4(50, 150);
   Point points[4] = {point1, point2, point3, point4};

   //Fill the curve.
   graphics.FillClosedCurve(&blackBrush, points, 4, FillModeAlternate, 1.0);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Brush, FillMode, Point
Tasks and Examples
Drawing Cardinal Splines
Concepts
Open and Closed Curves, Cardinal Splines, Brushes and Filled Shapes


Graphics::FillClosedCurve(Brush* brush, PointF* points, INT count, FillMode fillMode, REAL tension)

The FillClosedCurve method creates a closed cardinal spline from an array of points and uses a brush to fill, according to a specified mode, the interior of the spline.

Status FillClosedCurve(
  const Brush* brush,
  const PointF* points,
  INT count,
  FillMode fillMode,
  REAL tension
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the spline.
points
[in] Pointer to an array of points that this method uses to create a closed cardinal spline. Each point in the array is a point on the spline.
count
[in] Integer that specifies the number of points in the points array.
fillMode
[in] Element of the FillMode enumeration that specifies how to fill a closed area that is created when the curve passes over itself.
tension
[in] Optional. Nonnegative real number that specifies how tightly the spline bends as it passes through the points. A value of 0 specifies that the spline is a sequence of straight lines. As the value increases, the curve becomes fuller. The default value is 0.5f.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example fills a closed cardinal spline.

VOID Example_FillClosedCurve4(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   //Create an array of PointF objects.
   PointF point1(100.0f, 100.0f);
   PointF point2(200.0f, 50.0f);
   PointF point3(250.0f, 200.0f);
   PointF point4(50.0f, 150.0f);
   PointF points[4] = {point1, point2, point3, point4};

   //Fill the curve.
   graphics.FillClosedCurve(&blackBrush, points, 4, FillModeAlternate, 1.0);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Brush, FillMode, Point
Tasks and Examples
Drawing Cardinal Splines
Concepts
Open and Closed Curves, Cardinal Splines, Brushes and Filled Shapes


Graphics::FillEllipse Methods

This topic lists the FillEllipse methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • FillEllipse(Brush* brush, Rect& rect)
  • FillEllipse(Brush* brush, RectF& rect)
  • FillEllipse(Brush* brush, INT x, INT y, INT width, INT height)
  • FillEllipse(Brush* brush, REAL x, REAL y, REAL width, REAL height)


Graphics::FillEllipse(Brush* brush, Rect& rect)

The FillEllipse method uses a brush to fill the interior of an ellipse that is specified by a rectangle.

Status FillEllipse(
  const Brush* brush,
  const Rect& rect
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the ellipse.
rect
[in] Reference to a rectangle that specifies the boundaries of the ellipse.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example fills an ellipse that is defined by a bounding rectangle.

VOID Example_FillEllipse(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Create the Rect object that defines the ellipse.
   Rect ellipseRect(0, 0, 200, 100);

   // Fill the ellipse.
   graphics.FillEllipse(&blackBrush, ellipseRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Rect, SolidBrush
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


Graphics::FillEllipse(Brush* brush, RectF& rect)

The FillEllipse method uses a brush to fill the interior of an ellipse that is specified by a rectangle.

Status FillEllipse(
  const Brush* brush,
  const RectF& rect
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the ellipse.
rect
[in] Reference to a rectangle that specifies the boundaries of the ellipse.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example fills an ellipse defined by a bounding rectangle.

VOID Example_FillEllipse2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Create the RectF object that defines the ellipse.
   RectF ellipseRect(0.0f, 0.6f, 200.8f, 100.9f);

   // Fill the ellipse.
   graphics.FillEllipse(&blackBrush, ellipseRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Brush, RectF
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


Graphics::FillEllipse(Brush* brush, INT x, INT y, INT width, INT height)

The FillEllipse method uses a brush to fill the interior of an ellipse that is specified by coordinates and dimensions.

Status FillEllipse(
  const Brush* brush,
  INT x,
  INT y,
  INT width,
  INT height
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the ellipse.
x
[in] Integer that specifies the x-coordinate of the upper-left corner of the rectangle that specifies the boundaries of the ellipse.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the rectangle that specifies the boundaries of the ellipse.
width
[in] Integer that specifies the width of the rectangle that specifies the boundaries of the ellipse.
height
[in] Integer that specifies the height of the rectangle that specifies the boundaries of the ellipse.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example fills an ellipse that is defined by coordinates and dimensions.

VOID Example_FillEllipse3(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Initialize the variables that define the ellipse.
   int x = 0;
   int y = 0;
   int width = 200;
   int height = 100;

   // Fill the ellipse.
   graphics.FillEllipse(&blackBrush, x, y, width, height);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
SolidBrush
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


Graphics::FillEllipse(Brush* brush, REAL x, REAL y, REAL width, REAL height)

The FillEllipse method uses a brush to fill the interior of an ellipse that is specified by coordinates and dimensions.

Status FillEllipse(
  const Brush* brush,
  REAL x,
  REAL y,
  REAL width,
  REAL height
);

Parameters

brush
[in] Pointer to a brush that is used to paint the interior of the ellipse.
x
[in] Real number that specifies the x-coordinate of the upper-left corner of the rectangle that specifies the boundaries of the ellipse.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the rectangle that specifies the boundaries of the ellipse.
width
[in] Real number that specifies the width of the rectangle that specifies the boundaries of the ellipse.
height
[in] Real number that specifies the height of the rectangle that specifies the boundaries of the ellipse.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example fills an ellipse that is defined by coordinates and dimensions.

VOID Example_FillEllipse4(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Initialize the variables that define the ellipse.
   REAL x = 0.0f;
   REAL y = 0.0f;
   REAL width = 200.1f;
   REAL height = 100.4f;

   // Fill the ellipse.
   graphics.FillEllipse(&blackBrush, x, y, width, height);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
SolidBrush
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


Graphics::FillPath(brush, path)

The FillPath method uses a brush to fill the interior of a path. If a figure in the path is not closed, this method treats the nonclosed figure as if it were closed by a straight line that connects the figure's starting and ending points.

Status FillPath(
  const Brush* brush,
  const GraphicsPath* path
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the path.
path
[in] Pointer to a GraphicsPath object that specifies the path.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example fills a path.

VOID Example_FillPath(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a GraphicsPath and add an ellipse.
   GraphicsPath ellipsePath;
   ellipsePath.AddEllipse(Rect(0, 0, 200, 100));

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Draw ellipsePath.
   graphics.FillPath(&blackBrush, &ellipsePath);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GraphicsPath
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


Graphics::FillPie Methods

This topic lists the FillPie methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • FillPie(Brush* brush, Rect& rect, REAL startAngle, REAL sweepAngle)
  • FillPie(Brush* brush, RectF& rect, REAL startAngle, REAL sweepAngle)
  • FillPie(Brush* brush, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
  • FillPie(Brush* brush, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)


Graphics::FillPie(Brush* brush, Rect& rect, REAL startAngle, REAL sweepAngle)

The FillPie method uses a brush to fill the interior of a pie.

Status FillPie(
  const Brush* brush,
  const Rect& rect,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the pie.
rect
[in] Reference to a rectangle that bounds the ellipse. A curved portion of the ellipse is the arc of the pie.
startAngle
[in] Real number that specifies the angle, in degrees, between the x-axis and the starting point of the pie's arc.
sweepAngle
[in] Real number that specifies the angle, in degrees, between the starting and ending points of the pie's arc.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A pie is a portion of the interior of an ellipse (it is bounded by an elliptical curve and two radial lines). The startAngle and sweepAngle specify the portion of the ellipse to be used.

Example Code [C++]

The following example defines a pie and then fills it.

VOID Example_FillPie(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Define the pie shape.
   Rect ellipseRect(0, 0, 200, 100);
   REAL startAngle = 0.0f;
   REAL sweepAngle = 45.0f;

   // Fill the pie.
   graphics.FillPie(&blackBrush, ellipseRect, startAngle, sweepAngle);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Rect, Status


Graphics::FillPie(Brush* brush, RectF& rect, REAL startAngle, REAL sweepAngle)

The FillPie method uses a brush to fill the interior of a pie.

Status FillPie(
  const Brush* brush,
  const RectF& rect,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the pie.
rect
[in] Reference to a rectangle that bounds the ellipse. A curved portion of the ellipse is the arc of the pie.
startAngle
[in] Real number that specifies the angle, in degrees, between the x-axis and the starting point of the pie's arc.
sweepAngle
[in] Real number that specifies the angle, in degrees, between the starting and ending points of the pie's arc.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A pie is a portion of the interior of an ellipse (it is bounded by an elliptical curve and two radial lines). The startAngle and sweepAngle specify the portion of the ellipse to be used.

Example Code [C++]

The following example defines a pie and then fills it.

VOID Example_FillPie2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Define the pie shape.
   RectF ellipseRect(0.5f, 0.8f, 200.9f, 100.6f);
   REAL startAngle = 0.0;
   REAL sweepAngle = 45.8;

   // Fill the pie.
   graphics.FillPie(&blackBrush, ellipseRect, startAngle, sweepAngle);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Rect, Status


Graphics::FillPie(Brush* brush, INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)

The FillPie method uses a brush to fill the interior of a pie.

Status FillPie(
  const Brush* brush,
  INT x,
  INT y,
  INT width,
  INT height,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the pie.
x
[in] Integer that specifies the x-coordinate of the upper-left corner of the rectangle that bounds the ellipse. A curved portion of the ellipse is the arc of the pie.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the rectangle that bounds the ellipse.
width
[in] Integer that specifies the width of the rectangle that bounds the ellipse.
height
[in] Integer that specifies the height of the rectangle that bounds the ellipse.
startAngle
[in] Real number that specifies the angle, in degrees, between the x-axis and the starting point of the pie's arc.
sweepAngle
[in] Real number that specifies the angle, in degrees, between the starting and ending points of the pie's arc.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A pie is a portion of the interior of an ellipse (it is bounded by an elliptical curve and two radial lines). The startAngle and sweepAngle specify the portion of the ellipse to be used.

Example Code [C++]

The following example defines a pie and then fills it.

VOID Example_FillPie3(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Define the pie shape.
   int x = 0;
   int y = 0;
   int width = 200;
   int height = 100;
   REAL startAngle = 0.0f;
   REAL sweepAngle = 45.0f;

   // Fill the pie.
   graphics.FillPie(&blackBrush, x, y, width, height, startAngle, sweepAngle);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Status


Graphics::FillPie(Brush* brush, REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)

The FillPie method uses a brush to fill the interior of a pie.

Status FillPie(
  const Brush* brush,
  REAL x,
  REAL y,
  REAL width,
  REAL height,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the pie.
x
[in] Real number that specifies the x-coordinate of the upper-left corner of the rectangle that bounds the ellipse. A curved portion of the ellipse is the arc of the pie.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the rectangle that bounds the ellipse.
width
[in] Real number that specifies the width of the rectangle that bounds the ellipse.
height
[in] Real number that specifies the height of the rectangle that bounds the ellipse.
startAngle
[in] Real number that specifies the angle, in degrees, between the x-axis and the starting point of the pie's arc.
sweepAngle
[in] Real number that specifies the angle, in degrees, between the starting and ending points of the pie's arc.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A pie is a portion of the interior of an ellipse (it is bounded by an elliptical curve and two radial lines). The startAngle and sweepAngle specify the portion of the ellipse to be used.

Example Code [C++]

The following example defines a pie and then fills it.

VOID Example_FillPie4(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Define the pie shape.
   REAL x = 0.0f;
   REAL y = 2.0f;
   REAL width = 200.8f;
   REAL height = 100.1f;
   REAL startAngle = 0.0f;
   REAL sweepAngle = 45.7f;

   // Fill the pie.
   graphics.FillPie(&blackBrush, x, y, width, height, startAngle, sweepAngle);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Status


Graphics::FillPolygon Methods

This topic lists the FillPolygon methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • FillPolygon(Brush* brush, Point* points, INT count)
  • FillPolygon(Brush* brush, PointF* points, INT count)
  • FillPolygon(Brush* brush, Point* points, INT count, FillMode fillMode)
  • FillPolygon(Brush* brush, PointF* points, INT count, FillMode fillMode)


Graphics::FillPolygon(Brush* brush, Point* points, INT count)

The FillPolygon method uses a brush to fill the interior of a polygon.

Status FillPolygon(
  const Brush* brush,
  const Point* points,
  INT count
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the polygon.
points
[in] Pointer to an array of points that make up the vertices of the polygon. The first two points in the array specify the first side of the polygon. Each additional point specifies a new side, the vertices of which include the point and the previous point. If the last point and the first point do not coincide, they specify the last side of the polygon.
count
[in] Integer that specifies the number of points in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example defines a polygon and then fills it.

VOID Example_FillPolygon(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Create an array of Point objects that define the polygon.
   Point point1(100, 100);
   Point point2(200, 130);
   Point point3(150, 200);
   Point point4(50, 200);
   Point point5(0, 130);
   Point points[5] = {point1, point2, point3, point4, point5};

   // Fill the polygon.
   graphics.FillPolygon(&blackBrush, points, 5);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Status


Graphics::FillPolygon(Brush* brush, PointF* points, INT count)

The FillPolygon method uses a brush to fill the interior of a polygon.

Status FillPolygon(
  const Brush* brush,
  const PointF* points,
  INT count
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the polygon.
points
[in] Pointer to an array of points that make up the vertices of the polygon. The first two points in the array specify the first side of the polygon. Each additional point specifies a new side, the vertices of which include the point and the previous point. If the last point and the first point do not coincide, they specify the last side of the polygon.
count
[in] Integer that specifies the number of points in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example defines a polygon and then fills it.

VOID Example_FillPolygon3(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Create an array of PointF objects that define the polygon.
   PointF point1(100.0f, 100.0f);
   PointF point2(200.0f, 130.0f);
   PointF point3(150.0f, 200.0f);
   PointF point4(50.0f, 200.0f);
   PointF point5(0.0f, 130.0f);
   PointF points[5] = {point1, point2, point3, point4, point5};

   // Fill the polygon.
   graphics.FillPolygon(&blackBrush, points, 5);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Status


Graphics::FillPolygon(Brush* brush, Point* points, INT count, FillMode fillMode)

The FillPolygon method uses a brush to fill the interior of a polygon.

Status FillPolygon(
  const Brush* brush,
  const Point* points,
  INT count,
  FillMode fillMode
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the polygon.
points
[in] Pointer to an array of points that make up the vertices of the polygon. The first two points in the array specify the first side of the polygon. Each additional point specifies a new side, the vertices of which include the point and the previous point. If the last point and the first point do not coincide, they specify the last side of the polygon.
count
[in] Integer that specifies the number of points in the points array.
fillMode
[in] Element of the FillMode enumeration that specifies how to fill a closed area that is within another closed area and that is created when the curve or path passes over itself.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example defines a polygon and fills it.

VOID Example_FillPolygon2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Create an array of Point objects that define the polygon.
   Point point1(100, 100);
   Point point2(200, 130);
   Point point3(150, 200);
   Point point4(50, 200);
   Point point5(0, 130);
   Point points[5] = {point1, point2, point3, point4, point5};

   // Fill the polygon.
   graphics.FillPolygon(&blackBrush, points, 5, FillModeAlternate);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Point, Status


Graphics::FillPolygon(Brush* brush, PointF* points, INT count, FillMode fillMode)

The FillPolygon method uses a brush to fill the interior of a polygon.

Status FillPolygon(
  const Brush* brush,
  const PointF* points,
  INT count,
  FillMode fillMode
);

Parameters

brush
[in] Pointer to a Brush object that is used to paint the interior of the polygon.
points
[in] Pointer to an array of points that make up the vertices of the polygon. The first two points in the array specify the first side of the polygon. Each additional point specifies a new side, the vertices of which include the point and the previous point. If the last point and the first point do not coincide, they specify the last side of the polygon.
count
[in] Integer that specifies the number of points in the points array.
fillMode
[in] Element of the FillMode enumeration that specifies how to fill a closed area that is within another closed area and that is created when the curve or path passes over itself.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example defines a polygon and fills it.

VOID Example_FillPolygon4(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Create an array of PointF objects that define the polygon.
   PointF point1(100.0f, 100.0f);
   PointF point2(200.0f, 130.0f);
   PointF point3(150.0f, 200.0);
   PointF point4(50.0f, 200.0f);
   PointF point5(0.0f, 130.0f);
   PointF points[5] = {point1, point2, point3, point4, point5};

   // Fill the polygon.
   graphics.FillPolygon(&blackBrush, points, 5, FillModeAlternate);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Point, Status


Graphics::FillRectangle Methods

This topic lists the FillRectangle methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • FillRectangle(Brush* brush, Rect& rect)
  • FillRectangle(Brush* brush, RectF& rect)
  • FillRectangle(Brush* brush, INT x, INT y, INT width, INT height)
  • FillRectangle(Brush* brush, REAL x, REAL y, REAL width, REAL height)


Graphics::FillRectangle(Brush* brush, Rect& rect)

The FillRectangle method uses a brush to fill the interior of a rectangle.

Status FillRectangle(
  const Brush* brush,
  const Rect& rect
);

Parameters

brush
[in] Pointer to a brush that is used to paint the interior of the rectangle.
rect
[in] Reference to the rectangle to be filled.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example fills a rectangle.

VOID Example_FillRectangle(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Create a Rect object.
   Rect fillRect(0, 0, 100, 100);

   // Fill the rectangle.
   graphics.FillRectangle(&blackBrush, fillRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Rect, Status


Graphics::FillRectangle(Brush* brush, RectF& rect)

The FillRectangle method uses a brush to fill the interior of a rectangle.

Status FillRectangle(
  const Brush* brush,
  const RectF& rect
);

Parameters

brush
[in] Pointer to a brush that is used to paint the interior of the rectangle.
rect
[in] Reference to the rectangle to be filled.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example fills a rectangle.

VOID Example_FillRectangle2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Create a RectF object.
   RectF fillRect(1.0f, 2.5f, 100.3f, 100.9f);

   // Fill the rectangle.
   graphics.FillRectangle(&blackBrush, fillRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Rect, Status


Graphics::FillRectangle(Brush* brush, INT x, INT y, INT width, INT height)

The FillRectangle method uses a brush to fill the interior of a rectangle.

Status FillRectangle(
  const Brush* brush,
  INT x,
  INT y,
  INT width,
  INT height
);

Parameters

brush
[in] Pointer to a brush that is used to paint the interior of the rectangle.
x
[in] Integer that specifies the x-coordinate of the upper-left corner of the rectangle to be filled.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the rectangle to be filled.
width
[in] Integer that specifies the width of the rectangle to be filled.
height
[in] Integer that specifies the height of the rectangle to be filled.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example defines a rectangle and then fills it.

VOID Example_FillRectangle3(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Define the rectangle.
   int x = 0;
   int y = 0;
   int width = 100;
   int height = 100;

   // Fill the rectangle.
   graphics.FillRectangle(&blackBrush, x, y, width, height);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Rect, Status


Graphics::FillRectangle(Brush* brush, REAL x, REAL y, REAL width, REAL height)

The FillRectangle method uses a brush to fill the interior of a rectangle.

Status FillRectangle(
  const Brush* brush,
  REAL x,
  REAL y,
  REAL width,
  REAL height
);

Parameters

brush
[in] Pointer to a brush that is used to paint the interior of the rectangle.
x
[in] Real number that specifies the x-coordinate of the upper-left corner of the rectangle to be filled.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the rectangle to be filled.
width
[in] Real number that specifies the width of the rectangle to be filled.
height
[in] Real number that specifies the height of the rectangle to be filled.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example defines a rectangle and then fills it.

VOID Example_FillRectangle4(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Define the rectangle.
   REAL x = 0.5f;
   REAL y = 0.5f;
   REAL width = 100.8f;
   REAL height = 100.8f;

   // Fill the rectangle.
   graphics.FillRectangle(&blackBrush, x, y, width, height);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Rect, Status


Graphics::FillRectangles Methods

This topic lists the FillRectangles methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • FillRectangles(Brush* brush, Rect* rects, INT count)
  • FillRectangles(Brush* brush, RectF* rects, INT count)


Graphics::FillRectangles(Brush* brush, Rect* rects, INT count)

The FillRectangles method uses a brush to fill the interior of a sequence of rectangles.

Status FillRectangles(
  const Brush* brush,
  const Rect* rects,
  INT count
);

Parameters

brush
[in] Pointer to a brush that is used to fill the interior of each rectangle.
rects
[in] Pointer to an array of rectangles to be filled.
count
[in] Integer that specifies the number of rectangles in the rects array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example fills a sequence of rectangles.

VOID Example_FillRectangles(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Create an array of Rect objects.
   Rect rect1(0, 0, 100, 200);
   Rect rect2(100, 200, 200, 50);
   Rect rect3(300, 0, 50, 150);
   Rect rects[3] = {rect1, rect2, rect3};

   // Fill the rectangles.
   graphics.FillRectangles(&blackBrush, rects, 3);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Rect, Status


Graphics::FillRectangles(Brush* brush, RectF* rects, INT count)

The FillRectangles method uses a brush to fill the interior of a sequence of rectangles.

Status FillRectangles(
  const Brush* brush,
  const RectF* rects,
  INT count
);

Parameters

brush
[in] Pointer to a brush that is used to fill the interior of each rectangle.
rects
[in] Pointer to an array of rectangles to be filled.
count
[in] Integer that specifies the number of rectangles in the rects array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example fills a sequence of rectangles.

VOID Example_FillRectangles2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Create an array of RectF objects.
   RectF rect1(0.0f, 0.0f, 100.0f, 200.0f);
   RectF rect2(100.5f, 200.5f, 200.5f, 50.5f);
   RectF rect3(300.8f, 0.8f, 50.8f, 150.8f);
   RectF rects[3] = {rect1, rect2, rect3};

   // Fill the rectangles.
   graphics.FillRectangles(&blackBrush, rects, 3);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Rect, Status


Graphics::FillRegion(brush, region)

The FillRegion method uses a brush to fill a specified region.

Status FillRegion(
  const Brush* brush,
  const Region* region
);

Parameters

brush
[in] Pointer to a brush that is used to paint the region.
region
[in] Pointer to a region to be filled.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Because a region describes a set of pixels, a pixel is considered either fully inside, or fully outside the region. Consequently, FillRegion does not antialias the edges of the region.

Example Code [C++]

The following example creates a region from a rectangle and then fills the region.

VOID Example_FillRegion(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object.
   SolidBrush blackBrush(Color(255, 0, 0, 0));

   // Create a Region object from a rectangle.
   Region ellipseRegion(Rect(0, 0, 200, 100));

   // Fill the region.
   graphics.FillRegion(&blackBrush, &ellipseRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Pen, Region, Status
Concepts
Regions


Graphics::Flush(intention)

The Flush method flushes all pending graphics operations.

VOID Flush(
  FlushIntention intention
);

Parameters

intention
[in] Element of the FlushIntention enumeration that specifies whether pending operations are flushed immediately (not executed) or executed as soon as possible.

Return Values

This method does not return a value.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
FlushIntention


Graphics::FromHDC Methods

This topic lists the FromHDC methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • FromHDC(hdc)
  • FromHDC(hdc, hdevice)


Graphics::FromHDC(hdc)

The FromHDC method creates a Graphics object that is associated with a specified device context.

static Graphics* FromHDC(
  HDC hdc
);

Parameters

hdc
[in] Handle to the device context that will be associated with the new Graphics object.

Return Values

This method returns a pointer to the new Graphics object.

Remarks

When you use this method to create a Graphics object, make sure that the Graphics object is deleted before the device context is released.

Example Code [C++]

The following example calls FromHDC to create a Graphics object and then uses that Graphics object to draw a rectangle.

VOID Example_FromHDC(HDC hdc)
{
   Graphics* pGraphics = Graphics::FromHDC(hdc);
   Pen pen(Color(255, 255, 0, 0));
   pGraphics->DrawRectangle(&pen, 10, 10, 200, 100);
   delete pGraphics;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetHDC, Graphics Constructors, FromHDC Methods, FromHWND, FromImage
Concepts
Changes in the Programming Model


Graphics::FromHDC(hdc, hdevice)

The FromHDC method creates a Graphics object that is associated with a specified device context and a specified device.

static Graphics* FromHDC(
  HDC hdc,
  HANDLE hDevice
);

Parameters

hdc
[in] Handle to the device context that is associated with the new Graphics object.
hDevice
[in] Handle to a device that is associated with the new Graphics object.

Return Values

This method returns a pointer to the new Graphics object.

Remarks

When you use this method to create a Graphics object, make sure that the Graphics object is deleted before the device context is released.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetHDC, Graphics Constructors, FromHDC Methods, FromHWND, FromImage
Tasks and Examples
Optimizing Printing by Providing a Printer Handle
Concepts
Changes in the Programming Model


Graphics::FromHWND(hwnd, icm)

The FromHWND method creates a Graphics object that is associated with a specified window.

static Graphics* FromHWND(
  HWND hWnd,
  BOOL icm
);

Parameters

hWnd
[in] Handle to the window that will be associated with the new Graphics object.
icm
[in] Optional. Boolean value that specifies whether the new Graphics object applies color adjustment according to the International Color Consortium (ICC) profile associated with the display device. TRUE specifies that color adjustment is applied, and FALSE specifies that color adjustment is not applied. The default value is FALSE.

Return Values

This method returns a pointer to the new Graphics object.

Example Code [C++]

The following function calls FromHWND to create a Graphics object that is associated with a window. The call to the DrawLine method of that Graphics object draws a line in the window.

VOID Example_FromHWND(HWND hWnd)
{
   Graphics* graphics = Graphics::FromHWND(hWnd);
   Pen pen(Color(255, 0, 0, 255));
   graphics->DrawLine(&pen, 0, 0, 200, 100);
   delete graphics;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetHDC, FromHDC Methods, FromImage, Graphics Constructors
Concepts
Changes in the Programming Model


Graphics::FromImage(image)

The FromImage method creates a Graphics object that is associated with a specified Image object.

static Graphics* FromImage(
  Image* image
);

Parameters

image
[in] Pointer to an Image object that will be associated with the new Graphics object.

Return Values

This method returns a pointer to the new Graphics object.

Remarks

This method fails if the Image object is based on a metafile that was opened for reading. The Image::Image(file) and Metafile::Metafile(file) constructors open a metafile for reading. To open a metafile for recording, use a Metafile constructor that receives a device context handle.

This method also fails if the image has one of the following pixel formats:

  • PixelFormatUndefined
  • PixelFormatDontCare
  • PixelFormat1bppIndexed
  • PixelFormat4bppIndexed
  • PixelFormat8bppIndexed
  • PixelFormat16bppGrayScale
  • PixelFormat16bppARGB1555

Example Code [C++]

The following example calls the FromImage method to create a Graphics object that is associated with an Image object. The call to FillRectangle does not paint on the display device; instead, it alters the bitmap of the Image object. The call to DrawImage displays the altered bitmap.

VOID Example_FromImage(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object from a PNG file.
   Image image(L"Mosaic.png");

   // Create a Graphics object that is associated with the image.
   Graphics* imageGraphics = Graphics::FromImage(&image);

   // Alter the image.
   SolidBrush brush(Color(255, 0, 0, 255));
   imageGraphics->FillEllipse(&brush, 10, 40, 100, 50);

   // Draw the altered image.
   graphics.DrawImage(&image, 30, 20);

   delete imageGraphics;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetHDC, FromHDC Methods, FromHWND, FromImage, Graphics Constructors
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Changes in the Programming Model


Graphics::GetClip(region)

The GetClip method gets the clipping region of this Graphics object.

Status GetClip(
  Region* region
) const;

Parameters

region
[out] Pointer to a Region object that receives the clipping region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example sets a clipping region. Next, the code gets the clipping region, stores it in a Region object, and then uses the stored object to fill the region.

VOID Example_GetClip(HDC hdc)
{
   Graphics myGraphics(hdc);

   // Set a clipping region.
   myGraphics.SetClip(Rect(0, 0, 200, 100));

   // Get the clipping region.
   Region clipRegion;
   myGraphics.GetClip(&clipRegion);

   // Fill the clipping region of the myGraphics object.
   myGraphics.FillRegion(&SolidBrush(Color(255, 0, 0, 0)), &clipRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetClipBounds, ResetClip, SetClip, Region
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::GetClipBounds Methods

This topic lists the GetClipBounds methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • GetClipBounds(Rect* rect)
  • GetClipBounds(RectF* rect)


Graphics::GetClipBounds(Rect* rect)

The GetClipBounds method gets a rectangle that encloses the clipping region of this Graphics object.

Status GetClipBounds(
  Rect* rect
) const;

Parameters

rect
[out] Pointer to a Rect object that receives the rectangle that encloses the clipping region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The world transformation is applied to the clipping region and then the enclosing rectangle is calculated.

If you do not explicitly set the clipping region of a Graphics object, its clipping region is infinite. When the clipping region is infinite, GetClipBounds returns a large rectangle. The X and Y data members of that rectangle are large negative numbers, and the Width and Height data members are large positive numbers.

Example Code [C++]

The following example sets a clipping region, gets the rectangle that encloses the clipping region, and then fills the rectangle.

VOID Example_GetClipBounds(HDC hdc)
{
   Graphics graphics(hdc);

   Region   myRegion(Rect(25, 25, 100, 50));
   Rect     rect(40, 60, 100, 50);
   Region   gRegion;
   Rect     enclosingRect;

   SolidBrush  blueBrush(Color(100, 0, 0, 255));
   Pen         greenPen(Color(255, 0, 255, 0), 1.5f);

   // Modify the region by using a rectangle.
   myRegion.Union(rect);

   // Set the clipping region of the graphics object.
   graphics.SetClip(&myRegion);

   // Now, get the clipping region, and fill it.
   graphics.GetClip(&gRegion);
   graphics.FillRegion(&blueBrush, &gRegion);

   // Get a rectangle that encloses the clipping region, and draw the enclosing
   // rectangle.
   graphics.GetClipBounds(&enclosingRect);
   graphics.ResetClip();
   graphics.DrawRectangle(&greenPen, enclosingRect);}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetClip, SetClip, Rect, Status, GetVisibleClipBounds
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::GetClipBounds(RectF* rect)

The GetClipBounds method gets a rectangle that encloses the clipping region of this Graphics object.

Status GetClipBounds(
  RectF* rect
) const;

Parameters

rect
[out] Pointer to a RectF object that receives the rectangle that encloses the clipping region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The world transformation is applied to the clipping region and then the enclosing rectangle is calculated.

If you do not explicitly set the clipping region of a Graphics object, its clipping region is infinite. When the clipping region is infinite, GetClipBounds returns a large rectangle. The X and Y data members of that rectangle are large negative numbers, and the Width and Height data members are large positive numbers.

Example Code [C++]

The following example sets a clipping region, gets the rectangle that encloses the clipping region, and then fills the rectangle.

VOID Example_GetClipBounds2(HDC hdc)
{
   Graphics graphics(hdc);

   Region   myRegion(RectF(25.0f, 25.0f, 100.0f, 50.0f));
   RectF    rect(40.0f, 60.0f, 100.0f, 50.0f);
   Region   gRegion;
   RectF    enclosingRect;

   SolidBrush  blueBrush(Color(100, 0, 0, 255));
   Pen         greenPen(Color(255, 0, 255, 0), 1.5f);

   // Modify the region by using a rectangle.
   myRegion.Union(rect);

   // Set the clipping region of the graphics object.
   graphics.SetClip(&myRegion);

   // Now, get the clipping region, and fill it
   graphics.GetClip(&gRegion);
   graphics.FillRegion(&blueBrush, &gRegion);

   // Get a rectangle that encloses the clipping region, and draw the enclosing
   // rectangle.
   graphics.GetClipBounds(&enclosingRect);
   graphics.ResetClip();
   graphics.DrawRectangle(&greenPen, enclosingRect);}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetClip, SetClip, RectF, Status, GetVisibleClipBounds
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::GetCompositingMode()

The GetCompositingMode method gets the compositing mode currently set for this Graphics object.

CompositingMode GetCompositingMode(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the CompositingMode enumeration that indicates the compositing mode currently set for this Graphics object.

Remarks

Suppose you create a SolidBrush object based on a color that has an alpha component of 192, which is about 75 percent of 255. If your Graphics object has its compositing mode set to CompositingModeSourceOver, then areas filled with the solid brush are a blend that is 75 percent brush color and 25 percent background color. If your Graphics object has its compositing mode set to CompositingModeSourceCopy, then the background color is not blended with the brush color. However, the color rendered by the brush has an intensity that is 75 percent of what it would be if the alpha component were 255.

Example Code [C++]

The following example creates a Graphics object and sets its compositing mode to CompositingModeSourceCopy. The code creates a SolidBrush object based on a color with an alpha component of 128. The code passes the address of that brush to the FillRectangle method of the Graphics object to fill a rectangle with a color that is not blended with the background color. The call to the GetCompositingMode method of the Graphics object demonstrates how to obtain the compositing mode (which is already known in this case). The code determines whether the compositing mode is CompositingModeSourceCopy and if so, changes it to CompositingModeSourceOver. Then the code calls FillRectangle a second time to fill a rectangle with a color that is a half-and-half blend of the brush color and the background color.

VOID Example_GetCompositingMode(HDC hdc)
{
   Graphics graphics(hdc);

   graphics.SetCompositingMode(CompositingModeSourceCopy);
   SolidBrush alphaBrush(Color(128, 255, 0, 0));
   graphics.FillRectangle(&alphaBrush, 0, 0, 100, 100);

   // Get the compositing mode.
   CompositingMode compMode = graphics.GetCompositingMode();

   // Change the compositing mode if it is CompositingModeSourceCopy.
   if(compMode == CompositingModeSourceCopy)
   {
      graphics.SetCompositingMode(CompositingModeSourceOver);
   }

   graphics.FillRectangle(&alphaBrush, 0, 100, 100, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetCompositingQuality, HatchBrush, SetCompositingMode, SetCompositingQuality, SolidBrush
Tasks and Examples
Alpha Blending Lines and Fills, Using Compositing Mode to Control Alpha Blending
Concepts
New Features


Graphics::GetCompositingQuality()

The GetCompositingQuality method gets the compositing quality currently set for this Graphics object.

CompositingQuality GetCompositingQuality(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the CompositingQuality enumeration that indicates the compositing quality currently set for this Graphics object.

Example Code [C++]

The following example creates a Graphics object and sets its compositing quality to CompositingQualityHighQuality. The code creates a SolidBrush object based on a color with an alpha component of 128. The code passes the address of that brush to the FillRectangle method of the Graphics object. The call to the GetCompositingQuality method of the Graphics object demonstrates how to obtain the compositing quality (which is already known in this case). The code determines whether the compositing quality is CompositingQualityHighQuality and if so, changes it to CompositingQualityHighSpeed. Then the code calls the FillRectangle method a second time. The second rectangle is filled with the same brush that was used to fill the first rectangle, but the result is different because of the compositing quality setting.

VOID Example_GetCompositingQuality(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the compositing quality.
   graphics.SetCompositingQuality(CompositingQualityHighQuality);

   SolidBrush alphaBrush(Color(128, 255, 0, 0));
   graphics.FillRectangle(&alphaBrush, 0, 0, 100, 100);

   // Get the compositing quality.
   CompositingQuality compQuality = graphics.GetCompositingQuality();

   // Change the compositing mode if it is CompositingModeSourceCopy.
   if (compQuality == CompositingQualityHighQuality)
   {
      graphics.SetCompositingQuality(CompositingQualityHighSpeed);
   }

   graphics.FillRectangle(&alphaBrush, 0, 100, 100, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetCompositingQuality, HatchBrush, SetCompositingMode, SetCompositingQuality, SolidBrush
Tasks and Examples
Alpha Blending Lines and Fills
Concepts
New Features


Graphics::GetDpiX()

The GetDpiX method gets the horizontal resolution, in dots per inch, of the display device associated with this Graphics object.

REAL GetDpiX(void);

Parameters

This method has no parameters.

Return Values

This method returns the horizontal resolution, in dots per inch, of the display device associated with this Graphics object.

Example Code [C++]

The following example gets the horizontal resolution, in dots per inch, of the display device and uses that value to convert pixels to inches. Then the code draws two rectangles that have the same width: one measured in inches and one measured in pixels. t

VOID Example_GetDpiX(HDC hdc)
{
   Graphics graphics(hdc);

   // Get the horizontal resolution, in dots per inch, of the display device.
   REAL dpiX = graphics.GetDpiX();

   // Set the unit of measure for graphics to inches.
   graphics.SetPageUnit(UnitInch);

   // Use dipX to convert pixels to inches, and draw a
   // rectangle that has a width of 100 pixels.
   REAL side = 100.0f/dpiX;
   Pen bluePen(Color(255, 0, 0, 255), 0.0f);
   graphics.DrawRectangle(&bluePen, 0.0f, 0.0f, side, side);

   // Set the unit of measure for graphics to pixels.
   graphics.SetPageUnit(UnitPixel);

   // Draw a 100-pixel square.
   Pen redPen(Color(255, 255, 0, 0), 0.0f);
   graphics.DrawRectangle(&redPen, 120, 0, 100, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetDpiY, GetPageUnit, SetPageUnit
Concepts
Global and Local Transformations, Types of Coordinate Systems


Graphics::GetDpiY()

The GetDpiY method gets the vertical resolution, in dots per inch, of the display device associated with this Graphics object.

REAL GetDpiY(void);

Parameters

This method has no parameters.

Return Values

This method returns the vertical resolution, in dots per inch, of the display device associated with this Graphics object.

Example Code [C++]

The following example gets the vertical resolution, in dots per inch, of the display device and uses that value to convert pixels to inches. Then the code draws two rectangles that have the same height: one measured in inches and one measured in pixels.

VOID Example_GetDpiY(HDC hdc)
{
   Graphics graphics(hdc);

   // Get the vertical resolution, in dots per inch, of the display device.
   REAL dpiY = graphics.GetDpiY();

   // Set the unit of measure for graphics to inches.
   graphics.SetPageUnit(UnitInch);

   // Use dipY to convert pixels to inches, and draw a
   // rectangle that has a height of 100 pixels.
   REAL side = 100.0f/dpiY;
   Pen bluePen(Color(255, 0, 0, 255), 0.0f);
   graphics.DrawRectangle(&bluePen, 0.0f, 0.0f, side, side);

   // Set the unit of measure for graphics to pixels.
   graphics.SetPageUnit(UnitPixel);

   // Draw a 100-pixel square.
   Pen redPen(Color(255, 255, 0, 0), 0.0f);
   graphics.DrawRectangle(&redPen, 120, 0, 100, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetDpiY, GetPageUnit, SetPageUnit
Concepts
Global and Local Transformations, Types of Coordinate Systems


Graphics::GetHalftonePalette()

The GetHalftonePalette method gets a Windows halftone palette.

static HPALETTE GetHalftonePalette(void);

Parameters

This method has no parameters.

Return Values

This method returns a handle to a Windows halftone palette.

Remarks

The purpose of the GetHalftonePalette method is to enable GDI+ to produce a better quality halftone when the display uses 8 bits per pixel. To display an image using the halftone palette, use the following procedure:

  1. Call GetHalftonePalette to get a GDI+ halftone palette.
  2. Select the halftone palette into a device context.
  3. Realize the palette by calling the RealizePalette function.
  4. Construct a Graphics object from a handle to the device context.
  5. Call the DrawImage method of the Graphics object.

Be sure to delete the palette when you have finished using it. If you do not follow the preceding procedure, then on an 8-bits-per-pixel-display device, the default, 16-color process is used, which results in a lesser quality halftone.

Example Code [C++]

The following example draws the same image twice. Before the image is drawn the second time, the code gets a halftone palette, selects the palette into a device context, and realizes the palette.

VOID Example_GetHalftonePalette(HDC hdc)
{
   Image image(L"Mosaic.png");

   Graphics* graphics1 = new Graphics(hdc);
   graphics1->DrawImage(&image, 10, 10);
   delete graphics1;

   HPALETTE hPalette = Graphics::GetHalftonePalette();
   SelectPalette(hdc, hPalette, FALSE);
   RealizePalette(hdc);
   Graphics* graphics2 = new Graphics(hdc);
   graphics2->DrawImage(&image, 300, 10);
   delete graphics2;
   DeleteObject(hPalette);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetPalette, RealizePalette, SetPalette


Graphics::GetHDC()

The GetHDC method gets a handle to the device context associated with this Graphics object.

HDC GetHdc(void);

Parameters

This method has no parameters.

Return Values

This method returns a handle to the device context associated with this Graphics object.

Remarks

Each call to the GetHDC method of a Graphics object should be paired with a call to the ReleaseHDC method of that same Graphics object. Do not call any methods of the Graphics object between the calls to GetHDC and ReleaseHDC. If you attempt to call a method of the Graphics object between GetHDC and ReleaseHDC, the method will fail and will return ObjectBusy.

Any state changes you make to the device context between GetHDC and ReleaseHDC will be ignored by GDI+ and will not be reflected in rendering done by GDI+.

Example Code [C++]

The following function uses GDI+ to draw an ellipse, then uses GDI to draw a rectangle, and finally uses GDI+ to draw a line. The function's one parameter is a pointer to a GDI+ Graphics object. The code calls the DrawEllipse method of that Graphics object to draw an ellipse. Next, the code calls the GetHDC method to obtain a handle to the device context associated with the Graphics object. The code draws a rectangle by passing the device context handle to the GDI Rectangle function. The code calls the ReleaseHDC method of the Graphics object and then uses the Graphics object to draw a line.

VOID Example_GetReleaseHDC(Graphics* g)
{
   Pen pen(Color(255, 0, 0, 255));
   g->DrawEllipse(&pen, 10, 10, 100, 50);  // GDI+

   HDC hdc = g->GetHDC();

      // Make GDI calls, but don't call any methods
      // on g until after the call to ReleaseHDC.
      Rectangle(hdc, 120, 10, 220, 60);  // GDI

   g->ReleaseHDC(hdc);

   // Ok to call methods on g again.
   g->DrawLine(&pen, 240, 10, 340, 60);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
FromHDC Methods, Graphics Constructors, ReleaseHDC
Concepts
Changes in the Programming Model


Graphics::GetInterpolationMode()

The GetInterpolationMode method gets the interpolation mode currently set for this Graphics object. The interpolation mode determines the algorithm that is used when images are scaled or rotated.

InterpolationMode GetInterpolationMode(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the InterpolationMode enumeration that indicates the interpolation mode currently set for this Graphics object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
InterpolationMode, SetInterpolationMode
Tasks and Examples
Using Interpolation Mode to Control Image Quality During Scaling


Graphics::GetLastStatus()

The GetLastStatus method returns a value that indicates the nature of this Graphics object's most recent method failure.

Status GetLastStatus(void);

Parameters

This method has no parameters.

Return Values

The GetLastStatus method returns an element of the Status enumeration.

If no methods invoked on this Graphics object have failed since the previous call to GetLastStatus, then GetLastStatus returns Ok.

If at least one method invoked on this Graphics object has failed since the previous call to GetLastStatus, then GetLastStatus returns a value that indicates the nature of the most recent failure.

Remarks

You can call GetLastStatus immediately after constructing a Graphics object to determine whether the constructor succeeded.

The first time you call the GetLastStatus method of a Graphics object, it returns Ok if the constructor succeeded and all methods invoked so far on the Graphics object succeeded. Otherwise, it returns a value that indicates the nature of the most recent failure.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Status


Graphics::GetNearestColor(color)

The GetNearestColor method gets the nearest color to the color that is passed in. This method works on 8-bits per pixel or lower display devices for which there is an 8-bit color palette.

Status GetNearestColor(
  Color* color
) const;

Parameters

color
[in, out] Pointer to a Color object that, on input, specifies the color to be tested and, on output, receives the nearest color found in the color palette.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Color object and fills a rectangle with that color. It then gets the nearest 8-bit color and fills a second rectangle with that color.

VOID Example_GetNearestColor(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Color object, and fill a rectangle with that color.
   Color color(0xFFA53F88);
   graphics.FillRectangle(&SolidBrush(color), 0, 0, 100, 100);

   // Get the nearest 8-bit color, and fill a second rectangle with that color.
   graphics.GetNearestColor(&color);
   graphics.FillRectangle(&SolidBrush(color), 100, 0, 100, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Color, Status


Graphics::GetPageScale()

The GetPageScale method gets the scaling factor currently set for the page transformation of this Graphics object. The page transformation converts page coordinates to device coordinates.

REAL GetPageScale(void);

Parameters

This method has no parameters.

Return Values

This method returns the scaling factor currently set for the page transformation of this Graphics object.

Example Code [C++]

The following example sets the world and page transformations of a Graphics object. The page scale and page unit both belong to the page transformation. The code demonstrates how to obtain the page scale (which is already known in this case). The code determines whether the page scale is greater than 1 and, if so, sets the page unit to UnitMillimeter. The call to DrawRectangle draws a rectangle that has a width of 3 centimeters (UnitMillimeter along with a scaling factor of 10) and a height of 2 centimeters.

VOID Example_GetPageScale(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0), 0.0f);

   // Set the world transformation of the Graphics object.
   graphics.TranslateTransform(4.0f, 1.0f);

   // Set the page transformation of the Graphics object.
   graphics.SetPageUnit(UnitInch);
   graphics.SetPageScale(10.0f);

   REAL pageScale = graphics.GetPageScale();

   if(pageScale > 1.0f)
      graphics.SetPageUnit(UnitMillimeter);

   graphics.DrawRectangle(&pen, 0, 0, 3, 2);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetDpiX, GetDpiY, GetPageUnit, SetPageScale, SetPageUnit, Unit
Concepts
Types of Coordinate Systems


Graphics::GetPageUnit()

The GetPageUnit method gets the unit of measure currently set for this Graphics object.

Unit GetPageUnit(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the Unit enumeration that indicates the unit of measure currently set for this Graphics object.

Example Code [C++]

The following example creates a Graphics object and sets its unit of measure to UnitPixel. Then the code draws a square that is 100 pixels on each side. The call to GetPageUnit demonstrates how to obtain the unit of measure (which is already known in this case) for the Graphics object. The code determines whether the unit of measure is UnitPixel and if so, changes the unit of measure to UnitInch. Then the code draws a square that is 1 inch on each side.

VOID Example_GetPageUnit(HDC hdc)
{
   Graphics graphics(hdc);
   Pen blackPen(Color(255, 0, 0, 0), 0.0f);
   Pen redPen(Color(255, 255, 0, 0), 0.0f);

   graphics.SetPageUnit(UnitPixel);
   graphics.DrawRectangle(&blackPen, 0, 0, 100, 100);

   // Get the page unit.
   Unit pageUnit = graphics.GetPageUnit();

   // If unit is UnitPixel, set the page unit to UnitInch.
   if (pageUnit == UnitPixel)
   {
      graphics.SetPageUnit(UnitInch);
   }

   graphics.DrawRectangle(&redPen, 2, 0, 1, 1);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetDpiX, GetDpiY, GetPageScale, SetPageScale, SetPageUnit, Unit
Concepts
Types of Coordinate Systems


Graphics::GetPixelOffsetMode()

The GetPixelOffsetMode method gets the pixel offset mode currently set for this Graphics object.

PixelOffsetMode GetPixelOffsetMode(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the PixelOffsetMode enumeration that indicates the pixel offset mode currently set for this Graphics object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
PixelOffsetMode


Graphics::GetRenderingOrigin(x, y)

The GetRenderingOrigin method gets the rendering origin currently set for this Graphics object. The rendering origin is used to set the dither origin for 8-bits per pixel and 16-bits per pixel dithering and is also used to set the origin for hatch brushes.

Status GetRenderingOrigin(
  INT* x,
  INT* y
);

Parameters

x
[out] Pointer to an INT that receives the x-coordinate of the rendering origin.
y
[out] Pointer to an INT that receives the y-coordinate of the rendering origin.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
SetRenderingOrigin


Graphics::GetSmoothingMode()

The GetSmoothingMode method determines whether smoothing (antialiasing) is applied to the Graphics object.

SmoothingMode GetSmoothingMode(void) const;

Parameters

This method has no parameters.

Return Values

If smoothing (antialiasing) is applied to this Graphics object, this method returns SmoothingModeAntiAlias. If smoothing (antialiasing) is not applied to this Graphics object, this method returns SmoothingModeNone. SmoothingModeAntiAlias and SmoothingModeNone are elements of the SmoothingMode enumeration.

Remarks

To get the render quality level for text, use the GetTextRenderingHint method.

Example Code [C++]

The following example sets the smoothing mode to high speed and draws an ellipse. It then gets the smoothing mode, changes it to high quality, and draws a second ellipse to demonstrate the difference.

VOID Example_GetSmoothingMode(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the smoothing mode to SmoothingModeHighSpeed.
   graphics.SetSmoothingMode(SmoothingModeHighSpeed);

   // Draw an ellipse.
   graphics.DrawEllipse(&Pen(Color(255, 0, 0, 0), 3), Rect(10, 0, 200, 100));

   // Get the smoothing mode.
   SmoothingMode mode = graphics.GetSmoothingMode();

   // Test mode to see whether smoothing has been set for the Graphics object.
   if (mode == SmoothingModeAntiAlias)
   {
   graphics.SetSmoothingMode(SmoothingModeHighQuality);
   }

   // Draw an ellipse to demonstrate the difference.
   graphics.DrawEllipse(&Pen(Color::Red, 3), Rect(220, 0, 200, 100));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Image
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Antialiasing with Lines and Curves


Graphics::GetTextContrast()

The GetTextContrast method gets the contrast value currently set for this Graphics object. The contrast value is used for antialiasing text.

UINT GetTextContrast(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the contrast value.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::GetTextRenderingHint()

The GetTextRenderingHint method returns the text rendering mode currently set for this Graphics object.

TextRenderingHint GetTextRenderingHint(void) const;

Parameters

This method has no parameters.

Return Values

This method returns an element of the TextRenderingHint enumeration that indicates the process currently used by this Graphics object to render text.

Example Code [C++]

The following example sets the text-rendering hint to low quality and draws text. It then gets the text-rendering hint, changes it to high quality, and draws more text to demonstrate the difference.

VOID Example_GetTextRenderingHint(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the text rendering hint to TextRenderingHintSingleBitPerPixel.
   graphics.SetTextRenderingHint(TextRenderingHintSingleBitPerPixel);

   // Draw text.
   graphics.DrawString(
        L"Low quality rendering",
        21,
        &Font(L"Arial", 24),
        PointF(0, 0),
        &SolidBrush(Color(255, 0, 0, 0)));

   // Get the text-rendering hint.
   TextRenderingHint hint = graphics.GetTextRenderingHint();

   // Test hint, and set the text-rendering hint to TextRenderingHintAntiAlias.
   if (hint == TextRenderingHintSingleBitPerPixel)
   {
      graphics.SetTextRenderingHint(TextRenderingHintAntiAlias);
   }

   // Draw more text to demonstrate the difference.
   graphics.DrawString(
       L"High quality rendering",
       22,
       &Font(L"Arial", 24),
       PointF(0, 50),
       &SolidBrush(Color(255, 0, 0, 0)));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
TextRenderingHint


Graphics::GetTransform(matrix)

The GetTransform method gets the world transformation matrix of this Graphics object.

Status GetTransform(
  Matrix* matrix
);

Parameters

matrix
[out] Pointer to a Matrix object that receives the transformation matrix.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example calls the RotateTransform method of a Graphics object to set the world transformation matrix of that Graphics object. Then the code calls the GetTransform method of the Graphics object to obtain its world transformation matrix (which now represents a 30-degree rotation). The call to Matrix::GetElements copies the elements of the retrieved matrix to an array.

VOID Example_GetTransform(HDC hdc)
{
   Graphics graphics(hdc);

   graphics.RotateTransform(30.0f);

   Matrix matrix;
   REAL elements[6];
   graphics.GetTransform(&matrix);
   matrix.GetElements(elements);

   for(INT j = 0; j <= 5; ++j)
   {
      // Inspect or use the value in elements[j].
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Matrix, MatrixOrder, MultiplyTransform, ResetTransform, RotateTransform, ScaleTransform, SetTransform, TransformPoints, TranslateTransform
Tasks and Examples
Transformations
Concepts
Coordinate Systems and Transformations


Graphics::GetVisibleClipBounds Methods

This topic lists the GetVisibleClipBounds methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • GetVisibleClipBounds(Rect* rect)
  • GetVisibleClipBounds(RectF* rect)


Graphics::GetVisibleClipBounds(Rect* rect)

The GetVisibleClipBounds method gets a rectangle that encloses the visible clipping region of this Graphics object. The visible clipping region is the intersection of the clipping region of this Graphics object and the clipping region of the window.

Status GetVisibleClipBounds(
  Rect* rect
) const;

Parameters

rect
[out] Pointer to a Rect object that receives the rectangle that encloses the visible clipping region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example sets the clipping region for the Graphics object. It then gets a rectangle that encloses the visible clipping region and fills that rectangle.

VOID Example_GetVisibleClipBounds(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the clipping region.
   graphics.SetClip(Rect(100, 100, 200, 100));

   // Get a bounding rectangle for the clipping region.
   Rect boundRect;
   graphics.GetVisibleClipBounds(&boundRect);

   // Fill the bounding rectangle.
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), boundRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetClipBounds, IsVisibleClipEmpty, IsVisible Methods, Rect


Graphics::GetVisibleClipBounds(RectF* rect)

The GetVisibleClipBounds method gets a rectangle that encloses the visible clipping region of this Graphics object. The visible clipping region is the intersection of the clipping region of this Graphics object and the clipping region of the window.

Status GetVisibleClipBounds(
  RectF* rect
) const;

Parameters

rect
[out] Pointer to a RectF object that receives the rectangle that encloses the visible clipping region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example sets the clipping region for the Graphics object. It then gets a rectangle that encloses the visible clipping region and fills that rectangle.

VOID Example_GetVisibleClipBounds2(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the clipping region.
   graphics.SetClip(RectF(100.0f, 100.0f, 200.0f, 100.0f));

   // Get a bounding rectangle for the clipping region.
   RectF boundRect;
   graphics.GetVisibleClipBounds(&boundRect);

   // Fill the bounding rectangle.
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), boundRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetClipBounds, IsVisibleClipEmpty, IsVisible Methods, RectF


Graphics::IntersectClip Methods

This topic lists the IntersectClip methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • IntersectClip(Rect& rect)
  • IntersectClip(RectF& rect)
  • IntersectClip(region)


Graphics::IntersectClip(Rect& rect)

The IntersectClip method updates the clipping region of this Graphics object to the portion of the specified rectangle that intersects with the current clipping region of this Graphics object.

Status IntersectClip(
  const Rect& rect
);

Parameters

rect
[in] Reference to a rectangle that is used to update the clipping region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example sets a clipping region and updates the clipping region. It then draws rectangles to demonstrate the effective clipping region.

VOID Example_IntersectClip(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the clipping region.
   Rect clipRect(0, 0, 200, 200);
   graphics.SetClip(clipRect);

   // Update the clipping region to the portion of the rectangle that
   // intersects with the current clipping region.
   Rect intersectRect(100, 100, 200, 200);
   graphics.IntersectClip(intersectRect);

   // Fill a rectangle to demonstrate the effective clipping region.
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 255)), 0, 0, 500, 500);

   // Reset the clipping region to infinite.
   graphics.ResetClip();

   // Draw clipRect and intersectRect.
   graphics.DrawRectangle(&Pen(Color(255, 0, 0, 0)), clipRect);
   graphics.DrawRectangle(&Pen(Color(255, 255, 0, 0)), intersectRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetClip, GetClipBounds, Rect, SetClip, Status
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::IntersectClip(RectF& rect)

The IntersectClip method updates the clipping region of this Graphics object to the portion of the specified rectangle that intersects with the current clipping region of this Graphics object.

Status IntersectClip(
  const RectF& rect
);

Parameters

rect
[in] Reference to a rectangle that is used to update the clipping region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example sets a clipping region and updates the clipping region. It then draws rectangles to demonstrate the effective clipping region.

VOID Example_IntersectClip2(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the clipping region.
   RectF clipRect(0.5f, 0.5f, 200.5f, 200.5f);
   graphics.SetClip(clipRect);

   // Update the clipping region to the portion of the rectangle that
   // intersects with the current clipping region.
   RectF intersectRect(100.5f, 100.5f, 200.5f, 200.5f);
   graphics.IntersectClip(intersectRect);

   // Fill a rectangle to demonstrate the effective clipping region.
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 255)), 0, 0, 500, 500);

   // Reset the clipping region to infinite.
   graphics.ResetClip();

   // Draw clipRect and intersectRect.
   graphics.DrawRectangle(&Pen(Color(255, 0, 0, 0)), clipRect);
   graphics.DrawRectangle(&Pen(Color(255, 255, 0, 0)), intersectRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetClip, GetClipBounds, RectF, SetClip, Status
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::IntersectClip(region)

The IntersectClip method updates the clipping region of this Graphics object to the portion of the specified region that intersects with the current clipping region of this Graphics object.

Status IntersectClip(
  const Region* region
);

Parameters

region
[in] Pointer to a region that is used to update the clipping region of this Graphics object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example sets a clipping region and updates the clipping region. It then draws rectangles to demonstrate the effective clipping region.

VOID Example_IntersectClip3(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the clipping region.
   Region clipRegion(Rect(0, 0, 200, 200));
   graphics.SetClip(&clipRegion);

   // Update the clipping region to the portion of the specified region that
   // intersects with the current clipping region of the graphics object.
   Region intersectRegion(Rect(100, 100, 200, 200));
   graphics.IntersectClip(&intersectRegion);

   // Fill a rectangle to demonstrate the effective clipping region.
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 255)), 0, 0, 500, 500);

   // Reset the clipping region to infinite.
   graphics.ResetClip();

   // Draw clipRect and intersectRect.
   Rect clipRect;
   clipRegion.GetBounds(&clipRect, &graphics);
   Rect intersectRect;
   intersectRegion.GetBounds(&intersectRect, &graphics);
   graphics.DrawRectangle(&Pen(Color(255, 0, 0, 0)), clipRect);
   graphics.DrawRectangle(&Pen(Color(255, 255, 0, 0)), intersectRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetClip, GetClipBounds, Region, SetClip
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::IsClipEmpty()

The IsClipEmpty method determines whether the clipping region of this Graphics object is empty.

BOOL IsClipEmpty(void) const;

Parameters

This method has no parameters.

Return Values

If the clipping region of a Graphics object is empty, this method returns TRUE; otherwise, it returns FALSE.

Remarks

If the clipping region of a Graphics object is empty, there is no area left in which to draw. Consequently, nothing will be drawn when the clipping region is empty.

Example Code [C++]

The following example determines whether the clipping region is empty and, if it isn't, draws a rectangle.

VOID Example_IsClipEmpty(HDC hdc)
{
   Graphics graphics(hdc);

   // If the clipping region is not empty, draw a rectangle.
   if (!graphics.IsClipEmpty())
   {
   graphics.DrawRectangle(&Pen(Color(255, 0, 0, 0), 3), 0, 0, 100, 100);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetClip, GetClipBounds, IsVisibleClipEmpty, Region, ResetClip, SetClip
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::IsVisible Methods

This topic lists the IsVisible methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • IsVisible(Point& point)
  • IsVisible(PointF& point)
  • IsVisible(Rect& rect)
  • IsVisible(RectF& rect)
  • IsVisible(INT x, INT y)
  • IsVisible(REAL x, REAL y)
  • IsVisible(INT x, INT y, INT width, INT height)
  • IsVisible(REAL x, REAL y, REAL width, REAL height)


Graphics::IsVisible(Point& point)

The IsVisible method determines whether the specified point is inside the visible clipping region of this Graphics object. The visible clipping region is the intersection of the clipping region of this Graphics object and the clipping region of the window.

BOOL IsVisible(
  const Point& point
) const;

Parameters

point
[in] Reference to a point to be tested to see whether it is inside the visible clipping region.

Return Values

If the specified point is inside the visible clipping region, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a Point object and determines whether the point is visible on the display device. If it is, it fills an ellipse that represents the point.

VOID Example_IsVisible(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Point object.
   Point visiblePoint(100, 100);

   // Determine whether the point is visible and, if it is,
   // draw an ellipse.
   if (graphics.IsVisible(visiblePoint))
   {
   graphics.FillEllipse(&SolidBrush(Color(255, 0, 0, 0)), 100, 100, 5, 5);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
IsVisibleClipEmpty, Point


Graphics::IsVisible(PointF& point)

The IsVisible method determines whether the specified point is inside the visible clipping region of this Graphics object. The visible clipping region is the intersection of the clipping region of this Graphics object and the clipping region of the window.

BOOL IsVisible(
  const PointF& point
) const;

Parameters

point
[in] Reference to a point to be tested to see whether it is inside the visible clipping region.

Return Values

If the specified point is inside the visible clipping region, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a PointF object and tests whether the point is visible on the display device. If it is, it fills an ellipse that represents the point.

VOID Example_IsVisible2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a PointF object.
   PointF visiblePoint(100.2f, 100.2f);

   // Test whether the point is visible and, if it is, draw an ellipse.
   if (graphics.IsVisible(visiblePoint))
   {
   graphics.FillEllipse(&SolidBrush(Color(255, 0, 0, 0)), 100.2f, 100.2f, 5.0f, 5.0f);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
IsVisibleClipEmpty, PointF


Graphics::IsVisible(Rect& rect)

The IsVisible method determines whether the specified rectangle intersects the visible clipping region of this Graphics object. The visible clipping region is the intersection of the clipping region of this Graphics object and the clipping region of the window.

BOOL IsVisible(
  const Rect& rect
) const;

Parameters

rect
[in] Reference to a rectangle to be tested to determine whether it intersects the visible clipping region.

Return Values

If the specified rectangle intersects the visible clipping region, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a Rect object and determines whether the rectangle is visible or partially visible on the display device. If it is, it fills the rectangle.

VOID Example_IsVisible3(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Rect object.
   Rect visibleRect(0, 0, 100, 100);

   // Determine whether the rectangle is visible and,
   // if it is, fill it.
   if (graphics.IsVisible(visibleRect))
   {
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), visibleRect);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
IsVisibleClipEmpty, Rect


Graphics::IsVisible(RectF& rect)

The IsVisible method determines whether the specified rectangle intersects the visible clipping region of this Graphics object. The visible clipping region is the intersection of the clipping region of this Graphics object and the clipping region of the window.

BOOL IsVisible(
  const RectF& rect
) const;

Parameters

rect
[in] Reference to a rectangle to be tested to see whether it intersects the visible clipping region.

Return Values

If the specified rectangle intersects the visible clipping region, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a RectF object and determines whether the rectangle is visible or partially visible on the display device. If it is, it fills the rectangle.

VOID Example_IsVisible4(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a RectF object.
   RectF visibleRect(0.0f, 0.0f, 100.2f, 100.2f);

   // Determine whether the rectangle is visible and,
   // if it is, fill it.
   if (graphics.IsVisible(visibleRect))
   {
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), visibleRect);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
IsVisibleClipEmpty, RectF


Graphics::IsVisible(INT x, INT y)

The IsVisible method determines whether the specified point is inside the visible clipping region of this Graphics object. The visible clipping region is the intersection of the clipping region of this Graphics object and the clipping region of the window.

BOOL IsVisible(
  INT x,
  INT y
) const;

Parameters

x
[in] Integer that specifies the x-coordinate of the point to test.
y
[in] Integer that specifies the y-coordinate of the point to test.

Return Values

If the specified coordinates are inside the visible clipping region, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example tests whether the specified point is visible on the display device. If it is, it fills an ellipse that represents that point.

VOID Example_IsVisible5(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the coordinates of the point.
   int x = 100;
   int y = 100;

   // If the point (x, y) is visible, fill an ellipse that represents it.
   if (graphics.IsVisible(x, y))
   {
   graphics.FillEllipse(&SolidBrush(Color(255, 0, 0, 0)), x, y, 5, 5);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
IsVisibleClipEmpty


Graphics::IsVisible(REAL x, REAL y)

The IsVisible method determines whether the specified point is inside the visible clipping region of this Graphics object. The visible clipping region is the intersection of the clipping region of this Graphics object and the clipping region of the window.

BOOL IsVisible(
  REAL x,
  REAL y
) const;

Parameters

x
[in] Real number that specifies the x-coordinate of the point to test.
y
[in] Real number that specifies the y-coordinate of the point to test.

Return Values

If the specified coordinates are inside the visible clipping region, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example determines whether the specified point is visible on the display device. If it is, it fills an ellipse that represents that point.

VOID Example_IsVisible7(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the coordinates of the point.
   REAL x = 100.5f;
   REAL y = 100.5f;

   // If the point (x, y) is visible, fill an ellipse that represents it.
   if (graphics.IsVisible(x, y))
   {
   graphics.FillEllipse(&SolidBrush(Color(255, 0, 0, 0)), x, y, 5.0f, 5.0f);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
IsVisibleClipEmpty


Graphics::IsVisible(INT x, INT y, INT width, INT height)

The IsVisible method determines whether the specified rectangle intersects the visible clipping region of this Graphics object. The visible clipping region is the intersection of the clipping region of this Graphics object and the clipping region of the window.

BOOL IsVisible(
  INT x,
  INT y,
  INT width,
  INT height
) const;

Parameters

x
[in] Integer that specifies the x-coordinate of the upper-left corner of the rectangle to test.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the rectangle to test.
width
[in] Integer that specifies the width of the rectangle to test.
height
[in] Integer that specifies the height of the rectangle to test.

Return Values

If the specified rectangle intersects the visible clipping region, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example determines whether the specified rectangle is visible or partially visible on the display device. If it is, it fills the rectangle.

VOID Example_IsVisible6(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the coordinates of the rectangle.
   int x = 0;
   int y = 0;
   int width = 100;
   int height = 100;

   // If the rectangle is visible, fill it.
   if (graphics.IsVisible(x, y, width, height))
   {
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), x, y, width, height);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
IsVisibleClipEmpty


Graphics::IsVisible(REAL x, REAL y, REAL width, REAL height)

The IsVisible method determines whether the specified rectangle intersects the visible clipping region of this Graphics object. The visible clipping region is the intersection of the clipping region of this Graphics object and the clipping region of the window.

BOOL IsVisible(
  REAL x,
  REAL y,
  REAL width,
  REAL height
) const;

Parameters

x
[in] Real number that specifies the x-coordinate of the upper-left corner of the rectangle to test.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the rectangle to test.
width
[in] Real number that specifies the width of the rectangle to test.
height
[in] Real number that specifies the height of the rectangle to test.

Return Values

If the specified rectangle intersects the visible clipping region, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example determines whether the specified rectangle is visible or partially visible on the display device. If it is, it fills the rectangle.

VOID Example_IsVisible8(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the coordinates of the rectangle.
   REAL x = 0;
   REAL y = 0;
   REAL width = 100;
   REAL height = 100;

   // If the rectangle is visible, fill it.
   if (graphics.IsVisible(x, y, width, height))
   {
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), x, y, width, height);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
IsVisibleClipEmpty


Graphics::IsVisibleClipEmpty()

The IsVisibleClipEmpty method determines whether the visible clipping region of this Graphics object is empty. The visible clipping region is the intersection of the clipping region of this Graphics object and the clipping region of the window.

BOOL IsVisibleClipEmpty(void) const;

Parameters

This method has no parameters.

Return Values

If the visible clipping region of this Graphics object is empty, this method returns TRUE; otherwise, it returns FALSE.

Remarks

If the visible clipping region of a Graphics object is empty, there is no area left in which to draw. Consequently, nothing will be drawn when the visible clipping region is empty.

Example Code [C++]

The following example determines whether the visible clipping region is empty. If it is not empty, it draws a rectangle.

VOID Example_IsVisibleClipEmpty(HDC hdc)
{
   Graphics graphics(hdc);

   // If the clipping region is not empty, draw a rectangle.
   if (!graphics.IsVisibleClipEmpty())
   {
   graphics.DrawRectangle(&Pen(Color(255, 0, 0, 0), 3), 0, 0, 100, 100);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::MeasureCharacterRanges(string, length, font, layoutRect, stringFormat, regionCount, regions)

The MeasureCharacterRanges method gets a set of regions each of which bounds a range of character positions within a string.

Status MeasureCharacterRanges(
  const WCHAR* string,
  INT length,
  const Font* font,
  const RectF& layoutRect,
  const StringFormat* stringFormat,
  INT regionCount,
  Region* regions
) const;

Parameters

string
[in] Pointer to a wide-character string.
length
[in] Integer that specifies the number of characters in the string array. If the string parameter points to a NULL-terminated string, this parameter can be set to –1.
font
[in] Pointer to a Font object that specifies the font characteristics (the family name, size, and style of the font) to be applied to the string.
layoutRect
[in] Reference to a rectangle that bounds the string.
stringFormat
[in] Pointer to a StringFormat object that specifies the character ranges and layout information, such as alignment, trimming, tab stops, and so forth.
regionCount
[in] Integer that specifies the number of regions that are expected to be received into the regions array. This number should be equal to the number of character ranges currently in the StringFormat object.
regions
[out] Pointer to an array of Region objects that receives the regions, each of which bounds a range of text.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A character range is a range of character positions within a string of text. The area of the display that is occupied by a group of characters that are specified by the character range, is the bounding region. A character range is set by StringFormat::SetMeasurableCharacterRanges. The number of ranges that are currently set can be determined by calling StringFormat::GetMeasurableCharacterRangeCount. This number is also the number of regions expected to be obtained by the MeasureCharacterRanges method.

Example Code [C++]

The following example defines three ranges of character positions within a string and sets those ranges in a StringFormat object. Next, the MeasureCharacterRanges method is used to get the three regions of the display that are occupied by the characters that are specified by the ranges. This is done for three different layout rectangles to show how the regions change according to the layout of the string. Also, on the third repetition of this, the string format flags are changed so that the regions measured will include trailing spaces.

VOID MeasureCharRanges(HDC hdc)
{
   Graphics graphics(hdc);

   // Brushes and pens used for drawing and painting
   SolidBrush blueBrush(Color(255, 0, 0, 255));
   SolidBrush redBrush(Color(100, 255, 0, 0));
   Pen        blackPen(Color(255, 0, 0, 0));

   // Layout rectangles used for drawing strings
   RectF   layoutRect_A(20.0f, 20.0f, 130.0f, 130.0f);
   RectF   layoutRect_B(160.0f, 20.0f, 165.0f, 130.0f);
   RectF   layoutRect_C(335.0f, 20.0f, 165.0f, 130.0f);

   // Three different ranges of character positions within the string
   CharacterRange charRanges[3] = { CharacterRange(3, 5),
                                    CharacterRange(15, 2),
                                    CharacterRange(30, 15), };

   // Font and string format to apply to string when drawing
   Font         myFont(L"Times New Roman", 16.0f);
   StringFormat strFormat;

    // Other variables
   Region* pCharRangeRegions; // pointer to CharacterRange regions
   short   i;                 // loop counter
   INT     count;             // number of character ranges set
   WCHAR   string[] = L"The quick, brown fox easily jumps over the lazy dog.";

   // Set three ranges of character positions.
   strFormat.SetMeasurableCharacterRanges(3, charRanges);

   // Get the number of ranges that have been set, and allocate memory to
   // store the regions that correspond to the ranges.
   count = strFormat.GetMeasurableCharacterRangeCount();
   pCharRangeRegions = new Region[count];

   // Get the regions that correspond to the ranges within the string when
   // layout rectangle A is used. Then draw the string, and show the regions.
   graphics.MeasureCharacterRanges(string, -1,
      &myFont, layoutRect_A, &strFormat, count, pCharRangeRegions);
   graphics.DrawString(string, -1,
      &myFont, layoutRect_A, &strFormat, &blueBrush);
   graphics.DrawRectangle(&blackPen, layoutRect_A);
   for ( i = 0; i < count; i++)
   {
      graphics.FillRegion(&redBrush, pCharRangeRegions + i);
   }

   // Get the regions that correspond to the ranges within the string when
   // layout rectangle B is used. Then draw the string, and show the regions.
   graphics.MeasureCharacterRanges(string, -1,
      &myFont, layoutRect_B, &strFormat, count, pCharRangeRegions);
   graphics.DrawString(string, -1,
      &myFont, layoutRect_B, &strFormat, &blueBrush);
   graphics.DrawRectangle(&blackPen, layoutRect_B);
   for ( i = 0; i < count; i++)
   {
      graphics.FillRegion(&redBrush, pCharRangeRegions + i);
   }

   // Get the regions that correspond to the ranges within the string when
   // layout rectangle C is used. Set trailing spaces to be included in the
   // regions. Then draw the string, and show the regions.
   strFormat.SetFormatFlags(StringFormatFlagsMeasureTrailingSpaces);
   graphics.MeasureCharacterRanges(string, -1,
      &myFont, layoutRect_C, &strFormat, count, pCharRangeRegions);
   graphics.DrawString(string, -1,
      &myFont, layoutRect_C, &strFormat, &blueBrush);
   graphics.DrawRectangle(&blackPen, layoutRect_C);
   for ( i = 0; i < count; i++)
   {
      graphics.FillRegion(&redBrush, pCharRangeRegions + i);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
CharacterRange, GetMeasurableCharacterRangeCount, SetMeasurableCharacterRanges


Graphics::MeasureDriverString(text, length, font, positions, flags, matrix, boundingBox)

The MeasureDriverString method measures the bounding box for the specified characters and their corresponding positions.

Status MeasureDriverString(
  const UINT16* text,
  INT length,
  const Font* font,
  const PointF* positions,
  INT flags,
  const Matrix* matrix,
  RectF* boundingBox
) const;

Parameters

text
[in] Pointer to an array of 16-bit values. If the DriverStringOptionsCmapLookup flag is set, each value specifies a Unicode character to be displayed. Otherwise, each value specifies an index to a font glyph that defines a character to be displayed.
length
[in] Integer that specifies the number of values in the text array. The length parameter can be set to –1 if the string is null terminated.
font
[in] Pointer to a Font object that specifies the family name, size, and style of the font to be applied to the string.
positions
[in] If the DriverStringOptionsRealizedAdvance flag is set, positions is a pointer to a PointF object that specifies the position of the first glyph. Otherwise, positions is an array of PointF objects, each of which specifies the origin of an individual glyph.
flags
[in] Integer that specifies the options for the appearance of the string. This value must be an element of the DriverStringOptions enumeration or the result of a bitwise OR applied to two or more of these elements.
matrix
[in] Pointer to a Matrix object that specifies the transformation matrix to apply to each value in the text array.
boundingBox
[out] Pointer to a RectF object that receives the rectangle that bounds the string.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawDriverString, DriverStringOptions, Font, Matrix, RectF, SolidBrush


Graphics::MeasureString Methods

This topic lists the MeasureString methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • MeasureString(string, length, font, layoutRect, boundingBox)
  • MeasureString(string, length, font, layoutRect, stringFormat, boundingBox, codepointsFitted, linesFilled)
  • MeasureString(string, length, font, layoutRectSize, stringFormat, size, codepointsFitted, linesFilled)
  • MeasureString(string, length, font, origin, boundingBox)
  • MeasureString(string, length, font, origin, stringFormat, boundingBox)


Graphics::MeasureString(string, length, font, layoutRect, boundingBox)

The MeasureString method measures the extent of the string in the specified font and layout rectangle.

Status MeasureString(
  const WCHAR* string,
  INT length,
  const Font* font,
  const RectF& layoutRect,
  RectF* boundingBox
) const;

Parameters

string
[in] Pointer to a wide-character string to be measured.
length
[in] Integer that specifies the number of characters in the string array. The length parameter can be set to –1 if the string is null terminated.
font
[in] Pointer to a Font object that specifies the family name, size, and style of the font that is applied to the string.
layoutRect
[in] Reference to a rectangle that bounds the string.
boundingBox
[out] Pointer to a RectF object that receives the rectangle that bounds the string.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example measures the size of a string and then draws a rectangle that represents that size.

VOID Example_MeasureString(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the string.
   WCHAR string[256];
   wcscpy(string, L"Measure Text");
   Font font(L"Arial", 16);
   RectF layoutRect(0, 0, 100, 50);
   RectF boundRect;

   // Measure the string.
   graphics.MeasureString(string, wcslen(string), &font, layoutRect, &boundRect);

   // Draw a rectangle that represents the size of the string.
   graphics.DrawRectangle(&Pen(Color(255, 0, 0, 0)), boundRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawString, Font, RectF


Graphics::MeasureString(string, length, font, layoutRect, stringFormat, boundingBox, codepointsFitted, linesFilled)

The MeasureString method measures the extent of the string in the specified font, format, and layout rectangle.

Status MeasureString(
  const WCHAR* string,
  INT length,
  const Font* font,
  const RectF& layoutRect,
  const StringFormat* stringFormat,
  RectF* boundingBox,
  INT* codepointsFitted,
  INT* linesFilled
) const;

Parameters

string
[in] Pointer to a wide-character string to be measured.
length
[in] Integer that specifies the number of characters in the string array. The length parameter can be set to –1 if the string is null terminated.
font
[in] Pointer to a Font object that specifies the family name, size, and style of the font to be applied to the string.
layoutRect
[in] Reference to the rectangle that bounds the string.
stringFormat
[in] Pointer to a StringFormat object that specifies the layout information, such as alignment, trimming, tab stops, and so forth.
boundingBox
[out] Pointer to a RectF object that receives the rectangle that bounds the string.
codepointsFitted
[out] Optional. Pointer to an INT that receives the number of characters that actually fit into the layout rectangle. The default value is a NULL pointer.
linesFilled
[out] Optional. Pointer to an INT that receives the number of lines that fit into the layout rectangle. The default value is a NULL pointer.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example measures the size of a string and then draws a rectangle that represents that size.

VOID Example_MeasureString2(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the string.
   WCHAR string[256];
   wcscpy(string, L"Measure Text");
   Font font(L"Arial", 16);
   RectF layoutRect(0.0f, 0.0f, 100.0f, 50.0f);
   StringFormat format;
   format.SetAlignment(StringAlignmentFar);
   RectF boundRect;

   // Measure the string.
   graphics.MeasureString(string, wcslen(string), &font, layoutRect, &format, &boundRect);

   // Draw a rectangle that represents the size of the string.
   graphics.DrawRectangle(&Pen(Color(255, 0, 0, 0)), boundRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawString, Font, RectF, StringFormat


Graphics::MeasureString(string, length, font, layoutRectSize, stringFormat, size, codepointsFitted, linesFilled)

The MeasureString method measures the extent of the string in the specified font, format, and layout rectangle.

Status MeasureString(
  const WCHAR* string,
  INT length,
  const Font* font,
  const SizeF& layoutRectSize,
  const StringFormat* stringFormat,
  SizeF* size,
  INT* codepointsFitted,
  INT* linesFilled
) const;

Parameters

string
[in] Pointer to a wide-character string to be measured.
length
[in] Integer that specifies the number of characters in the string array. The length parameter can be set to –1 if the string is null terminated.
font
[in] Pointer to a Font object that specifies the family name, size, and style of the font that is applied to the string.
layoutRectSize
[in] Reference to a SizeF object that specifies the width and height of a rectangle that bounds the string.
stringFormat
[in] Pointer to a StringFormat object that specifies the layout information, such as alignment, trimming, tab stops, and so forth.
size
[out] Pointer to a SizeF object that receives the width and height of the rectangle that bounds the string.
codepointsFitted
[out] Optional. Pointer to an INT that receives the number of characters that actually fit into the layout rectangle. The default value is a NULL pointer.
linesFilled
[out] Optional. Pointer to an INT that receives the number of lines that actually fit into the layout rectangle. The default value is a NULL pointer.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example measures the size of a string and then draws a rectangle that represents that size.

VOID Example_MeasureString3(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the string.
   WCHAR string[256];
   wcscpy(string, L"Measure Text");
   Font font(L"Arial", 16);
   SizeF layoutSize(100, 50);
   StringFormat format;
   format.SetAlignment(StringAlignmentFar);
   SizeF stringSize;

   // Measure the string.
   graphics.MeasureString(string, wcslen(string), &font, layoutSize, &format, &stringSize);

   // Draw a rectangle that represents the size of the string.
   graphics.DrawRectangle(&Pen(Color(255, 0, 0, 0)), Rect(0, 0, stringSize.Width, stringSize.Height));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawString, Font, RectF, StringFormat


Graphics::MeasureString(string, length, font, origin, boundingBox)

The MeasureString method measures the extent of the string in the specified font and layout rectangle.

Status MeasureString(
  const WCHAR* string,
  INT length,
  const Font* font,
  const PointF& origin,
  RectF* boundingBox
) const;

Parameters

string
[in] Pointer to a wide-character string to be measured.
length
[in] Integer that specifies the number of characters in the string array. The length parameter can be set to –1 if the string is null terminated.
font
[in] Pointer to a Font object that specifies the family name, size, and style of the font that is applied to the string.
origin
[in] Reference to the point at which the string starts.
boundingBox
[out] Pointer to a RectF object that receives the rectangle that bounds the string.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example measures the size of a string and then draws a rectangle that represents that size.

VOID Example_MeasureString4(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the string.
   WCHAR string[256];
   wcscpy(string, L"Measure Text");
   Font font(L"Arial", 16);
   PointF origin(0.0f, 0.0f);
   RectF boundRect;

   // Measure the string.
   graphics.MeasureString(string, wcslen(string), &font, origin, &boundRect);

   // Draw a rectangle that represents the size of the string.
   graphics.DrawRectangle(&Pen(Color(255, 0, 0, 0)), boundRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawString, Font, RectF


Graphics::MeasureString(string, length, font, origin, stringFormat, boundingBox)

The MeasureString method measures the extent of the string in the specified font, format, and layout rectangle.

Status MeasureString(
  const WCHAR* string,
  INT length,
  const Font* font,
  const PointF& origin,
  const StringFormat* stringFormat,
  RectF* boundingBox
) const;

Parameters

string
[in] Pointer to a wide-character string to be measured.
length
[in] Integer that specifies the number of characters in the string array. The length parameter can be set to –1 if the string is null terminated.
font
[in] Pointer to a Font object that specifies the family name, size, and style of the font that is applied to the string.
origin
[in] Reference to the point at which the string starts.
stringFormat
[in] Pointer to a StringFormat object that specifies the layout information, such as alignment, trimming, tab stops, and so forth.
boundingBox
[out] Pointer to a RectF object that receives the rectangle that bounds the string.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example measures the size of a string and then draws a rectangle that represents that size.

VOID Example_MeasureString5(HDC hdc)
{
   Graphics graphics(hdc);

   // Set up the string.
   WCHAR string[256];
   wcscpy(string, L"Measure Text");
   Font font(L"Arial", 16);
   PointF origin(0.0f, 0.0f);
   StringFormat format;
   format.SetAlignment(StringAlignmentCenter);
   RectF boundRect;

   // Measure the string.
   graphics.MeasureString(string, wcslen(string), &font, origin, &format, &boundRect);

   // Draw a rectangle that represents the size of the string.
   graphics.DrawRectangle(&Pen(Color(255, 0, 0, 0)), boundRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
DrawString, Font, PointF, StringFormat


Graphics::MultiplyTransform(matrix, order)

The MultiplyTransform method updates this Graphics object's world transformation matrix with the product of itself and another matrix.

Status MultiplyTransform(
  Matrix* matrix,
  MatrixOrder order
);

Parameters

matrix
[in] Pointer to a matrix that will be multiplied by the world transformation matrix of this Graphics object.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of multiplication. MatrixOrderPrepend specifies that the passed matrix is on the left, and MatrixOrderAppend specifies that the passed matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example calls the RotateTransform method of a Graphics object to fill its world transformation matrix with the elements that represent a 30-degree rotation. Then the code calls the MultiplyTransform method to replace the world transformation matrix (which represents the 30-degree rotation) of the Graphics object with the product of itself and a translation matrix. At that point, the world transformation matrix of the Graphics object represents a composite transformation: first rotate, then translate. Finally, the code calls the DrawEllipse method to draw an ellipse that is rotated and translated.

VOID Example_MultiplyTransform(HDC hdc)
{
   Graphics graphics(hdc);

   Matrix matrix;
   matrix.Translate(150.0f, 100.0f);

   graphics.RotateTransform(30.0f);                         // first rotate
   graphics.MultiplyTransform(&matrix, MatrixOrderAppend);  // then translate

   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawEllipse(&pen, -80, -40, 160, 80);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, ResetTransform, RotateTransform, ScaleTransform, SetTransform, TransformPoints, TranslateTransform
Tasks and Examples
Transformations
Concepts
Coordinate Systems and Transformations


Graphics::ReleaseHDC(hdc)

The ReleaseHDC method releases a device context handle obtained by a previous call to the GetHDC method of this Graphics object.

VOID ReleaseHdc(
  HDC hdc
);

Parameters

hdc
[in] Handle to a device context obtained by a previous call to the GetHDC method of this Graphics object.

Return Values

This method does not return a value.

Example Code [C++]

The following function has a pointer to a Graphics object as its only parameter. The function calls GetHDC to get a handle to the device context associated with the Graphics object and then passes that device context handle to the GDI Rectangle function. The call to ReleaseHDC releases the device context handle.

VOID Example_GetReleaseHDC(Graphics* g)
{
   Pen pen(Color(255, 0, 0, 255));
   g->DrawEllipse(&pen, 10, 10, 100, 50);  // GDI+

   HDC hdc = g->GetHDC();

      // Make GDI calls, but don't call any methods
      // on g until after the call to ReleaseHDC.
      Rectangle(hdc, 120, 10, 220, 60);  // GDI

   g->ReleaseHDC(hdc);

   // Ok to call methods on g again.
   g->DrawLine(&pen, 240, 10, 340, 60);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
FromHDC Methods, GetHDC, Graphics Constructors
Concepts
Changes in the Programming Model


Graphics::ResetClip()

The ResetClip method sets the clipping region of this Graphics object to an infinite region.

Status ResetClip(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

If the clipping region of a Graphics object is infinite, then items drawn by that Graphics object will not be clipped.

Example Code [C++]

The following example creates a Graphics object and sets its clipping region to a rectangle. The code fills two ellipses that intersect the rectangular clipping region. The first ellipse is clipped, but the second ellipse is not clipped because it is filled after a call to ResetClip.

VOID Example_ResetClip(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the clipping region, and draw its outline.
   graphics.SetClip(Rect(100, 50, 200, 120));
   Pen blackPen(Color(255, 0, 0, 0), 2.0f);
   graphics.DrawRectangle(&blackPen, 100, 50, 200, 120);

   // Fill a clipped ellipse in red.
   SolidBrush redBrush(Color(255, 255, 0, 0));
   graphics.FillEllipse(&redBrush, 80, 40, 100, 70);

   // Reset the clipping region.
   graphics.ResetClip();

   // Fill an unclipped ellipse with blue.
   SolidBrush blueBrush(Color(255, 0, 0, 255));
   graphics.FillEllipse(&blueBrush, 160, 150, 100, 60);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetClip, IntersectClip Methods, IsClipEmpty, IsEmpty,
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::ResetTransform()

The ResetTransform method sets the world transformation matrix of this Graphics object to the identity matrix.

Status ResetTransform(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The identity matrix represents a transformation that does nothing. If the world transformation matrix of a Graphics object is the identity matrix, then no world transformation is applied to items drawn by that Graphics object.

Example Code [C++]

The following example sets the world transformation of a Graphics object to a 45-degree rotation and then draws a rectangle. The code calls the ResetTransform method of the Graphics object and then draws a second rectangle. No rotation transformation is applied to the second rectangle.

VOID Example_ResetTransform(HDC hdc)
{
   Graphics graphics(hdc);

   // Rotate the transformation and draw a rectangle.
   graphics.RotateTransform(45.0f);
   Pen blackPen(Color(255, 0, 0, 0));
   graphics.DrawRectangle(&blackPen, 100, 0, 100, 50);

   // Reset the transformation to identity, and draw a second rectangle.
   graphics.ResetTransform();
   Pen redPen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&redPen, 110, 0, 100, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, MultiplyTransform, RotateTransform, ScaleTransform, SetTransform, TransformPoints, TranslateTransform
Tasks and Examples
Transformations
Concepts
Coordinate Systems and Transformations


Graphics::Restore(gstate)

The Restore method sets the state of this Graphics object to the state stored by a previous call to the Save method of this Graphics object.

Status Restore(
  GraphicsState gstate
);

Parameters

gstate
[in] 32-bit value (returned by a previous call to the Save method of this Graphics object) that identifies a block of saved state.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

When you call the Save method of a Graphics object, an information block that holds the state of the Graphics object is put on a stack. The Save method returns a value that identifies that information block. When you pass the identifying value to the Restore method, the information block is removed from the stack and is used to restore the Graphics object to the state it was in at the time of the Save call. Note that the identifier returned by a given call to the Save method can be passed only once to the Restore method.

Calls to the Save method can be nested; that is, you can call the Save method several times before you call the Restore method. Each time you call the Save method, an information block is put on the stack, and you receive an identifier for the information block. When you pass one of those identifiers to the Restore method, the Graphics object is returned to the state it was in at the time of the Save call that returned that particular identifier. The information block placed on the stack by that Save call is removed from the stack, and all information blocks placed on that stack after that Save call are also removed.

Calls to the BeginContainer method place information blocks on the same stack as calls to the Save method. Just as a Restore call is paired with a Save call, an EndContainer call is paired with a BeginContainer call.

Caution When you call Restore, all information blocks placed on the stack (by Save or by BeginContainer) after the corresponding call to Save are removed from the stack. Likewise, When you call EndContainer, all information blocks placed on the stack (by Save or by BeginContainer) after the corresponding call to BeginContainer are removed from the stack.

Example Code [C++]

The following examples show two ways to use the Restore method. The first example shows how to restore nested saved states, and the second example shows how to restore only the first of two nested saved states.

  • Restoring Nested Saved States
  • Restoring Only the First of Two Nested Saved States

Restoring Nested Saved States

The following example sets the world transformation of a Graphics object to a rotation and then saves the state of the Graphics object. Next, the code calls TranslateTransform, and saves the state again. Then the code calls ScaleTransform. At that point, the world transformation of the Graphics object is a composite transformation: first rotate, then translate, then scale. The code uses a red pen to draw an ellipse that is transformed by that composite transformation.

The code passes state2, which was returned by the second call to Save, to the Restore method, and draws the ellipse again using a green pen. The green ellipse is rotated and translated but not scaled. Finally the code passes state1, which was returned by the first call to Save, to the Restore method, and draws the ellipse again using a blue pen. The blue ellipse is rotated but not translated or scaled.

VOID Example_Save1(HDC hdc)
{
   Graphics graphics(hdc);
   GraphicsState state1, state2;

   graphics.RotateTransform(30.0f);
   state1 = graphics.Save();
   graphics.TranslateTransform(100.0f, 0.0f, MatrixOrderAppend);
   state2 = graphics.Save();
   graphics.ScaleTransform(1.0f, 3.0f, MatrixOrderAppend);

   // Draw an ellipse.
   // Three transformations apply: rotate, then translate, then scale.
   Pen redPen(Color(255, 255, 0, 0));
   graphics.DrawEllipse(&redPen, 0, 0, 100, 20);

   // Restore to state2 and draw the ellipse again.
   // Two transformations apply: rotate then translate.
   graphics.Restore(state2);
   Pen greenPen(Color(255, 0, 255, 0));
   graphics.DrawEllipse(&greenPen, 0, 0, 100, 20);

   // Restore to state1 and draw the ellipse again.
   // Only the rotation transformation applies.
   graphics.Restore(state1);
   Pen bluePen(Color(255, 0, 0, 255));
   graphics.DrawEllipse(&bluePen, 0, 0, 100, 20);
}

Restoring Only the First of Two Nested Saved States

The following example sets the world transformation of a Graphics object to a rotation and then saves the state of the Graphics object. Next, the code calls TranslateTransform, and saves the state again. Then the code calls ScaleTransform. At that point, the world transformation of the Graphics object is a composite transformation: first rotate, then translate, then scale. The code uses a red pen to draw an ellipse that is transformed by that composite transformation.

The code passes state1, which was returned by the first call to Save, to the Restore method, and draws the ellipse again using a green pen. The green ellipse is rotated but not translated or scaled.

Next the code attempts to restore the state identified by state2. The attempt fails because the call Restore(state1) removed the information blocks identified by both state1 and state2 from the stack.

VOID Example_Save2(HDC hdc)
{
   Graphics graphics(hdc);
   GraphicsState state1, state2;

   graphics.RotateTransform(30.0f);
   state1 = graphics.Save();
   graphics.TranslateTransform(100.0f, 0.0f, MatrixOrderAppend);
   state2 = graphics.Save();
   graphics.ScaleTransform(1.0f, 3.0f, MatrixOrderAppend);

   // Draw an ellipse.
   // Three transformations apply: rotate, then translate, then scale.
   Pen redPen(Color(255, 255, 0, 0));
   graphics.DrawEllipse(&redPen, 0, 0, 100, 20);

   // Restore to state1 and draw the ellipse again.
   // Only the rotation transformation applies.
   graphics.Restore(state1);
   Pen greenPen(Color(255, 0, 255, 0));
   graphics.DrawEllipse(&greenPen, 0, 0, 100, 20);

   // The information block identified by state2 has been lost.
   // The following call to Restore has no effect because
   // Restore(state1) removed from the stack the
   // information blocks identified by state1 and state2.
   graphics.Restore(state2);

   // The Graphics object is still in the state identified by state1.
   // The following code draws a blue ellipse on top of the previously
   // drawn green ellipse.
   Pen bluePen(Color(255, 0, 0, 255));
   graphics.DrawEllipse(&bluePen, 0, 0, 100, 20);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Save


Graphics::RotateTransform(angle, order)

The RotateTransform method updates the world transformation matrix of this Graphics object with the product of itself and a rotation matrix.

Status RotateTransform(
  REAL angle,
  MatrixOrder order
);

Parameters

angle
[in] Real number that specifies the angle, in degrees, of rotation.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of multiplication. MatrixOrderPrepend specifies that the rotation matrix is on the left, and MatrixOrderAppend specifies that the rotation matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example sets the world transformation of a Graphics object to a translation. The call to RotateTransform multiplies the Graphics object's existing world transformation matrix (translation) by a rotation matrix. The MatrixOrderAppend argument specifies that the multiplication is done with the rotation matrix on the right. At that point, the world transformation matrix of the Graphics object represents a composite transformation: first translate, then rotate. The call to DrawEllipse draws a translated and rotated ellipse.

VOID Example_RotateTransform(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 255, 0, 0));

   graphics.TranslateTransform(100.0f, 0.0f);           // first translate
   graphics.RotateTransform(30.0f, MatrixOrderAppend);  // then rotate
   graphics.DrawEllipse(&pen, 0, 0, 200, 80);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, MultiplyTransform, ResetTransform, ScaleTransform, SetTransform, TransformPoints, TranslateTransform
Tasks and Examples
Transformations
Concepts
Coordinate Systems and Transformations


Graphics::Save()

The Save method saves the current state (transformations, clipping region, and quality settings) of this Graphics object. You can restore the state later by calling the Restore method.

GraphicsState Save(void);

Parameters

This method has no parameters.

Return Values

This method returns a value that identifies the saved state. Pass this value to the Restore method when you want to restore the state. The GraphicsState data type is defined in Gdiplusenums.h.

Remarks

When you call the Save method of a Graphics object, an information block that holds the state of the Graphics object is put on a stack. The Save method returns a value that identifies that information block. When you pass the identifying value to the Restore method, the information block is removed from the stack and is used to restore the Graphics object to the state it was in at the time of the Save call. Note that the identifier returned by a given call to the Save method can be passed only once to the Restore method.

Calls to the Save method can be nested; that is, you can call the Save method several times before you call the Restore method. Each time you call the Save method, an information block is put on the stack, and you receive an identifier for the information block. When you pass one of those identifiers to the Restore method, the Graphics object is returned to the state it was in at the time of the Save call that returned that particular identifier. The information block placed on the stack by that Save call is removed from the stack, and all information blocks placed on that stack after that Save call are also removed.

Calls to the BeginContainer method place information blocks on the same stack as calls to the Save method. Just as a Restore call is paired with a Save call, an EndContainer call is paired with a BeginContainer call.

Caution When you call Restore, all information blocks placed on the stack (by Save or by BeginContainer) after the corresponding call to Save are removed from the stack. Likewise, When you call EndContainer, all information blocks placed on the stack (by Save or by BeginContainer) after the corresponding call to BeginContainer are removed from the stack.

Example Code [C++]

The following examples show two ways to use the Save method. The first example shows how to nest saved states and then restore them, and the second example shows how to nest saved states and then restore only the first of them.

  • Restoring Nested Saved States
  • Restoring Only the First of Two Nested Saved States

Restoring Nested Saved States

The following example sets the world transformation of a Graphics object to a rotation and then saves the state of the Graphics object. Next, the code calls TranslateTransform, and saves the state again. Then the code calls ScaleTransform. At that point, the world transformation of the Graphics object is a composite transformation: first rotate, then translate, then scale. The code uses a red pen to draw an ellipse that is transformed by that composite transformation.

The code passes state2, which was returned by the second call to Save, to the Restore method, and draws the ellipse again using a green pen. The green ellipse is rotated and translated but not scaled. Finally the code passes state1, which was returned by the first call to Save, to the Restore method, and draws the ellipse again using a blue pen. The blue ellipse is rotated but not translated or scaled.

VOID Example_Save1(HDC hdc)
{
   Graphics graphics(hdc);
   GraphicsState state1, state2;

   graphics.RotateTransform(30.0f);
   state1 = graphics.Save();
   graphics.TranslateTransform(100.0f, 0.0f, MatrixOrderAppend);
   state2 = graphics.Save();
   graphics.ScaleTransform(1.0f, 3.0f, MatrixOrderAppend);

   // Draw an ellipse.
   // Three transformations apply: rotate, then translate, then scale.
   Pen redPen(Color(255, 255, 0, 0));
   graphics.DrawEllipse(&redPen, 0, 0, 100, 20);

   // Restore to state2 and draw the ellipse again.
   // Two transformations apply: rotate then translate.
   graphics.Restore(state2);
   Pen greenPen(Color(255, 0, 255, 0));
   graphics.DrawEllipse(&greenPen, 0, 0, 100, 20);

   // Restore to state1 and draw the ellipse again.
   // Only the rotation transformation applies.
   graphics.Restore(state1);
   Pen bluePen(Color(255, 0, 0, 255));
   graphics.DrawEllipse(&bluePen, 0, 0, 100, 20);
}

Restoring Only the First of Two Nested Saved States

The following example sets the world transformation of a Graphics object to a rotation and then saves the state of the Graphics object. Next, the code calls TranslateTransform, and saves the state again. Then the code calls ScaleTransform. At that point, the world transformation of the Graphics object is a composite transformation: first rotate, then translate, then scale. The code uses a red pen to draw an ellipse that is transformed by that composite transformation.

The code passes state1, which was returned by the first call to Save, to the Restore method, and draws the ellipse again using a green pen. The green ellipse is rotated but not translated or scaled.

Next the code attempts to restore the state identified by state2. The attempt fails because the call Restore(state1) removed the information blocks identified by both state1 and state2 from the stack.

VOID Example_Save2(HDC hdc)
{
   Graphics graphics(hdc);
   GraphicsState state1, state2;

   graphics.RotateTransform(30.0f);
   state1 = graphics.Save();
   graphics.TranslateTransform(100.0f, 0.0f, MatrixOrderAppend);
   state2 = graphics.Save();
   graphics.ScaleTransform(1.0f, 3.0f, MatrixOrderAppend);

   // Draw an ellipse.
   // Three transformations apply: rotate, then translate, then scale.
   Pen redPen(Color(255, 255, 0, 0));
   graphics.DrawEllipse(&redPen, 0, 0, 100, 20);

   // Restore to state1 and draw the ellipse again.
   // Only the rotation transformation applies.
   graphics.Restore(state1);
   Pen greenPen(Color(255, 0, 255, 0));
   graphics.DrawEllipse(&greenPen, 0, 0, 100, 20);

   // The information block identified by state2 has been lost.
   // The following call to Restore has no effect because
   // Restore(state1) removed from the stack the
   // information blocks identified by state1 and state2.
   graphics.Restore(state2);

   // The Graphics object is still in the state identified by state1.
   // The following code draws a blue ellipse on top of the previously
   // drawn green ellipse.
   Pen bluePen(Color(255, 0, 0, 255));
   graphics.DrawEllipse(&bluePen, 0, 0, 100, 20);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
Restore


Graphics::ScaleTransform(sx, sy, order)

The ScaleTransform method updates this Graphics object's world transformation matrix with the product of itself and a scaling matrix.

Status ScaleTransform(
  REAL sx,
  REAL sy,
  MatrixOrder order
);

Parameters

sx
[in] Real number that specifies the horizontal scaling factor in the scaling matrix.
sy
[in] Real number that specifies the vertical scaling factor in the scaling matrix.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of multiplication. MatrixOrderPrepend specifies that the scaling matrix is on the left, and MatrixOrderAppend specifies that the scaling matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example sets the world transformation of a Graphics object to a translation. The call to ScaleTransform multiplies the Graphics object's existing world transformation matrix (translation) by a scaling matrix. The MatrixOrderAppend argument specifies that the multiplication is done with the scaling matrix on the right. At that point, the world transformation matrix of the Graphics object represents a composite transformation: first translate, then scale. The call to DrawEllipse draws a translated and scaled ellipse.

VOID Example_ScaleTransform(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   graphics.TranslateTransform(80.0f, 80.0f);               // first translate
   graphics.ScaleTransform(3.0f, 1.0f, MatrixOrderAppend);  // then scale
   graphics.DrawEllipse(&pen, 0, 0, 50, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, MultiplyTransform, ResetTransform, RotateTransform, ScaleTransform, TransformPoints, TranslateTransform
Tasks and Examples
Transformations
Concepts
Coordinate Systems and Transformations


Graphics::SetClip Methods

This topic lists the SetClip methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • SetClip(g, combineMode)
  • SetClip(hRgn, combineMode)
  • SetClip(path, combineMode)
  • SetClip(Rect& rect, CombineMode combineMode)
  • SetClip(RectF& rect, CombineMode combineMode)
  • SetClip(region, combineMode)


Graphics::SetClip(g, combineMode)

The SetClip method updates the clipping region of this Graphics object to a region that is the combination of itself and the clipping region of another Graphics object.

Status SetClip(
  const Graphics* g,
  CombineMode combineMode
);

Parameters

g
[in] Pointer to a Graphics object that contains the clipping region to be combined with the clipping region of this Graphics object.
combineMode
[in] Optional. Element of the CombineMode enumeration that specifies how the specified region is combined with the clipping region of this Graphics object. The default value is CombineModeReplace.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
CombineMode, GetClip, GetClipBounds, IntersectClip Methods, IsClipEmpty, ResetClip, TranslateClip Methods
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::SetClip(hRgn, combineMode)

The SetClip method updates the clipping region of this Graphics object to a region that is the combination of itself and a GDI region.

Status SetClip(
  HRGN hRgn,
  CombineMode combineMode
);

Parameters

hRgn
[in] Handle to a GDI region to be combined with the clipping region of this Graphics object. This is provided for legacy code. New applications should pass a Region object as the first parameter.
combineMode
[in] Optional. Element of the CombineMode enumeration that specifies how the GDI region is combined with the clipping region of this Graphics object. The default value is CombineModeReplace.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

This method assumes that the GDI region specified by hRgn is already in device units, so it does not transform the coordinates of the GDI region.

Example Code [C++]

The following example uses a GDI region to update the clipping region.

VOID Example_SetClip2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Region object, and get its handle.
   Region region(Rect(0, 0, 100, 100));
   HRGN hRegion = region.GetHRGN(&graphics);

   // Set the clipping region with hRegion.
   graphics.SetClip(hRegion);

   // Fill a rectangle to demonstrate the clipping region.
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 500, 500);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
CombineMode, GetClip, GetClipBounds, IntersectClip, IsClipEmpty, ResetClip, TranslateClip
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::SetClip(path, combineMode)

The SetClip method updates the clipping region of this Graphics object to a region that is the combination of itself and the region specified by a graphics path. If a figure in the path is not closed, this method treats the nonclosed figure as if it were closed by a straight line that connects the figure's starting and ending points.

Status SetClip(
  const GraphicsPath* path,
  CombineMode combineMode
);

Parameters

path
[in] Pointer to a GraphicsPath object that specifies the region to be combined with the clipping region of this Graphics object.
combineMode
[in] Optional. Element of the CombineMode enumeration that specifies how the specified region is combined with the clipping region of this Graphics object. The default value is CombineModeReplace.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example updates the clipping region with a GraphicsPath object and then fills a rectangle.

VOID Example_SetClip3(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a GraphicsPath object.
   GraphicsPath clipPath;
   clipPath.AddEllipse(0, 0, 200, 100);

   // Set the clipping region with hRegion.
   graphics.SetClip(&clipPath);

   // Fill a rectangle to demonstrate the clipping region.
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 500, 500);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
CombineMode, GetClip, GetClipBounds, GraphicsPath, IntersectClip, IsClipEmpty, ResetClip, TranslateClip
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::SetClip(Rect& rect, CombineMode combineMode)

The SetClip method updates the clipping region of this Graphics object to a region that is the combination of itself and a rectangle.

Status SetClip(
  const Rect& rect,
  CombineMode combineMode
);

Parameters

rect
[in] Reference to a rectangle to be combined with the clipping region of this Graphics object.
combineMode
[in] Optional. Element of the CombineMode enumeration that specifies how the specified rectangle is combined with the clipping region of this Graphics object. The default value is CombineModeReplace.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example updates the clipping region with a Rect object and then fills a rectangle.

VOID Example_SetClip4(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Rect object.
   Rect clipRect(0, 0, 200, 100);

   // Set the clipping region with hRegion.
   graphics.SetClip(clipRect);

   // Fill a rectangle to demonstrate the clipping region.
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 500, 500);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
CombineMode, GetClip, GetClipBounds, IntersectClip, IsClipEmpty, Rect, ResetClip, TranslateClip
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::SetClip(RectF& rect, CombineMode combineMode)

The SetClip method updates the clipping region of this Graphics object to a region that is the combination of itself and a rectangle.

Status SetClip(
  const RectF& rect,
  CombineMode combineMode
);

Parameters

rect
[in] Reference to a rectangle to be combined with the clipping region of this Graphics object.
combineMode
[in] Optional. Element of the CombineMode enumeration that specifies how the specified rectangle is combined with the clipping region of this Graphics object. The default value is CombineModeReplace.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example updates the clipping region with a RectF object and then fills a rectangle.

VOID Example_SetClip5(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a RectF object.
   RectF clipRectF(0, 0, 200, 100);

   // Set the clipping region with hRegion.
   graphics.SetClip(clipRectF);

   // Fill a rectangle to demonstrate the clipping region.
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 500, 500);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
CombineMode, GetClip, GetClipBounds, IntersectClip, IsClipEmpty, RectF, ResetClip, TranslateClip
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::SetClip(region, combineMode)

The SetClip method updates the clipping region of this Graphics object to a region that is the combination of itself and the region specified by a Region object.

Status SetClip(
  const Region* region,
  CombineMode combineMode
);

Parameters

region
[in] Pointer to a Region object that specifies the region to be combined with the clipping region of this Graphics object.
combineMode
[in] Optional. Element of the CombineMode enumeration that specifies how the specified region is combined with the clipping region of this Graphics object. The default value is CombineModeReplace.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example updates the clipping region with a Region object and then fills a rectangle.

VOID Example_SetClip6(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Region object.
   Region clipRegion(Rect(0, 0, 200, 100));

   // Set the clipping region with hRegion.
   graphics.SetClip(&clipRegion);

   // Fill a rectangle to demonstrate the clipping region.
   graphics.FillRectangle(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 500, 500);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
CombineMode, GetClip, GetClipBounds, IntersectClip, IsClipEmpty, Region, ResetClip, TranslateClip
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::SetCompositingMode(compositingMode)

The SetCompositingMode method sets the compositing mode of this Graphics object.

Status SetCompositingMode(
  CompositingMode compositingMode
);

Parameters

compositingMode
[in] Element of the CompositingMode enumeration that specifies the compositing mode.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Suppose you create a SolidBrush object based on a color that has an alpha component of 192, which is about 75 percent of 255. If your Graphics object has its compositing mode set to CompositingModeSourceOver, then areas filled with the solid brush are a blend that is 75 percent brush color and 25 percent background color. If your Graphics object has its compositing mode set to CompositingModeSourceCopy, then the background color is not blended with the brush color. However, the color rendered by the brush has an intensity that is 75 percent of what it would be if the alpha component were 255.

You cannot use CompositingModeSourceCopy along with TextRenderingHintClearTypeGridFit.

Example Code [C++]

The following example creates a Graphics object and sets its compositing mode to CompositingModeSourceOver. The code creates a SolidBrush object based on a color that has an alpha component of 128. The code passes the address of that brush to the FillRectangle method of the Graphics object to fill a rectangle with a color that is a half-and-half blend of the brush color and the background color. Then the code sets the compositing mode of the Graphics object to CompositingModeSourceCopy and fills a second rectangle with the same brush. In that second rectangle, the brush color is not blended with the background color.

VOID Example_SetCompositingMode(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object with an alpha-blended color.
   SolidBrush alphaBrush(Color(180, 255, 0, 0));

   // Set the compositing mode to CompositingModeSourceOver,
   // and fill a rectangle.
   graphics.SetCompositingMode(CompositingModeSourceOver);
   graphics.FillRectangle(&alphaBrush, 0, 0, 100, 100);

   // Set the compositing mode to CompositingModeSourceCopy,
   // and fill a rectangle.
   graphics.SetCompositingMode(CompositingModeSourceCopy);
   graphics.FillRectangle(&alphaBrush, 100, 0, 100, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
CompositingMode, GetCompositingMode, GetCompositingQuality, HatchBrush, SolidBrush, SetCompositingQuality, SetTextRenderingHint, TextRenderingHint
Tasks and Examples
Alpha Blending Lines and Fills
Concepts
New Features


Graphics::SetCompositingQuality(compositingQuality)

The SetCompositingQuality method sets the compositing quality of this Graphics object.

Status SetCompositingQuality(
  CompositingQuality compositingQuality
);

Parameters

compositingQuality
[in] Element of the CompositingQuality enumeration that specifies the compositing quality.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a SolidBrush object based on a color that has an alpha component of 128. The code uses that brush to paint two rectangles. The first rectangle is painted with the compositing mode set to CompositingQualityHighSpeed, and the second rectangle is painted with the compositing mode set to CompositingQualityHighQuality.

VOID Example_SetCompositingQuality(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a SolidBrush object with an alpha-blended color.
   SolidBrush alphaBrush(Color(180, 255, 0, 0));

   // Set the compositing mode to CompositingQualityHighSpeed,
   // and fill a rectangle.
   graphics.SetCompositingQuality(CompositingQualityHighSpeed);
   graphics.FillRectangle(&alphaBrush, 0, 0, 100, 100);

   // Set the compositing mode to CompositingQualityHighQuality,
   // and fill a rectangle.
   graphics.SetCompositingQuality(CompositingQualityHighQuality);
   graphics.FillRectangle(&alphaBrush, 100, 0, 100, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetCompositingMode, GetCompositingQuality, HatchBrush, SolidBrush, SetCompositingMode
Tasks and Examples
Alpha Blending Lines and Fills
Concepts
New Features


Graphics::SetInterpolationMode(interpolationMode)

The SetInterpolationMode method sets the interpolation mode of this Graphics object. The interpolation mode determines the algorithm that is used when images are scaled or rotated.

Status SetInterpolationMode(
  InterpolationMode interpolationMode
);

Parameters

interpolationMode
[in] Element of the InterpolationMode enumeration that specifies the interpolation mode.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetInterpolationMode, InterpolationMode
Tasks and Examples
Using Interpolation Mode to Control Image Quality During Scaling


Graphics::SetPageScale(scale)

The SetPageScale method sets the scaling factor for the page transformation of this Graphics object. The page transformation converts page coordinates to device coordinates.

Status SetPageScale(
  REAL scale
);

Parameters

scale
[in] Real number that specifies the scaling factor.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example sets the world transformation and the page transformation of a Graphics object. The page unit and the page scale both belong to the page transformation. The code sets the page unit to millimeters and sets the page scale to 10. The call to the DrawRectangle method draws a rectangle that has a width of 3 centimeters (UnitMillimeter along with a scaling factor of 10) and a height of 2 centimeters. The rectangle is translated 4 centimeters to the right and 1 centimeter down by the world transformation.

VOID Example_SetPageScale(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the world transformation.
   graphics.TranslateTransform(4.0f, 1.0f);

   // Set the page transformation.
   graphics.SetPageUnit(UnitMillimeter);
   graphics.SetPageScale(10.0f);

   Pen pen(Color(255, 0, 0, 0), 0.0f);
   graphics.DrawRectangle(&pen, 0, 0, 3, 2);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetDpiX, GetDpiY, GetPageScale, GetPageUnit, SetPageUnit, Unit
Concepts
Types of Coordinate Systems


Graphics::SetPageUnit(unit)

The SetPageUnit method sets the unit of measure for this Graphics object. The page unit belongs to the page transformation, which converts page coordinates to device coordinates.

Status SetPageUnit(
  Unit unit
);

Parameters

unit
[in] Element of the Unit enumeration that specifies the unit of measure for this Graphics object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example draws two rectangles: one measured in pixels and one measured in inches.

VOID Example_SetPageUnit(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the page units to pixels, and draw a rectangle.
   graphics.SetPageUnit(UnitPixel);
   Pen blackPen(Color(255, 0, 0, 0), 0.0f);
   graphics.DrawRectangle(&blackPen, 0, 0, 100, 100);

   // Set the page units to inches, and draw a rectangle.
   graphics.SetPageUnit(UnitInch);
   Pen bluePen(Color(255, 0, 0, 255), 0.0f);
   graphics.DrawRectangle(&bluePen, 2, 0, 1, 1);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetDpiX, GetDpiY, GetPageScale, GetPageUnit, SetPageScale, Unit
Concepts
Types of Coordinate Systems


Graphics::SetPixelOffsetMode(pixelOffsetMode)

The SetPixelOffsetMode method sets the pixel offset mode of this Graphics object.

Status SetPixelOffsetMode(
  PixelOffsetMode pixelOffsetMode
);

Parameters

pixelOffsetMode
[in] Element of the PixelOffsetMode enumeration that specifies the pixel offset mode.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
PixelOffsetMode


Graphics::SetRenderingOrigin(x, y)

The SetRenderingOrigin method sets the rendering origin of this Graphics object. The rendering origin is used to set the dither origin for 8-bits-per-pixel and 16-bits-per-pixel dithering and is also used to set the origin for hatch brushes.

Status SetRenderingOrigin(
  INT x,
  INT y
);

Parameters

x
[in] Integer that specifies the x-coordinate of the rendering origin.
y
[in] Integer that specifies the y-coordinate of the rendering origin.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example uses a hatch brush to fill two rectangles. The first rectangle is filled using the default rendering origin. The second rectangle is filled after the rendering origin is set to (3, 0).

VOID Example_SetRenderingOrigin(HDC hdc)
{
   Graphics graphics(hdc);

   HatchBrush hatchBrush(
      HatchStyleDiagonalCross,
      Color(255, 255, 0, 0),     // red
      Color(255, 0, 255, 255));  // aqua

   graphics.FillRectangle(&hatchBrush, 0, 0, 100, 50);
   graphics.SetRenderingOrigin(3, 0);
   graphics.FillRectangle(&hatchBrush, 0, 50, 100, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetRenderingOrigin


Graphics::SetSmoothingMode(smoothingMode)

The SetSmoothingMode method sets the render quality of the Graphics object.

Status SetSmoothingMode(
  SmoothingMode smoothingMode
);

Parameters

smoothingMode
[in] Element of the SmoothingMode enumeration that specifies whether smoothing (antialiasing) is applied to lines and curves.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

To get the rendering quality for text, use the GetTextRenderingHint method. The higher the level of quality of the smoothing mode, the slower the performance.

Example Code [C++]

The following example sets the smoothing mode to two different values and fills an ellipse to demonstrate each mode.

VOID Example_SetSetSmoothingMode(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the smoothing mode to SmoothingModeHighSpeed, and fill an ellipse.
   graphics.SetSmoothingMode(SmoothingModeHighSpeed);
   graphics.FillEllipse(&SolidBrush(Color(255, 0, 0, 0)), 0, 0, 200, 100);

   // Set the smoothing mode to SmoothingModeHighQuality, and fill an ellipse.
   graphics.SetSmoothingMode(SmoothingModeHighQuality);
   graphics.FillEllipse(&SolidBrush(Color(255, 0, 0, 0)), 200, 0, 200, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetSmoothingMode
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Antialiasing with Lines and Curves


Graphics::SetTextContrast(contrast)

The SetTextContrast method sets the contrast value of this Graphics object. The contrast value is used for antialiasing text.

Status SetTextContrast(
  UINT contrast
);

Parameters

contrast
[in] Integer that specifies the contrast value for antialiasing text.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.


Graphics::SetTextRenderingHint(newMode)

The SetTextRenderingHint method sets the text rendering mode of this Graphics object.

Status SetTextRenderingHint(
  TextRenderingHint newMode
);

Parameters

newMode
[in] Element of the TextRenderingHint enumeration that specifies the process currently used by this Graphics object to render text.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

TextRenderingHintClearTypeGridFit is supported only on Windows XP and Windows .NET Server.

You cannot use TextRenderingHintClearTypeGridFit along with CompositingModeSourceCopy.

Example Code [C++]

The following example sets the text rendering hint to two different values and draws text to demonstrate each value.

VOID Example_SetTextRenderingHint(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the text rendering hint to TextRenderingHintSingleBitPerPixel.
   graphics.SetTextRenderingHint(TextRenderingHintSingleBitPerPixel);

   // Draw text.
   graphics.DrawString(
   L"Low quality rendering",
       21,
   &Font(L"Arial", 24),
   PointF(0, 0),
   &SolidBrush(Color(255, 0, 0, 0)));

   // Get the text rendering hint.
   TextRenderingHint hint = graphics.GetTextRenderingHint();

   // Set the text rendering hint to TextRenderingHintAntiAlias.
   graphics.SetTextRenderingHint(TextRenderingHintAntiAlias);

   // Draw more text to demonstrate the difference.
   graphics.DrawString(
   L"High quality rendering",
       22,
   &Font(L"Arial", 24),
   PointF(0, 50),
   &SolidBrush(Color(255, 0, 0, 0)));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
CompositingMode, GetTextRenderingHint, SetCompositingMode, TextRenderingHint
Tasks and Examples
Antialiasing with Text


Graphics::SetTransform(matrix)

The SetTransform method sets the world transformation of this Graphics object.

Status SetTransform(
  const Matrix* matrix
);

Parameters

matrix
[in] Pointer to a Matrix object that specifies the world transformation.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a rotation matrix and passes the address of that matrix to the SetTransform method of a Graphics object. The code calls the DrawRectangle method of the Graphics object to draw a rotated rectangle.

VOID Example_SetTransform(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a rotation matrix.
   Matrix transformMatrix;
   transformMatrix.Rotate(45.0f);

   // Set the transformation matrix of the Graphics object.
   graphics.SetTransform(&transformMatrix);

   // Draw a rotated rectangle.
   Pen pen(Color(255, 0, 0, 0));
   graphics.DrawRectangle(&pen, 120, 0, 100, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, MultiplyTransform, ResetTransform, RotateTransform, ScaleTransform, TransformPoints, TranslateTransform
Tasks and Examples
Transformations
Concepts
Coordinate Systems and Transformations


Graphics::TransformPoints(destSpace, srcSpace, pts, count)

The TransformPoints method converts an array of points from one coordinate space to another. The conversion is based on the current world and page transformations of this Graphics object.

Status TransformPoints(
  CoordinateSpace destSpace,
  CoordinateSpace srcSpace,
  Point* pts,
  INT count
);

Parameters

destSpace
[in] Element of the CoordinateSpace enumeration that specifies the destination coordinate space.
srcSpace
[in] Element of the CoordinateSpace enumeration that specifies the source coordinate space.
pts
[in, out] Pointer to an array that, on input, holds the points to be converted and, on output, holds the converted points.
count
[in] Integer that specifies the number of elements in the pts array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The world transformation converts points from the world coordinate space to the page coordinate space. The page transformation converts points from the page coordinate space to the device coordinate space. For more information about coordinate spaces, see Types of Coordinate Systems.

Example Code [C++]

The following example creates a Graphics object and sets its world transformation to a translation 40 units right and 30 units down. Then the code creates an array of points and passes the address of that array to the TransformPoints method of the same Graphics object. The points in the array are transformed by the world transformation of the Graphics object. The code calls the DrawLine method twice: once to connect the two points before the transformation and once to connect the two points after the transformation.

VOID Example_TransformPoints(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   // Create an array of two Point objects.
   Point points[2] = {Point(0, 0), Point(100, 50)};

   // Draw a line that connects the two points.
   // No transformation has been performed yet.
   graphics.DrawLine(&pen, points[0], points[1]);

   // Set the world transformation of the Graphics object.
   graphics.TranslateTransform(40.0f, 30.0f);

   // Transform the points in the array from world to page coordinates.
   graphics.TransformPoints(
      CoordinateSpacePage,
      CoordinateSpaceWorld,
      points,
      2);

   // It is the world transformation that takes points from world
   // space to page space. Because the world transformation is a
   // translation 40 to the right and 30 down, the
   // points in the array are now (40, 30) and (140, 80).

   // Draw a line that connects the transformed points.
   graphics.ResetTransform();
   graphics.DrawLine(&pen, points[0], points[1]);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, MultiplyTransform, ResetTransform, RotateTransform, ScaleTransform, SetTransform, TranslateTransform
Tasks and Examples
Transformations
Concepts
Types of Coordinate Systems


Graphics::TranslateClip Methods

This topic lists the TranslateClip methods of the Graphics class. For a complete list of methods for the Graphics class, see Graphics Methods.

  • TranslateClip(INT dx, INT dy)
  • TranslateClip(REAL dx, REAL dy)


Graphics::TranslateClip(INT dx, INT dy)

The TranslateClip method translates the clipping region of this Graphics object.

Status TranslateClip(
  INT dx,
  INT dy
);

Parameters

dx
[in] Integer that specifies the horizontal component of the translation.
dy
[in] Integer that specifies the vertical component of the translation.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Graphics object and sets its clipping region. The code translates the clipping region 100 units to the right and then fills a large rectangle that is clipped by the translated region.

VOID Example_TranslateClipInt(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the clipping region.
   graphics.SetClip(Rect(0, 0, 100, 50));

   // Translate the clipping region.
   graphics.TranslateClip(40, 30);

   // Fill an ellipse that is clipped by the translated clipping region.
   SolidBrush brush(Color(255, 255, 0, 0));
   graphics.FillEllipse(&brush, 20, 40, 100, 80);

   // Draw the outline of the clipping region (rectangle).
   Pen pen(Color(255, 0, 0, 0), 2.0f);
   graphics.DrawRectangle(&pen, 40, 30, 100, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetClip, IntersectClip Methods, IsClipEmpty, SetClip Methods
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::TranslateClip(REAL dx, REAL dy)

The TranslateClip method translates the clipping region of this Graphics object.

Status TranslateClip(
  REAL dx,
  REAL dy
);

Parameters

dx
[in] Real number that specifies the horizontal component of the translation.
dy
[in] Real number that specifies the vertical component of the translation.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Graphics object and sets its clipping region. The code translates the clipping region 100 units to the right and then fills a large rectangle that is clipped by the translated region.

VOID Example_TranslateClipReal(HDC hdc)
{
   Graphics graphics(hdc);

   // Set the clipping region.
   graphics.SetClip(RectF(0.0f, 0.0f, 100.0f, 50.0f));

   // Translate the clipping region.
   graphics.TranslateClip(40.0f, 30.0f);

   // Fill an ellipse that is clipped by the translated clipping region.
   SolidBrush brush(Color(255, 255, 0, 0));
   graphics.FillEllipse(&brush, 20, 40, 100, 80);

   // Draw the outline of the clipping region (rectangle).
   Pen pen(Color(255, 0, 0, 0), 2.0f);
   graphics.DrawRectangle(&pen, 40, 30, 100, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetClip, IntersectClip Methods, IsClipEmpty, SetClip Methods
Tasks and Examples
Clipping with a Region
Concepts
Clipping


Graphics::TranslateTransform(dx, dy, order)

The TranslateTransform method updates this Graphics object's world transformation matrix with the product of itself and a translation matrix.

Status TranslateTransform(
  REAL dx,
  REAL dy,
  MatrixOrder order
);

Parameters

dx
[in] Real number that specifies the horizontal component of the translation.
dy
[in] Real number that specifies the vertical component of the translation.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of multiplication. MatrixOrderPrepend specifies that the translation matrix is on the left, and MatrixOrderAppend specifies that the translation matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example sets the world transformation of a Graphics object to a rotation. The call to TranslateTransform multiplies the Graphics object's existing world transformation matrix (rotation) by a translation matrix. The MatrixOrderAppend argument specifies that the multiplication is done with the translation matrix on the right. At that point, the world transformation matrix of the Graphics object represents a composite transformation: first rotate, then translate. The call to DrawEllipse draws a rotated and translated ellipse.

VOID Example_TranslateTransform(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   graphics.RotateTransform(30.0f);
   graphics.TranslateTransform(100.0f, 50.0f, MatrixOrderAppend);
   graphics.DrawEllipse(&pen, 0, 0, 200, 80);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusgraphics.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, ResetTransform, ScaleTransform, SetTransform, TransformPoints, TranslateTransform
Tasks and Examples
Transformations
Concepts
Coordinate Systems and Transformations


GraphicsPath Class

A GraphicsPath object stores a sequence of lines, curves, and shapes. You can draw the entire sequence by calling the DrawPath method of a Graphics object. You can partition the sequence of lines, curves, and shapes into figures, and with the help of a GraphicsPathIterator object, you can draw selected figures. You can also place markers in the sequence, so that you can draw selected portions of the path.

Inheritance

GdiplusBase
GraphicsPath

Constructors

Constructor | Description
GraphicsPath | Overloaded. Creates and initializes a new GraphicsPath object.

Methods

Method | Description
AddArc | Overloaded. Adds an elliptical arc to the current figure.
AddBezier | Overloaded. Adds a Bézier spline to the current figure.
AddBeziers | Overloaded. Adds a sequence of connected Bézier splines to the current figure.
AddClosedCurve | Overloaded. Adds a closed cardinal spline to the path.
AddCurve | Overloaded. Adds a cardinal spline to the current figure.
AddEllipse | Overloaded. Adds an ellipse to the path.
AddLine | Overloaded. Adds a line to the current figure.
AddLines | Overloaded. Adds a series of connected lines to the current figure.
AddPath | Adds a new path to the existing path.
AddPie | Overloaded. Adds a pie to the path.
AddPolygon | Overloaded. Adds a polygon to the path.
AddRectangle | Overloaded. Adds a rectangle to the path.
AddRectangles | Overloaded. Adds a sequence of rectangles to the path.
AddString | Overloaded. Adds the outline of a string to the path.
ClearMarkers | Clears the markers from the path.
Clone | Creates a new GraphicsPath object and initializes it with the contents of this GraphicsPath object.
CloseAllFigures | Closes all open figures in the path.
CloseFigure | Closes the current figure.
Flatten | Converts each curve in the path into a sequence of connected line segments.
GetBounds | Overloaded. Gets the bounding rectangle for the path.
GetFillMode | Gets the fill mode.
GetLastPoint | Gets the last point in the path.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetPathData | Gets the array of points and the array of point types that together define the path.
GetPathPoints | Overloaded. Gets the array of points stored by the GraphicsPath object.
GetPathTypes | Gets the array of point types stored by the GraphicsPath object.
GetPointCount | Gets the number of elements in the array of points stored by the GraphicsPath object.
IsOutlineVisible | Overloaded. Determines whether a point touches the path as it would be drawn by a specified pen.
IsVisible | Overloaded. Determines whether a point lies in the interior of the path.
Outline | Converts the path's data points so that they represent only the outline of the path.
Reset | Empties the path and sets the fill mode to FillModeAlternate.
Reverse | Reverses the order of the points in the path.
SetFillMode | Sets the fill mode.
SetMarker | Sets a marker.
StartFigure | Starts a new figure without closing the current figure.
Transform | Transforms the path's data points.
Warp | Flattens the path and applies a warp transformation to the path.
Widen | Flattens and widens the path.
~GraphicsPath | GraphicsPath object destructor.

Remarks

A path consists of one or more figures. As you add lines and curves to a path, those lines and curves become part of a figure. You can start a new figure by calling the StartFigure method. When you draw a path, the lines and curves within an individual figure are connected by straight lines; the ending point of one line or curve is connected to the starting point of the next line or curve. No connecting line is drawn between the end of one figure and the start of the next figure.

A figure can be open or closed. You can close a figure by calling the CloseFigure method. After you call CloseFigure, the next line, curve, or shape that you add to the path is part of the next figure. When you draw a path, the ending point of each closed figure is automatically connected to the starting point of that figure.

Some shapes (for example, rectangles and ellipses) are intrinsically closed. When you add an intrinsically closed shape to a path, that shape is in a figure by itself, and that figure is considered closed even if you don't call CloseFigure. The following methods add intrinsically closed figures to a path:

  • AddClosedCurve
  • AddEllipse
  • AddPie
  • AddPolygon
  • AddRectangle
  • AddRectangles
  • AddString


GraphicsPath Constructors

This topic lists the constructors of the GraphicsPath class. For a complete class listing, see GraphicsPath Class.

  • GraphicsPath(fillMode)
  • GraphicsPath(Point* points, BYTE* types, INT count, FillMode fillMode)
  • GraphicsPath(PointF* points, BYTE* types, INT count, FillMode fillMode)


GraphicsPath::GraphicsPath(fillMode)

Creates a GraphicsPath object and initializes the fill mode. This is the default constructor.

GraphicsPath(
  FillMode fillMode
);

Parameters

fillMode
[in] Optional. Element of the FillMode enumeration that specifies how areas are filled if the path intersects itself. The default value is FillModeAlternate.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
FillMode, GraphicsPath Constructors, PathGradientBrush
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::GraphicsPath(Point* points, BYTE* types, INT count, FillMode fillMode)

Creates a GraphicsPath object based on an array of points, an array of types, and a fill mode.

GraphicsPath(
  const Point* points,
  const BYTE* types,
  INT count,
  FillMode fillMode
);

Parameters

points
[in] Pointer to an array of points that specifies the endpoints and control points of the lines and Bézier splines that are used to draw the path.
types
[in] Pointer to an array of bytes that holds the point type and a set of flags for each point in the points array. The point type is stored in the three least significant bits, and the flags are stored in the four most significant bits. Possible point types and flags are listed in the PathPointType enumeration.
count
[in] Integer that specifies the number of elements in the points array. This is the same as the number of elements in the types array.
fillMode
[in] Optional. Element of the FillMode enumeration that specifies how areas are filled if the path intersects itself. The default value is FillModeAlternate.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
FillMode, GraphicsPath Constructors, PathData, PathGradientBrush, PathPointType, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::GraphicsPath(PointF* points, BYTE* types, INT count, FillMode fillMode)

Creates a GraphicsPath object based on an array of points, an array of types, and a fill mode.

GraphicsPath(
  const PointF* points,
  const BYTE* types,
  INT count,
  FillMode fillMode
);

Parameters

points
[in] Pointer to an array of points that specifies the endpoints and control points of the lines and Bézier splines that are used to draw the path.
types
[in] Pointer to an array of bytes that holds the point type and a set of flags for each point in the points array. The point type is stored in the three least significant bits, and the flags are stored in the four most significant bits. Possible point types and flags are listed in the PathPointType enumeration.
count
[in] Integer that specifies the number of elements in the points array. This is the same as the number of elements in the types array.
fillMode
[in] Optional. Element of the FillMode enumeration that specifies how areas are filled if the path intersects itself. The default value is FillModeAlternate.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
FillMode, GraphicsPath Constructors, PathData, PathGradientBrush, PathPointType, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath Methods

This topic lists the methods of the GraphicsPath class. For a complete class listing, see GraphicsPath Class.

  • AddArc(Rect& rect, REAL startAngle, REAL sweepAngle)
  • AddArc(RectF& rect, REAL startAngle, REAL sweepAngle)
  • AddArc(INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
  • AddArc(REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)
  • AddBezier(Point& pt1, Point& pt2, Point& pt3, Point& pt4)
  • AddBezier(PointF& pt1, PointF& pt2, PointF& pt3, PointF& pt4)
  • AddBezier(INT x1, INT y1, INT x2, INT y2, INT x3, INT y3, INT x4, INT y4)
  • AddBezier(REAL x1, REAL y1, REAL x2, REAL y2, REAL x3, REAL y3, REAL x4, REAL y4)
  • AddBeziers(Point* points, INT count)
  • AddBeziers(PointF* points, INT count)
  • AddClosedCurve(Point* points, INT count)
  • AddClosedCurve(PointF* points, INT count)
  • AddClosedCurve(Point* points, INT count, REAL tension)
  • AddClosedCurve(PointF* points, INT count, REAL tension)
  • AddCurve(Point* points, INT count)
  • AddCurve(Point* points, INT count, INT offset, INT numberOfSegments, REAL tension)
  • AddCurve(Point* points, INT count, REAL tension)
  • AddCurve(PointF* points, INT count)
  • AddCurve(PointF* points, INT count, INT offset, INT numberOfSegments, REAL tension)
  • AddCurve(PointF* points, INT count, REAL tension)
  • AddEllipse(Rect& rect)
  • AddEllipse(RectF& rect)
  • AddEllipse(INT x, INT y, INT width, INT height)
  • AddEllipse(REAL x, REAL y, REAL width, REAL height)
  • AddLine(Point& pt1, Point& pt2)
  • AddLine(PointF& pt1, PointF& pt2)
  • AddLine(INT x1, INT y1, INT x2, INT y2)
  • AddLine(REAL x1, REAL y1, REAL x2, REAL y2)
  • AddLines(Point* points, INT count)
  • AddLines(PointF* points, INT count)
  • AddPath(addingPath, connect)
  • AddPie(Rect& rect, REAL startAngle, REAL sweepAngle)
  • AddPie(RectF& rect, REAL startAngle, REAL sweepAngle)
  • AddPie(INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
  • AddPie(REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)
  • AddPolygon(Point* points, INT count)
  • AddPolygon(PointF* points, INT count)
  • AddRectangle(Rect& rect)
  • AddRectangle(RectF& rect)
  • AddRectangles(Rect* rects, INT count)
  • AddRectangles(RectF* rects, INT count)
  • AddString(WCHAR* string, INT length, FontFamily* family, INT style, REAL emSize, Rect& layoutRect, StringFormat* format)
  • AddString(WCHAR* string, INT length, FontFamily* family, INT style, REAL emSize, RectF& layoutRect, StringFormat* format)
  • AddString(WCHAR* string, INT length, FontFamily* family, INT style, REAL emSize, Point& origin, StringFormat* format)
  • AddString(WCHAR* string, INT length, FontFamily* family, INT style, REAL emSize, PointF& origin, StringFormat* format)
  • ClearMarkers()
  • Clone()
  • CloseAllFigures()
  • CloseFigure()
  • Flatten(matrix, flatness)
  • GetBounds(Rect* bounds, Matrix* matrix, Pen* pen)
  • GetBounds(RectF* bounds, Matrix* matrix, Pen* pen)
  • GetFillMode()
  • GetLastPoint(lastPoint)
  • GetLastStatus()
  • GetPathData(pathData)
  • GetPathPoints(Point* points, INT count)
  • GetPathPoints(PointF* points, INT count)
  • GetPathTypes(types, count)
  • GetPointCount()
  • IsOutlineVisible(Point& point, Pen* pen, Graphics* g)
  • IsOutlineVisible(PointF& point, Pen* pen, Graphics* g)
  • IsOutlineVisible(INT x, INT y, Pen* pen, Graphics* g)
  • IsOutlineVisible(REAL x, REAL y, Pen* pen, Graphics* g)
  • IsVisible(Point& point, Graphics* g)
  • IsVisible(PointF& point, Graphics* g)
  • IsVisible(INT x, INT y, Graphics* g)
  • IsVisible(REAL x, REAL y, Graphics* g)
  • Reset()
  • Reverse()
  • SetFillMode(fillmode)
  • SetMarker()
  • StartFigure()
  • Transform(matrix)
  • Warp(destPoints, count, srcRect, matrix, warpMode, flatness)
  • Widen(pen, matrix, flatness)


GraphicsPath::AddArc Methods

This topic lists the AddArc methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • AddArc(Rect& rect, REAL startAngle, REAL sweepAngle)
  • AddArc(RectF& rect, REAL startAngle, REAL sweepAngle)
  • AddArc(INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
  • AddArc(REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)


GraphicsPath::AddArc(Rect& rect, REAL startAngle, REAL sweepAngle)

The AddArc method adds an elliptical arc to the current figure of this path.

Status AddArc(
  const Rect& rect,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

rect
[in] Reference to a rectangle that bounds the ellipse that contains the arc.
startAngle
[in] Real number that specifies the clockwise angle, in degrees, between the horizontal axis of the ellipse and the starting point of the arc.
sweepAngle
[in] Real number that specifies the clockwise angle, in degrees, between the starting point (startAngle) and the ending point of the arc.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds an arc to path, closes the arc, and then draws path.

VOID AddArcExample(HDC hdc)
{
   Graphics graphics(hdc);
   Rect rect(20, 20, 50, 100);

   GraphicsPath path;
   path.AddArc(rect, 0.0f, 180.0f);
   path.CloseFigure();

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddArc Methods, DrawArc Methods, Rect
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Ellipses and Arcs, Paths


GraphicsPath::AddArc(RectF& rect, REAL startAngle, REAL sweepAngle)

The AddArc method adds an elliptical arc to the current figure of this path.

Status AddArc(
  const RectF& rect,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

rect
[in] Reference to a rectangle that bounds the ellipse that contains the arc.
startAngle
[in] Real number that specifies the clockwise angle, in degrees, between the horizontal axis of the ellipse and the starting point of the arc.
sweepAngle
[in] Real number that specifies the clockwise angle, in degrees, between the starting point (startAngle) and the ending point of the arc.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds an arc to path, closes the arc, and then draws path.

VOID AddArcExample(HDC hdc)
{
   Graphics graphics(hdc);
   RectF rect(20.0f, 20.0f, 50.0f, 100.0f);

   GraphicsPath path;
   path.AddArc(rect, 0.0f, 180.0f);
   path.CloseFigure();

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddArc Methods, DrawArc Methods, RectF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Ellipses and Arcs, Paths


GraphicsPath::AddArc(INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)

The AddArc method adds an elliptical arc to the current figure of this path.

Status AddArc(
  INT x,
  INT y,
  INT width,
  INT height,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

x
[in] Integer that specifies the x-coordinate of the upper-left corner of the bounding rectangle for the ellipse that contains the arc.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the bounding rectangle for the ellipse that contains the arc.
width
[in] Integer that specifies the width of the bounding rectangle for the ellipse that contains the arc.
height
[in] Integer that specifies the height of the bounding rectangle for the ellipse that contains the arc.
startAngle
[in] Real number that specifies the clockwise angle, in degrees, between the horizontal axis of the ellipse and the starting point of the arc.
sweepAngle
[in] Real number that specifies the clockwise angle, in degrees, between the starting point (startAngle) and ending point of the arc.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds an arc to path, closes the arc, and then draws path.

VOID AddArcExample2(HDC hdc)
{
   Graphics graphics(hdc);

   GraphicsPath path;
   path.AddArc(20, 20, 50, 100, 0.0f, 180.0f);
   path.CloseFigure();

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddArc Methods, DrawArc Methods
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Ellipses and Arcs, Paths


GraphicsPath::AddArc(REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)

The AddArc method adds an elliptical arc to the current figure of this path.

Status AddArc(
  REAL x,
  REAL y,
  REAL width,
  REAL height,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

x
[in] Real number that specifies the x-coordinate of the upper-left corner of the bounding rectangle for the ellipse that contains the arc.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the bounding rectangle for the ellipse that contains the arc.
width
[in] Real number that specifies the width of the bounding rectangle for the ellipse that contains the arc.
height
[in] Real number that specifies the height of the bounding rectangle for the ellipse that contains the arc.
startAngle
[in] Real number that specifies the clockwise angle, in degrees, between the horizontal axis of the ellipse and the starting point of the arc.
sweepAngle
[in] Real number that specifies the clockwise angle, in degrees, between the starting point (startAngle) and the ending point of the arc.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds an arc to path, closes the arc, and then draws path.

VOID AddArcExample2(HDC hdc)
{
   Graphics graphics(hdc);

   GraphicsPath path;
   path.AddArc(20.0f, 20.0f, 50.0f, 100.0f, 0.0f, 180.0f);
   path.CloseFigure();

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddArc Methods, DrawArc Methods
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Ellipses and Arcs, Paths


GraphicsPath::AddBezier Methods

This topic lists the AddBezier methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • AddBezier(Point& pt1, Point& pt2, Point& pt3, Point& pt4)
  • AddBezier(PointF& pt1, PointF& pt2, PointF& pt3, PointF& pt4)
  • AddBezier(INT x1, INT y1, INT x2, INT y2, INT x3, INT y3, INT x4, INT y4)
  • AddBezier(REAL x1, REAL y1, REAL x2, REAL y2, REAL x3, REAL y3, REAL x4, REAL y4)


GraphicsPath::AddBezier(Point& pt1, Point& pt2, Point& pt3, Point& pt4)

The AddBezier method adds a Bézier spline to the current figure of this path.

Status AddBezier(
  const Point& pt1,
  const Point& pt2,
  const Point& pt3,
  const Point& pt4
);

Parameters

pt1
[in] Reference to a point at which to start the Bézier spline.
pt2
[in] Reference to a point that is the first control point of the Bézier spline.
pt3
[in] Reference to a point that is the second control point of the Bézier spline.
pt4
[in] Reference to a point at which to end the Bézier spline.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a Bézier spline to path, closes the current figure (the only figure in this case), and then draws path.

VOID Example_AddBezier(HDC hdc)
{
   Graphics graphics(hdc);
   GraphicsPath  path;

   Point pt1(50, 50);
   Point pt2(60, 20);
   Point pt3(70, 100);
   Point pt4(80, 50);

   path.AddBezier(pt1, pt2, pt3, pt4);
   path.CloseFigure();

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddCurve Methods, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Bézier Splines
Concepts
Bézier Splines, Paths


GraphicsPath::AddBezier(PointF& pt1, PointF& pt2, PointF& pt3, PointF& pt4)

The AddBezier method adds a Bézier spline to the current figure of this path.

Status AddBezier(
  const PointF& pt1,
  const PointF& pt2,
  const PointF& pt3,
  const PointF& pt4
);

Parameters

pt1
[in] Reference to a point at which to start the Bézier spline.
pt2
[in] Reference to a point that is the first control point of the Bézier spline.
pt3
[in] Reference to a point that is the second control point of the Bézier spline.
pt4
[in] Reference to a point at which to end the Bézier spline.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a Bézier spline to path, closes the current figure (the only figure in this case), and then draws path.

VOID Example_AddBezier(HDC hdc)
{
   Graphics graphics(hdc);
   GraphicsPath  path;

   PointF pt1(50.0f, 50.0f);
   PointF pt2(60.0f, 20.0f);
   PointF pt3(70.0f, 100.0f);
   PointF pt4(80.0f, 50.0f);

   path.AddBezier(pt1, pt2, pt3, pt4);
   path.CloseFigure();

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddCurve Methods, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Bézier Splines
Concepts
Bézier Splines, Paths


GraphicsPath::AddBezier(INT x1, INT y1, INT x2, INT y2, INT x3, INT y3, INT x4, INT y4)

The AddBezier method adds a Bézier spline to the current figure of this path.

Status AddBezier(
  INT x1,
  INT y1,
  INT x2,
  INT y2,
  INT x3,
  INT y3,
  INT x4,
  INT y4
);

Parameters

x1
[in] Integer that specifies the x-coordinate of the starting point of the Bézier spline.
y1
[in] Integer that specifies the y-coordinate of the starting point of the Bézier spline.
x2
[in] Integer that specifies the x-coordinate of the first control point of the Bézier spline.
y2
[in] Integer that specifies the y-coordinate of the first control point of the Bézier spline.
x3
[in] Integer that specifies the x-coordinate of the second control point of the Bézier spline.
y3
[in] Integer that specifies the y-coordinate of the second control point of the Bézier spline.
x4
[in] Integer that specifies the x-coordinate of the ending point of the Bézier spline.
y4
[in] Integer that specifies the y-coordinate of the ending point of the Bézier spline.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a Bézier spline to path, closes the current figure (the only figure in this case), and then draws path.

VOID Example_AddBezier(HDC hdc)
{
   Graphics graphics(hdc);
   GraphicsPath  path;

   path.AddBezier(50, 50, 60, 20, 70, 100, 80, 50);
   path.CloseFigure();

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddCurve Methods
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Bézier Splines
Concepts
Bézier Splines, Paths


GraphicsPath::AddBezier(REAL x1, REAL y1, REAL x2, REAL y2, REAL x3, REAL y3, REAL x4, REAL y4)

The AddBezier method adds a Bézier spline to the current figure of this path.

Status AddBezier(
  REAL x1,
  REAL y1,
  REAL x2,
  REAL y2,
  REAL x3,
  REAL y3,
  REAL x4,
  REAL y4
);

Parameters

x1
[in] Real number that specifies the x-coordinate of the starting point of the Bézier spline.
y1
[in] Real number that specifies the y-coordinate of the starting point of the Bézier spline.
x2
[in] Real number that specifies the x-coordinate of the first control point of the Bézier spline.
y2
[in] Real number that specifies the y-coordinate of the first control point of the Bézier spline.
x3
[in] Real number that specifies the x-coordinate of the second control point of the Bézier spline.
y3
[in] Real number that specifies the y-coordinate of the second control point of the Bézier spline.
x4
[in] Real number that specifies the x-coordinate of the ending point of the Bézier spline.
y4
[in] Real number that specifies the y-coordinate of the ending point of the Bézier spline.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a Bézier spline to path, closes the current figure (the only figure in this case), and then draws path.

VOID Example_AddBezier(HDC hdc)
{
   Graphics graphics(hdc);
   GraphicsPath  path;

   path.AddBezier(50.0f, 50.0f, 60.0f, 20.0f, 70.0f, 100.0f, 80.0f, 50.0f);
   path.CloseFigure();

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddCurve Methods
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Bézier Splines
Concepts
Bézier Splines, Paths


GraphicsPath::AddBeziers Methods

This topic lists the AddBeziers methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • AddBeziers(Point* points, INT count)
  • AddBeziers(PointF* points, INT count)


GraphicsPath::AddBeziers(Point* points, INT count)

The AddBeziers method adds a sequence of connected Bézier splines to the current figure of this path.

Status AddBeziers(
  const Point* points,
  INT count
);

Parameters

points
[in] Pointer to an array of starting points, ending points, and control points for the connected splines. The first spline is constructed from the first point through the fourth point in the array and uses the second and third points as control points. Each subsequent spline in the sequence needs exactly three more points: the ending point of the previous spline is used as the starting point, the next two points in the sequence are control points, and the third point is the ending point.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a sequence of two connected Bézier splines to path, closes the current figure (the only figure in this case), and then draws path.

VOID Example_AddBeziers(HDC hdc)
{
   Graphics graphics(hdc);
   GraphicsPath  path;

   Point pts[] = {Point(50,50),
                  Point(60,20),
                  Point(70,100),
                  Point(80,50),
                  Point(120,40),
                  Point(150,80),
                  Point(170,30)};

   path.AddBeziers(pts, 7);
   path.CloseFigure();

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddCurve Methods, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Bézier Splines
Concepts
Bézier Splines, Paths


GraphicsPath::AddBeziers(PointF* points, INT count)

The AddBeziers method adds a sequence of connected Bézier splines to the current figure of this path.

Status AddBeziers(
  const PointF* points,
  INT count
);

Parameters

points
[in] Pointer to an array of starting points, ending points, and control points for the connected splines. The first spline is constructed from the first point through the fourth point in the array and uses the second and third points as control points. Each subsequent spline in the sequence needs exactly three more points: the ending point of the previous spline is used as the starting point, the next two points in the sequence are control points, and the third point is the ending point.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a sequence of connected Bézier splines to path, closes the current figure (the only figure in this case), and then draws path.

VOID Example_AddBeziers(HDC hdc)
{
   Graphics graphics(hdc);
   GraphicsPath  path;

   PointF pts[] = {PointF(50.0f,50.0f),
                   PointF(60.0f,20.0f),
                   PointF(70.0f,100.0f),
                   PointF(80.0f,50.0f),
                   PointF(120.0f,40.0f),
                   PointF(150.0f,80.0f),
                   PointF(170.0f,30.0f)};

   path.AddBeziers(pts, 7);
   path.CloseFigure();

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddCurve Methods, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Bézier Splines
Concepts
Bézier Splines, Paths


GraphicsPath::AddClosedCurve Methods

This topic lists the AddClosedCurve methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • AddClosedCurve(Point* points, INT count)
  • AddClosedCurve(PointF* points, INT count)
  • AddClosedCurve(Point* points, INT count, REAL tension)
  • AddClosedCurve(PointF* points, INT count, REAL tension)


GraphicsPath::AddClosedCurve(Point* points, INT count)

The AddClosedCurve method adds a closed cardinal spline to this path.

Status AddClosedCurve(
  const Point* points,
  INT count
);

Parameters

points
[in] Pointer to an array of points that define the cardinal spline. The cardinal spline is a curve that passes through each point in the array.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

You should keep a copy of the points array if those points will be needed later. The GraphicsPath object does not store the points passed to the AddClosedCurve method; instead, it converts the cardinal spline to a sequence of Bézier splines and stores the points that define those Bézier splines. You cannot retrieve the original array of points from the GraphicsPath object.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a closed cardinal spline to path, and then draws path.

VOID Example_AddClosedCurve(HDC hdc)
{
   Graphics graphics(hdc);

   Point pts[] = {Point(50,50),
                  Point(60,20),
                  Point(70,100),
                  Point(80,50)};

   GraphicsPath path;
   path.AddClosedCurve(pts, 4);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddClosedCurve Methods, AddCurve Methods, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Cardinal Splines
Concepts
Cardinal Splines, Paths


GraphicsPath::AddClosedCurve(PointF* points, INT count)

The AddClosedCurve method adds a closed cardinal spline to this path.

Status AddClosedCurve(
  const PointF* points,
  INT count
);

Parameters

points
[in] Pointer to an array of points that define the cardinal spline. The cardinal spline is a curve that passes through each point in the array.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

You should keep a copy of the points array if those points will be needed later. The GraphicsPath object does not store the points passed to the AddClosedCurve method; instead, it converts the cardinal spline to a sequence of Bézier splines and stores the points that define those Bézier splines. You cannot retrieve the original array of points from the GraphicsPath object.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a closed cardinal spline to path, and then draws path.

VOID Example_AddClosedCurve(HDC hdc)
{
   Graphics graphics(hdc);

   PointF pts[] = {PointF(50.0f,50.0f),
                   PointF(60.0f,20.0f),
                   PointF(70.0f,100.0f),
                   PointF(80.0f,50.0f)};

   GraphicsPath path;
   path.AddClosedCurve(pts, 4);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddClosedCurve Methods, AddCurve Methods, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Cardinal Splines
Concepts
Cardinal Splines, Paths


GraphicsPath::AddClosedCurve(Point* points, INT count, REAL tension)

The AddClosedCurve method adds a closed cardinal spline to this path.

Status AddClosedCurve(
  const Point* points,
  INT count,
  REAL tension
);

Parameters

points
[in] Pointer to an array of points that define the cardinal spline. The cardinal spline is a curve that passes through each point in the array.
count
[in] Integer that specifies the number of elements in the points array.
tension
[in] Nonnegative real number that controls the length of the curve and how the curve bends. A value of 0 specifies that the spline is a sequence of straight lines. As the value increases, the curve becomes fuller.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

You should keep a copy of the points array if those points will be needed later. The GraphicsPath object does not store the points passed to the AddClosedCurve method; instead, it converts the cardinal spline to a sequence of Bézier splines and stores the points that define those Bézier splines. You cannot retrieve the original array of points from the GraphicsPath object.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a closed cardinal spline to path, and then draws path. The tension is set to 1.0.

VOID Example_AddClosedCurve(HDC hdc)
{
   Graphics graphics(hdc);

   Point pts[] = {Point(50,50),
                  Point(60,20),
                  Point(70,100),
                  Point(80,50)};

   GraphicsPath path;
   path.AddClosedCurve(pts, 4, 1.0f);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddClosedCurve Methods, AddCurve Methods, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Cardinal Splines
Concepts
Cardinal Splines, Paths


GraphicsPath::AddClosedCurve(PointF* points, INT count, REAL tension)

The AddClosedCurve method adds a closed cardinal spline to this path.

Status AddClosedCurve(
  const PointF* points,
  INT count,
  REAL tension
);

Parameters

points
[in] Pointer to an array of points that define the cardinal spline. The cardinal spline is a curve that passes through each point in the array.
count
[in] Integer that specifies the number of elements in the points array.
tension
[in] Nonnegative real number that controls the length of the curve and how the curve bends. A value of 0 specifies that the spline is a sequence of straight line segments. As the value increases, the curve becomes fuller.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

You should keep a copy of the points array if those points will be needed later. The GraphicsPath object does not store the points passed to the AddClosedCurve method; instead, it converts the cardinal spline to a sequence of Bézier splines and stores the points that define those Bézier splines. You cannot retrieve the original array of points from the GraphicsPath object.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a closed cardinal spline to path, and then draws path. The tension is set to 1.0.

VOID Example_AddClosedCurve(HDC hdc)
{
   Graphics graphics(hdc);

   PointF pts[] = {PointF(50.0f,50.0f),
                   PointF(60.0f,20.0f),
                   PointF(70.0f,100.0f),
                   PointF(80.0f,50.0f)};

   GraphicsPath path;
   path.AddClosedCurve(pts, 4, 1.0f);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddClosedCurve Methods, AddCurve Methods, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Cardinal Splines
Concepts
Cardinal Splines, Paths


GraphicsPath::AddCurve Methods

This topic lists the AddCurve methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • AddCurve(Point* points, INT count)
  • AddCurve(PointF* points, INT count)
  • AddCurve(Point* points, INT count, INT offset, INT numberOfSegments, REAL tension)
  • AddCurve(PointF* points, INT count, INT offset, INT numberOfSegments, REAL tension)
  • AddCurve(Point* points, INT count, REAL tension)
  • AddCurve(PointF* points, INT count, REAL tension)


GraphicsPath::AddCurve(Point* points, INT count)

The AddCurve method adds a cardinal spline to the current figure of this path.

Status AddCurve(
  const Point* points,
  INT count
);

Parameters

points
[in] Pointer to an array of points that define the cardinal spline. The cardinal spline is a curve that passes through each point in the array.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

You should keep a copy of the points array if those points will be needed later. The GraphicsPath object does not store the points passed to the AddClosedCurve method; instead, it converts the cardinal spline to a sequence of Bézier splines and stores the points that define those Bézier splines. You cannot retrieve the original array of points from the GraphicsPath object.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a cardinal spline to path, and then draws path.

VOID AddCurveExample(HDC hdc)
{
   Graphics graphics(hdc);

   Point pts[] = {Point(50,50),
                  Point(60,20),
                  Point(70,100),
                  Point(80,50)};

   GraphicsPath path;
   path.AddCurve(pts, 4);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddClosedCurve Methods, AddCurve Methods, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Cardinal Splines
Concepts
Cardinal Splines, Paths


GraphicsPath::AddCurve(PointF* points, INT count)

The AddCurve method adds a cardinal spline to the current figure of this path.

Status AddCurve(
  const PointF* points,
  INT count
);

Parameters

points
[in] Pointer to an array of points that define the cardinal spline. The cardinal spline is a curve that passes through each point in the array.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

You should keep a copy of the points array if those points will be needed later. The GraphicsPath object does not store the points passed to the AddClosedCurve method; instead, it converts the cardinal spline to a sequence of Bézier splines and stores the points that define those Bézier splines. You cannot retrieve the original array of points from the GraphicsPath object.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a cardinal spline to path, and then draws path.

VOID AddCurveExample(HDC hdc)
{
   Graphics graphics(hdc);

   PointF pts[] = {PointF(50.0f, 50.0f),
                   PointF(60.0f, 20.0f),
                   PointF(70.0f, 100.0f),
                   PointF(80.0f, 50.0f)};

   GraphicsPath path;
   path.AddCurve(pts, 4);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddClosedCurve Methods, AddCurve Methods, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Cardinal Splines
Concepts
Cardinal Splines, Paths


GraphicsPath::AddCurve(Point* points, INT count, INT offset, INT numberOfSegments, REAL tension)

The AddCurve method adds a cardinal spline to the current figure of this path.

Status AddCurve(
  const Point* points,
  INT count,
  INT offset,
  INT numberOfSegments,
  REAL tension
);

Parameters

points
[in] Pointer to an array of points that define the cardinal spline. The cardinal spline is a curve that passes through a subset (specified by the offset and numberOfSegments parameters) of the points in the array.
count
[in] Integer that specifies the number of elements in the points array.
offset
[in] Integer that specifies the index of the array element that is used as the first point of the cardinal spline.
numberOfSegments
[in] Integer that specifies the number of segments in the cardinal spline. Segments are the curves that connect consecutive points in the array.
tension
[in] Nonnegative real number that controls the length of the curve and how the curve bends. A value of 0 specifies that the spline is a sequence of straight line segments. As the value increases, the curve becomes fuller.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

You should keep a copy of the points array if those points will be needed later. The GraphicsPath object does not store the points passed to the AddClosedCurve method; instead, it converts the cardinal spline to a sequence of Bézier splines and stores the points that define those Bézier splines. You cannot retrieve the original array of points from the GraphicsPath object.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a cardinal spline to path, and then draws path. The spline is built from the points indexed 2 through 6 in an array of eight points.

VOID AddCurveExample2(HDC hdc)
{
   GraphicsPath   path;
   Graphics graphics(hdc);

   Point pts[] = {Point(50, 50),
                  Point(70, 80),
                  Point(100, 100),
                  Point(130, 40),
                  Point(150, 90),
                  Point(180, 30),
                  Point(210, 120),
                  Point(240, 80)};

   path.AddCurve(
      pts,
      8,     // There are eight points in the array.
      2,     // Start at the point with index 2.
      4,     // Four segments. End at the point with index 6.
      1.0f);

   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawPath(&pen, &path);

   // Draw all eight points in the array.
   SolidBrush brush(Color(255, 255, 0, 0));
   for(INT j = 0; j <= 7; ++j)
      graphics.FillEllipse(&brush, pts[j].X - 3, pts[j].Y - 3, 6, 6);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddClosedCurve Methods, AddCurve Methods, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Cardinal Splines
Concepts
Cardinal Splines, Paths


GraphicsPath::AddCurve(PointF* points, INT count, INT offset, INT numberOfSegments, REAL tension)

The AddCurve method adds a cardinal spline to the current figure of this path.

Status AddCurve(
  const PointF* points,
  INT count,
  INT offset,
  INT numberOfSegments,
  REAL tension
);

Parameters

points
[in] Pointer to an array of points that define the cardinal spline. The cardinal spline is a curve that passes through a subset (specified by the offset and numberOfSegments parameters) of the points in the array.
count
[in] Integer that specifies the number of elements in the points array.
offset
[in] Integer that specifies the index of the array element that is used as the first point of the cardinal spline.
numberOfSegments
[in] Integer that specifies the number of segments in the cardinal spline. Segments are the curves that connect consecutive points in the array.
tension
[in] Nonnegative real number that controls the length of the curve and how the curve bends. A value of 0 specifies that the spline is a sequence of straight line segments. As the value increases, the curve becomes fuller.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

You should keep a copy of the points array if those points will be needed later. The GraphicsPath object does not store the points passed to the AddClosedCurve method; instead, it converts the cardinal spline to a sequence of Bézier splines and stores the points that define those Bézier splines. You cannot retrieve the original array of points from the GraphicsPath object.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a cardinal spline to path, and then draws path. The spline is built from the points indexed 2 through 6 in an array of eight points.

VOID AddCurveExample3(HDC hdc)
{
   Graphics graphics(hdc);
   GraphicsPath path;

   PointF pts[] = {PointF(50.0f, 50.0f),
                  PointF(70.0f, 80.0f),
                  PointF(100.0f, 100.0f),
                  PointF(130.0f, 40.0f),
                  PointF(150.0f, 90.0f),
                  PointF(180.0f, 30.0f),
                  PointF(210.0f, 120.0f),
                  PointF(240.0f, 80.0f)};

   path.AddCurve(
      pts,
      8,     // There are eight points in the array.
      2,     // Start at the point with index 2.
      4,     // Four segments. End at the point with index 6.
      1.0f);

   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawPath(&pen, &path);

   // Draw all eight points in the array.
   SolidBrush brush(Color(255, 255, 0, 0));
   for(INT j = 0; j <= 7; ++j)
      graphics.FillEllipse(&brush, pts[j].X - 3.0f, pts[j].Y - 3.0f, 6.0f, 6.0f);
}

Color(255, 255, 0,  0)

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddClosedCurve Methods, AddCurve Methods, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Cardinal Splines
Concepts
Cardinal Splines, Paths


GraphicsPath::AddCurve(Point* points, INT count, REAL tension)

The AddCurve method adds a cardinal spline to the current figure of this path.

Status AddCurve(
  const Point* points,
  INT count,
  REAL tension
);

Parameters

points
[in] Pointer to an array of points that define the cardinal spline. The cardinal spline is a curve that passes through each point in the array.
count
[in] Integer that specifies the number of elements in the points array.
tension
[in] Nonnegative real number that controls the length of the curve and how the curve bends. A value of 0 specifies that the spline is a sequence of straight line segments. As the value increases, the curve becomes fuller.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

You should keep a copy of the points array if those points will be needed later. The GraphicsPath object does not store the points passed to the AddClosedCurve method; instead, it converts the cardinal spline to a sequence of Bézier splines and stores the points that define those Bézier splines. You cannot retrieve the original array of points from the GraphicsPath object.

Example Code [C++]

The following example creates a GraphicsPath object and calls the AddCurve method to add a cardinal spline to the path. The third argument passed to AddCurve specifies the tension for the cardinal spline.

VOID AddCurveExample(HDC hdc)
{
   Graphics graphics(hdc);

   Point pts[] = {Point(50, 50),
                  Point(60, 20),
                  Point(70, 100),
                  Point(80, 50)};

   GraphicsPath path;
   path.AddCurve(pts, 4);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Color(255, 255, 0,  0)

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddClosedCurve Methods, AddCurve Methods, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Cardinal Splines
Concepts
Cardinal Splines, Paths


GraphicsPath::AddCurve(PointF* points, INT count, REAL tension)

The AddCurve method adds a cardinal spline to the current figure of this path.

Status AddCurve(
  const PointF* points,
  INT count,
  REAL tension
);

Parameters

points
[in] Pointer to an array of points that define the cardinal spline. The cardinal spline is a curve that passes through each point in the array.
count
[in] Integer that specifies the number of elements in the points array.
tension
[in] Nonnegative real number that controls the length of the curve and how the curve bends. A value of 0 specifies that the spline is a sequence of straight line segments. As the value increases, the curve becomes fuller.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

You should keep a copy of the points array if those points will be needed later. The GraphicsPath object does not store the points passed to the AddClosedCurve method; instead, it converts the cardinal spline to a sequence of Bézier splines and stores the points that define those Bézier splines. You cannot retrieve the original array of points from the GraphicsPath object.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a cardinal spline to path, and then draws path. The tension is set to 1.0.

VOID AddCurveExample(HDC hdc)
{
   Graphics graphics(hdc);

   PointF pts[] = {PointF(50.0f, 50.0f),
                   PointF(60.0f, 20.0f),
                   PointF(70.0f, 100.0f),
                   PointF(80.0f, 50.0f)};

   GraphicsPath path;
   path.AddCurve(pts, 4, 1.0f);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddBezier Methods, AddBeziers Methods, AddClosedCurve Methods, AddCurve Methods, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Drawing Cardinal Splines
Concepts
Cardinal Splines, Paths


GraphicsPath::AddEllipse Methods

This topic lists the AddEllipse methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • AddEllipse(Rect& rect)
  • AddEllipse(RectF& rect)
  • AddEllipse(INT x, INT y, INT width, INT height)
  • AddEllipse(REAL x, REAL y, REAL width, REAL height)


GraphicsPath::AddEllipse(Rect& rect)

The AddEllipse method adds an ellipse to this path.

Status AddEllipse(
  const Rect& rect
);

Parameters

rect
[in] Reference to a rectangle that bounds the ellipse.

Remarks

A GraphicsPath object stores an ellipse as a sequence of four connected Bézier splines. The GraphicsPath object does not store the upper-left corner, width, and height of the ellipse's bounding rectangle.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds an ellipse to path, and then draws path.

VOID Example_AddEllipse(HDC hdc)
{
   Graphics graphics(hdc);
   Rect rect(20, 20, 200, 100);

   GraphicsPath path;
   path.AddEllipse(rect);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddArc Methods, AddEllipse Methods, Rect
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Ellipses and Arcs, Paths


GraphicsPath::AddEllipse(RectF& rect)

The AddEllipse method adds an ellipse to this path.

Status AddEllipse(
  const RectF& rect
);

Parameters

rect
[in] Reference to a rectangle that bounds the ellipse.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A GraphicsPath object stores an ellipse as a sequence of four connected Bézier splines. The GraphicsPath object does not store the upper-left corner, width, and height of the ellipse's bounding rectangle.

Example Code [C++]

The following example creates a GraphicsPath object path, adds an ellipse to path, and then draws path.

VOID Example_AddEllipse(HDC hdc)
{
   Graphics graphics(hdc);
   RectF rect(20.0f, 20.0f, 200.0f, 100.0f);

   GraphicsPath path;
   path.AddEllipse(rect);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddArc Methods, AddEllipse Methods, RectF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Ellipses and Arcs, Paths


GraphicsPath::AddEllipse(INT x, INT y, INT width, INT height)

The AddEllipse method adds an ellipse to this path.

Status AddEllipse(
  INT x,
  INT y,
  INT width,
  INT height
);

Parameters

x
[in] Integer that specifies the x-coordinate of the upper-left corner of the bounding rectangle for the ellipse.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the bounding rectangle for the ellipse.
width
[in] Integer that specifies the width of the bounding rectangle for the ellipse.
height
[in] Integer that specifies the height of the bounding rectangle for the ellipse.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A GraphicsPath object stores an ellipse as a sequence of four connected Bézier splines. The GraphicsPath object does not store the upper-left corner, width, and height of the ellipse's bounding rectangle.

Example Code [C++]

The following example creates a GraphicsPath object path, adds an ellipse to path, and then draws path.

VOID Example_AddEllipse(HDC hdc)
{
   Graphics graphics(hdc);

   GraphicsPath path;
   path.AddEllipse(20, 20, 200, 100);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddArc Methods, AddEllipse Methods
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Ellipses and Arcs, Paths


GraphicsPath::AddEllipse(REAL x, REAL y, REAL width, REAL height)

The AddEllipse method adds an ellipse to this path.

Status AddEllipse(
  REAL x,
  REAL y,
  REAL width,
  REAL height
);

Parameters

x
[in] Real number that specifies the x-coordinate of the upper-left corner of the bounding rectangle for the ellipse.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the bounding rectangle for the ellipse.
width
[in] Real number that specifies the width of the bounding rectangle for the ellipse.
height
[in] Real number that specifies the height of the bounding rectangle for the ellipse.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A GraphicsPath object stores an ellipse as a sequence of four connected Bézier splines. The GraphicsPath object does not store the upper-left corner, width, and height of the ellipse's bounding rectangle.

Example Code [C++]

The following example creates a GraphicsPath object path, adds an ellipse to path, and then draws path.

VOID Example_AddEllipse(HDC hdc)
{
   Graphics graphics(hdc);

   GraphicsPath path;
   path.AddEllipse(20.0f, 20.0f, 200.0f, 100.0f);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddArc Methods, AddEllipse Methods
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Ellipses and Arcs, Paths


GraphicsPath::AddLine Methods

This topic lists the AddLine methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • AddLine(Point& pt1, Point& pt2)
  • AddLine(PointF& pt1, PointF& pt2)
  • AddLine(INT x1, INT y1, INT x2, INT y2)
  • AddLine(REAL x1, REAL y1, REAL x2, REAL y2)


GraphicsPath::AddLine(Point& pt1, Point& pt2)

The AddLine method adds a line to the current figure of this path.

Status AddLine(
  const Point& pt1,
  const Point& pt2
);

Parameters

pt1
[in] Reference to a point at which to start the line.
pt2
[in] Reference to a point at which to end the line.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a line to path, and then draws path.

VOID Example_AddLine(HDC hdc)
{
   Graphics graphics(hdc);

   Point point1(20, 20);
   Point point2(100, 100);

   GraphicsPath path;
   path.AddLine(point1, point2);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddLine Methods, AddLines Methods, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Using a Pen to Draw Lines and Rectangles
Concepts
Paths, Pens, Lines, and Rectangles


GraphicsPath::AddLine(PointF& pt1, PointF& pt2)

The AddLine method adds a line to the current figure of this path.

Status AddLine(
  const PointF& pt1,
  const PointF& pt2
);

Parameters

pt1
[in] Reference to a point at which to start the line.
pt2
[in] Reference to a point at which to end the line.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a line to path, and then draws path.

VOID Example_AddLine(HDC hdc)
{
   Graphics graphics(hdc);

   PointF point1(20.0f, 20.0f);
   PointF point2(100.0f, 100.0f);

   GraphicsPath path;
   path.AddLine(point1, point2);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddLine Methods, AddLines Methods, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Using a Pen to Draw Lines and Rectangles
Concepts
Paths, Pens, Lines, and Rectangles


GraphicsPath::AddLine(INT x1, INT y1, INT x2, INT y2)

The AddLine method adds a line to the current figure of this path.

Status AddLine(
  INT x1,
  INT y1,
  INT x2,
  INT y2
);

Parameters

x1
[in] Integer that specifies the x-coordinate of the starting point of the line.
y1
[in] Integer that specifies the y-coordinate of the starting point of the line.
x2
[in] Integer that specifies the x-coordinate of the ending point of the line.
y2
[in] Integer that specifies the y-coordinate of the ending point of the line.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a line to path, and then draws path.

VOID Example_AddLine(HDC hdc)
{
   Graphics graphics(hdc);

   GraphicsPath path;
   path.AddLine(20, 20, 100, 100);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddLine Methods, AddLines Methods
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Using a Pen to Draw Lines and Rectangles
Concepts
Paths, Pens, Lines, and Rectangles


GraphicsPath::AddLine(REAL x1, REAL y1, REAL x2, REAL y2)

The AddLine method adds a line to the current figure of this path.

Status AddLine(
  REAL x1,
  REAL y1,
  REAL x2,
  REAL y2
);

Parameters

x1
[in] Real number that specifies the x-coordinate of the starting point of the line.
y1
[in] Real number that specifies the y-coordinate of the starting point of the line.
x2
[in] Real number that specifies the x-coordinate of the ending point of the line.
y2
[in] Real number that specifies the y-coordinate of the ending point of the line.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a line to path, and then draws path.

VOID Example_AddLine(HDC hdc)
{
   Graphics graphics(hdc);

   GraphicsPath path;
   path.AddLine(20.0f, 20.0f, 100.0f, 100.0f);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddLine Methods, AddLines Methods
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Using a Pen to Draw Lines and Rectangles
Concepts
Paths, Pens, Lines, and Rectangles


GraphicsPath::AddLines Methods

This topic lists the AddLines methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • AddLines(Point* points, INT count)
  • AddLines(PointF* points, INT count)


GraphicsPath::AddLines(Point* points, INT count)

The AddLines method adds a sequence of connected lines to the current figure of this path.

Status AddLines(
  const Point* points,
  INT count
);

Parameters

points
[in] Pointer to an array of points that specify the starting and ending points of the lines. The first point in the array is the starting point of the first line, and the last point in the array is the ending point of the last line. Each of the other points serves as ending point for one line and starting point for the next line.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a sequence of four connected lines to path, and then draws path.

VOID Example_AddLines(HDC hdc)
{
   Graphics graphics(hdc);

   Point pts[] = {Point(20, 20),
                  Point(30, 30),
                  Point(40, 25),
                  Point(50, 30),
                  Point(60, 20)};

   GraphicsPath path;
   path.AddLines(pts, 5);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddLine Methods, AddLines Methods, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Using a Pen to Draw Lines and Rectangles
Concepts
Paths, Pens, Lines, and Rectangles


GraphicsPath::AddLines(PointF* points, INT count)

The AddLines method adds a sequence of connected lines to the current figure of this path.

Status AddLines(
  const PointF* points,
  INT count
);

Parameters

points
[in] Pointer to an array of points that specify the starting and ending points of the lines. The first point in the array is the starting point of the first line, and the last point in the array is the ending point of the last line. Each of the other points serves as ending point for one line and starting point for the next line.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a sequence of four connected lines to path, and then draws path.

VOID Example_AddLines(HDC hdc)
{
   Graphics graphics(hdc);

   PointF pts[] = {PointF(20.0f, 20.0f),
                   PointF(30.0f, 30.0f),
                   PointF(40.0f, 25.0f),
                   PointF(50.0f, 30.0f),
                   PointF(60.0f, 20.0f)};

   GraphicsPath path;
   path.AddLines(pts, 5);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddLine Methods, AddLines Methods, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Using a Pen to Draw Lines and Rectangles
Concepts
Paths, Pens, Lines, and Rectangles


GraphicsPath::AddPath(addingPath, connect)

The AddPath method adds a path to this path.

Status AddPath(
  const GraphicsPath* addingPath,
  BOOL connect
);

Parameters

addingPath
[in] Pointer to the path to be added.
connect
[in] Boolean value that specifies whether the first figure in the added path is part of the last figure in this path. TRUE specifies that (if possible) the first figure in the added path is part of the last figure in this path. FALSE specifies that the first figure in the added path is separate from the last figure in this path.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Even if the value of the connect parameter is TRUE, this method might not be able to make the first figure of the added path part of the last figure of this path. If either of those figures is closed, then they must remain separate figures.

Example Code [C++]

The following example creates two GraphicsPath objects: path1 and path2. The code adds an open figure consisting of an arc and a Bézier spline to each path. The code calls the AddPath method of path1 to add path2 to path1. The second argument is TRUE, which specifies that all four items (two arcs and two Bézier splines) belong to the same figure.

VOID AddPathExample(HDC hdc)
{
   Graphics graphics(hdc);

   GraphicsPath path1;
   path1.AddArc(10, 10, 50, 20, 0.0f, 150.0f);
   path1.AddBezier(10, 50, 60, 50, 10, 80, 60, 80);

   GraphicsPath path2;
   path2.AddArc(10, 110, 50, 20, 0.0f, 150.0f);
   path2.AddBezier(10, 150, 60, 150, 10, 180, 60, 180);

   path1.AddPath(&path2, TRUE);

   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawPath(&pen, &path1);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddEllipse Methods, AddRectangle Methods
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::AddPie Methods

This topic lists the AddPie methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • AddPie(Rect& rect, REAL startAngle, REAL sweepAngle)
  • AddPie(RectF& rect, REAL startAngle, REAL sweepAngle)
  • AddPie(INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)
  • AddPie(REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)


GraphicsPath::AddPie(Rect& rect, REAL startAngle, REAL sweepAngle)

The AddPie method adds a pie to this path. An arc is a portion of an ellipse, and a pie is a portion of the area enclosed by an ellipse. A pie is bounded by an arc and two lines (edges) that go from the center of the ellipse to the endpoints of the arc.

Status AddPie(
  const Rect& rect,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

rect
[in] Reference to a rectangle that bounds the ellipse that bounds the pie.
startAngle
[in] Real number that specifies the clockwise angle, in degrees, between the horizontal axis of the ellipse and the starting point of the arc that defines the pie.
sweepAngle
[in] Real number that specifies the clockwise angle, in degrees, between the starting and ending points of the arc that defines the pie.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a pie to path, and then draws path.

VOID Example_AddPie(HDC hdc)
{
   Graphics graphics(hdc);
   Rect rect(50, 50, 100, 100);

   GraphicsPath path;
   path.AddPie(rect, 20.0f, 45.0f);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);

   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddArc Methods, AddPie Methods, DrawArc Methods, DrawPie Methods, Rect
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Ellipses and Arcs, Open and Closed Curves, Paths


GraphicsPath::AddPie(RectF& rect, REAL startAngle, REAL sweepAngle)

The AddPie method adds a pie to this path. An arc is a portion of an ellipse, and a pie is a portion of the area enclosed by an ellipse. A pie is bounded by an arc and two lines (edges) that go from the center of the ellipse to the endpoints of the arc.

Status AddPie(
  const RectF& rect,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

rect
[in] Reference to a rectangle that bounds the ellipse that bounds the pie.
startAngle
[in] Real number that specifies the clockwise angle, in degrees, between the horizontal axis of the ellipse and the starting point of the arc that defines the pie.
sweepAngle
[in] Real number that specifies the clockwise angle, in degrees, between the starting and ending points of the arc that defines the pie.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a pie to path, and then draws path.

VOID Example_AddPie(HDC hdc)
{
   Graphics graphics(hdc);

   RectF rect(50.0f, 50.0f, 100.0f, 100.0f);

   GraphicsPath path;
   path.AddPie(rect, 20.0f, 45.0f);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);

   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddArc Methods, AddPie Methods, DrawArc Methods, DrawPie Methods, RectF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Ellipses and Arcs, Open and Closed Curves, Paths


GraphicsPath::AddPie(INT x, INT y, INT width, INT height, REAL startAngle, REAL sweepAngle)

The AddPie method adds a pie to this path. An arc is a portion of an ellipse, and a pie is a portion of the area enclosed by an ellipse. A pie is bounded by an arc and two lines (edges) that go from the center of the ellipse to the endpoints of the arc.

Status AddPie(
  INT x,
  INT y,
  INT width,
  INT height,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

x
[in] Integer that specifies the x-coordinate of the upper-left corner of the rectangle that bounds the ellipse that bounds the pie.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the rectangle that bounds the ellipse that bounds the pie.
width
[in] Integer that specifies the width of the rectangle that bounds the ellipse that bounds the pie.
height
[in] Integer that specifies the height of the rectangle that bounds the ellipse that bounds the pie.
startAngle
[in] Real number that specifies the clockwise angle, in degrees, between the horizontal axis of the ellipse and the starting point of the arc that defines the pie.
sweepAngle
[in] Real number that specifies the clockwise angle, in degrees, between the starting and ending points of the arc that defines the pie.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a pie to path, and then draws path.

VOID Example_AddPie(HDC hdc)
{
   Graphics graphics(hdc);

   GraphicsPath path;
   path.AddPie(50, 50, 100, 100, 20.0f, 45.0f);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);

   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddArc Methods, AddPie Methods, DrawArc Methods, DrawPie Methods
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Ellipses and Arcs, Open and Closed Curves, Paths


GraphicsPath::AddPie(REAL x, REAL y, REAL width, REAL height, REAL startAngle, REAL sweepAngle)

The AddPie method adds a pie to this path. An arc is a portion of an ellipse, and a pie is a portion of the area enclosed by an ellipse. A pie is bounded by an arc and two lines (edges) that go from the center of the ellipse to the endpoints of the arc.

Status AddPie(
  REAL x,
  REAL y,
  REAL width,
  REAL height,
  REAL startAngle,
  REAL sweepAngle
);

Parameters

x
[in] Real number that specifies the x-coordinate of the upper-left corner of the rectangle that bounds the ellipse that bounds the pie.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the rectangle that bounds the ellipse that bounds the pie.
width
[in] Real number that specifies the width of the rectangle that bounds the ellipse that bounds the pie.
height
[in] Real number that specifies the height of the rectangle that bounds the ellipse that bounds the pie.
startAngle
[in] Real number that specifies the clockwise angle, in degrees, between the horizontal axis of the ellipse and the starting point of the arc that defines the pie.
sweepAngle
[in] Real number that specifies the clockwise angle, in degrees, between the starting and ending points of the arc that defines the pie.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a pie to path, and then draws path.

VOID Example_AddPie(HDC hdc)
{
   Graphics graphics(hdc);

   GraphicsPath path;
   path.AddPie(50.0f, 50.0f, 100.0f, 100.0f, 20.0f, 45.0f);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);

   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddArc Methods, AddPie Methods, DrawArc Methods, DrawPie Methods
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Ellipses and Arcs, Open and Closed Curves, Paths


GraphicsPath::AddPolygon Methods

This topic lists the AddPolygon methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • AddPolygon(Point* points, INT count)
  • AddPolygon(PointF* points, INT count)


GraphicsPath::AddPolygon(Point* points, INT count)

The AddPolygon method adds a polygon to this path.

Status AddPolygon(
  const Point* points,
  INT count
);

Parameters

points
[in] Pointer to an array of points that specifies the vertices of the polygon.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The AddPolygon method is similar to the AddLines method. The difference is that a polygon is an intrinsically closed figure, but a sequence of lines is not a closed figure unless you call CloseFigure. When GDI+ renders a path, each polygon in that path is closed; that is, the last vertex of the polygon is connected to the first vertex by a straight line.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a polygon to path, and then draws path.

VOID Example_AddPolygon(HDC hdc)
{
   Graphics graphics(hdc);

   Point pts[] = {Point(20, 20),
                  Point(120, 20),
                  Point(120, 70)};

   GraphicsPath path;
   path.AddPolygon(pts, 3);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddPolygon Methods, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths, Polygons


GraphicsPath::AddPolygon(PointF* points, INT count)

The AddPolygon method adds a polygon to this path.

Status AddPolygon(
  const PointF* points,
  INT count
);

Parameters

points
[in] Pointer to an array of points that specifies the vertices of the polygon.
count
[in] Integer that specifies the number of elements in the points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The AddPolygon method is similar to the AddLines method. The difference is that a polygon is an intrinsically closed figure, but a sequence of lines is not a closed figure unless you call CloseFigure. When GDI+ renders a path, each polygon in that path is closed; that is, the last vertex of the polygon is connected to the first vertex by a straight line.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a polygon to path, and then draws path.

VOID Example_AddPolygon(HDC hdc)
{
   Graphics graphics(hdc);

   PointF pts[] = {PointF(20.0f, 20.0f),
                   PointF(120.0f, 20.0f),
                   PointF(120.0f, 70.0f)};

   GraphicsPath path;
   path.AddPolygon(pts, 3);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddPolygon Methods, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths, Polygons


GraphicsPath::AddRectangle Methods

This topic lists the AddRectangle methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • AddRectangle(Rect& rect)
  • AddRectangle(RectF& rect)


GraphicsPath::AddRectangle(Rect& rect)

The AddRectangle method adds a rectangle to this path.

Status AddRectangle(
  const Rect& rect
);

Parameters

rect
[in] Reference to a rectangle to be added to the path.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a rectangle to path, and then draws path.

VOID Example_AddRectangle(HDC hdc)
{
   Graphics graphics(hdc);
   Rect rect(20, 20, 100, 50);

   GraphicsPath path;
   path.AddRectangle(rect);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddRectangle Methods, AddRectangles Methods, Rect
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Using a Pen to Draw Lines and Rectangles
Concepts
Paths, Pens, Lines, and Rectangles


GraphicsPath::AddRectangle(RectF& rect)

The AddRectangle method adds a rectangle to this path.

Status AddRectangle(
  const RectF& rect
);

Parameters

rect
[in] Reference to a rectangle to be added to the path.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a rectangle to path, and then draws path.

VOID Example_AddRectangle(HDC hdc)
{
   Graphics graphics(hdc);
   RectF rect(20.0f, 20.0f, 100.0f, 50.0f);

   GraphicsPath path;
   path.AddRectangle(rect);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddRectangle Methods, AddRectangles Methods, RectF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Using a Pen to Draw Lines and Rectangles
Concepts
Paths, Pens, Lines, and Rectangles


GraphicsPath::AddRectangles Methods

This topic lists the AddRectangles methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • AddRectangles(Rect* rects, INT count)
  • AddRectangles(RectF* rects, INT count)


GraphicsPath::AddRectangles(Rect* rects, INT count)

The AddRectangles method adds a sequence of rectangles to this path

Status AddRectangles(
  const Rect* rects,
  INT count
);

Parameters

rects
[in] Pointer to an array of rectangles that will be added to the path.
count
[in] Integer that specifies the number of elements in the rects array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds two rectangles to path, and then draws path.

VOID Example_AddRectangles(HDC hdc)
{
   Graphics graphics(hdc);

   Rect rects[] = {Rect(20, 20, 100, 50),
                   Rect(30, 30, 50, 100)};

   GraphicsPath path;
   path.AddRectangles(rects, 2);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddRectangle Methods, AddRectangles Methods, Rect
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Using a Pen to Draw Lines and Rectangles
Concepts
Paths, Pens, Lines, and Rectangles


GraphicsPath::AddRectangles(RectF* rects, INT count)

The AddRectangles method adds a sequence of rectangles to this path.

Status AddRectangles(
  const RectF* rects,
  INT count
);

Parameters

rects
[in] Pointer to an array of rectangles that will be added to the path.
count
[in] Integer that specifies the number of elements in the rects array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds two rectangles to path, and then draws path.

VOID Example_AddRectangles(HDC hdc)
{
   Graphics graphics(hdc);

   RectF rects[] = {RectF(20.0f, 20.0f, 100.0f, 50.0f),
                    RectF(30.0f, 30.0f, 50.0f, 100.0f)};

   GraphicsPath path;
   path.AddRectangles(rects, 2);

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddRectangle Methods, AddRectangles Methods, RectF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Using a Pen to Draw Lines and Rectangles
Concepts
Paths, Pens, Lines, and Rectangles


GraphicsPath::AddString Methods

This topic lists the AddString methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • AddString(WCHAR* string, INT length, FontFamily* family, INT style, REAL emSize, Rect& layoutRect, StringFormat* format)
  • AddString(WCHAR* string, INT length, FontFamily* family, INT style, REAL emSize, RectF& layoutRect, StringFormat* format)
  • AddString(WCHAR* string, INT length, FontFamily* family, INT style, REAL emSize, Point& origin, StringFormat* format)
  • AddString(WCHAR* string, INT length, FontFamily* family, INT style, REAL emSize, PointF& origin, StringFormat* format)


GraphicsPath::AddString(WCHAR* string, INT length, FontFamily* family, INT style, REAL emSize, Rect& layoutRect, StringFormat* format)

The AddString method adds the outline of a string to this path.

Status AddString(
  const WCHAR* string,
  INT length,
  const FontFamily* family,
  INT style,
  REAL emSize,
  const Rect& layoutRect,
  const StringFormat* format
);

Parameters

string
[in] Pointer to a wide-character string.
length
[in] Integer that specifies the number of characters to display. If the string parameter points to a null-terminated string, this parameter can be set to –1.
family
[in] Pointer to a FontFamily object that specifies the font family for the string.
style
[in] Integer that specifies the style of the typeface. This value must be an element of the FontStyle enumeration or the result of a bitwise OR applied to two or more of these elements. For example, FontStyleBold | FontStyleUnderline | FontStyleStrikeout sets the style as a combination of the three styles.
emSize
[in] Real number that specifies the em size, in world units, of the string characters.
layoutRect
[in] Reference to a Rect object that specifies, in world units, the bounding rectangle for the string.
format
[in] Pointer to a StringFormat object that specifies layout information (alignment, trimming, tab stops, and the like) for the string.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a null-terminated string to path, and then draws path.

VOID Example_AddString(HDC hdc)
{
   Graphics graphics(hdc);
   FontFamily fontFamily(L"Times New Roman");
   GraphicsPath path;

   path.AddString(
      L"Hello World",
      -1,                 // null-terminated string
      &fontFamily,
      FontStyleRegular,
      48,
      Rect(50, 50, 150, 100),
      NULL);

   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddString Methods, Font, FontFamily, FontStyle, StringFormat, Rect
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Using Text and Fonts


GraphicsPath::AddString(WCHAR* string, INT length, FontFamily* family, INT style, REAL emSize, RectF& layoutRect, StringFormat* format)

The AddString method adds the outline of a string to this path.

Status AddString(
  const WCHAR* string,
  INT length,
  const FontFamily* family,
  INT style,
  REAL emSize,
  const RectF& layoutRect,
  const StringFormat* format
);

Parameters

string
[in] Pointer to a wide-character string.
length
[in] Integer that specifies the number of characters to display. If the string parameter points to a null-terminated string, this parameter can be set to –1.
family
[in] Pointer to a FontFamily object that specifies the font family for the string.
style
[in] Integer that specifies the style of the typeface. This value must be an element of the FontStyle enumeration or the result of a bitwise OR applied to two or more of these elements. For example, FontStyleBold | FontStyleUnderline | FontStyleStrikeout sets the style as a combination of the three styles.
emSize
[in] Real number that specifies the em size, in world units, of the string characters.
layoutRect
[in] Reference to a RectF object that specifies, in world units, the bounding rectangle for the string.
format
[in] Pointer to a StringFormat object that specifies layout information (alignment, trimming, tab stops, and the like) for the string.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a null-terminated string to path, and then draws path.

VOID Example_AddString(HDC hdc)
{
   Graphics graphics(hdc);
   FontFamily fontFamily(L"Times New Roman");
   GraphicsPath path;

   path.AddString(
      L"Hello World",
      -1,                 // null-terminated string
      &fontFamily,
      FontStyleRegular,
      48,
      RectF(50.0f, 50.0f, 150.0f, 100.0f),
      NULL);

   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddString Methods, Font, FontFamily, FontStyle, StringFormat, RectF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Using Text and Fonts


GraphicsPath::AddString(WCHAR* string, INT length, FontFamily* family, INT style, REAL emSize, Point& origin, StringFormat* format)

The AddString method adds the outlines of a string to this path.

Status AddString(
  const WCHAR* string,
  INT length,
  const FontFamily* family,
  INT style,
  REAL emSize,
  const Point& origin,
  const StringFormat* format
);

Parameters

string
[in] Pointer to a wide-character string.
length
[in] Integer that specifies the number of characters to display. If the string parameter points to a null-terminated string, this parameter can be set to –1.
family
[in] Pointer to a FontFamily object that specifies the font family for the string.
style
[in] Integer that specifies the style of the typeface. This value must be an element of the FontStyle enumeration or the result of a bitwise OR applied to two or more of these elements. For example, FontStyleBold | FontStyleUnderline | FontStyleStrikeout sets the style as a combination of the three styles.
emSize
[in] Real number that specifies the em size, in world units, of the string characters.
origin
[in] Reference to a Point object that specifies, in world units, the location of the string.
format
[in] Pointer to a StringFormat object that specifies layout information (alignment, trimming, tab stops, and the like) for the string.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a null-terminated string to path, and then draws path.

VOID Example_AddString(HDC hdc)
{
   Graphics graphics(hdc);
   FontFamily fontFamily(L"Times New Roman");
   GraphicsPath path;

   path.AddString(
      L"Hello World",
      -1,                 // null-terminated string
      &fontFamily,
      FontStyleRegular,
      48,
      Point(50, 50),
      NULL);

   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddString Methods, Font, FontFamily, FontStyle, StringFormat, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Using Text and Fonts


GraphicsPath::AddString(WCHAR* string, INT length, FontFamily* family, INT style, REAL emSize, PointF& origin, StringFormat* format)

The AddString method adds the outline of a string to this path.

Status AddString(
  const WCHAR* string,
  INT length,
  const FontFamily* family,
  INT style,
  REAL emSize,
  const PointF& origin,
  const StringFormat* format
);

Parameters

string
[in] Pointer to a wide-character string.
length
[in] Integer that specifies the number of characters to display. If the string parameter points to a null-terminated string, this parameter can be set to –1
family
[in] Pointer to a FontFamily object that specifies the font family for the string.
style
[in] Integer that specifies the style of the typeface. This value must be an element of the FontStyle enumeration or the result of a bitwise OR applied to two or more of these elements. For example, FontStyleBold | FontStyleUnderline | FontStyleStrikeout sets the style as a combination of the three styles.
emSize
[in] Real number that specifies the em size, in world units, of the string characters.
origin
[in] Reference to a PointF object that specifies, in world units, the location of the string.
format
[in] Pointer to a StringFormat object that specifies layout information (alignment, trimming, tab stops, and the like) for the string.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds a null-terminated string to path, and then draws path.

VOID Example_AddString(HDC hdc)
{
   Graphics graphics(hdc);
   FontFamily fontFamily(L"Times New Roman");
   GraphicsPath path;

   path.AddString(
      L"Hello World",
      -1,                 // null-terminated string
      &fontFamily,
      FontStyleRegular,
      48,
      PointF(50.0f, 50.0f),
      NULL);

   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddString Methods, Font, FontFamily, FontStyle, StringFormat, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Using Text and Fonts


GraphicsPath::ClearMarkers()

The ClearMarkers method clears the markers from this path.

Status ClearMarkers(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
NextMarker Methods, SetMarker
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::Clone()

The Clone method creates a new GraphicsPath object, and initializes it with the contents of this GraphicsPath object.

GraphicsPath* Clone(void);

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new GraphicsPath object.

Example Code [C++]

The following example creates a GraphicsPath object path1, and then clones path1 to create a new GraphicsPath object.

GraphicsPath path1;
GraphicsPath* pPath2 = path1.Clone();

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GraphicsPath Constructors
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::CloseAllFigures()

The CloseAllFigures method closes all open figures in this path.

Status CloseAllFigures(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path, adds two figures to path (arcs), closes all figures, and then draws path.

VOID Example_CloseAllFigures(HDC hdc)
{
   Graphics graphics(hdc);

   Rect rect1(20, 20, 50, 100);
   Rect rect2(40, 40, 50, 100);

   GraphicsPath path;
   path.AddArc(rect1, 0.0f, 180.0f);  // first figure
   path.StartFigure();
   path.AddArc(rect2, 0.0f, 180.0f);  // second figure
   path.CloseAllFigures();

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
CloseFigure, StartFigure
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Open and Closed Curves, Paths


GraphicsPath::CloseFigure()

The CloseFigure method closes the current figure of this path.

Status CloseFigure(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object path and adds two figures to path. The code closes the first figure, but leaves the second figure open.

VOID Example_CloseFigure(HDC hdc)
{
   Graphics graphics(hdc);

   Rect rect1(20, 20, 50, 100);
   Rect rect2(40, 40, 50, 100);

   GraphicsPath path;
   path.AddArc(rect1, 0.0f, 180.0f);  // first figure
   path.CloseFigure();                // first figure closed
   path.AddArc(rect2, 0.0f, 180.0f);  // second figure

   // Draw the path.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
CloseAllFigures, StartFigure
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Open and Closed Curves, Paths


GraphicsPath::Flatten(matrix, flatness)

The Flatten method applies a transformation to this path and converts each curve in the path to a sequence of connected lines.

Status Flatten(
  const Matrix* matrix,
  REAL flatness
);

Parameters

matrix
[in] Optional. Pointer to a Matrix object that specifies the transformation to be applied to the path's data points. The default value is NULL, which specifies that no transformation is to be applied.
flatness
[in] Optional. Real number that specifies the maximum error between the path and its flattened approximation. Reducing the flatness increases the number of line segments in the approximation. The default value is FlatnessDefault, which is a constant defined in Gdiplusenums.h.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object and then adds a curve (cardinal spline), an ellipse, and a Bézier spline to the path. The code draws the path in blue, flattens the path, and then draws the flattened path in green. The call to GetPathData gets the data points stored by the flattened path. The code draws each of those points by filling a small ellipse with red.

VOID FlattenExample(HDC hdc)
{
   Graphics graphics(hdc);

   // Begin example.
   Point pts[] = {Point(20,50),
                  Point(40,70),
                  Point(60,10),
                  Point(80,50)};

   GraphicsPath path;
   path.AddCurve(pts, 4);
   path.AddEllipse(20, 100, 150, 80);
   path.AddBezier(20, 200, 20, 250, 50, 210, 100, 260);

   // Draw the path before flattening.
   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawPath(&pen, &path);

   path.Flatten(NULL, 8.0f);

   // Draw the flattened path.
   pen.SetColor(Color(255, 0, 255, 0));
   graphics.DrawPath(&pen, &path);

   // Get the path data from the flattened path.
   PathData pathData;
   path.GetPathData(&pathData);

   // Draw the data points of the flattened path.
   SolidBrush brush(Color(255, 255, 0, 0));
   for(INT j = 0; j < pathData.Count; ++j)
   {
      graphics.FillEllipse(
         &brush,
         pathData.Points[j].X - 3.0f,
         pathData.Points[j].Y - 3.0f,
         6.0f,
         6.0f);
   }
}

In the preceding example, the NULL argument passed to the Flatten method indicates no transformation should be applied to the path when it is flattened. If you want to transform the path along with flattening it, you can pass the address of a Matrix object to the Flatten method. For example, to rotate and translate the flattened path, replace the statement path.Flatten(NULL, 8.0f); with the following code:

Matrix matrix;
matrix.Rotate(30.0f);
matrix.Translate(200.0f, 0.0f, MatrixOrderAppend);
path.Flatten(&matrix, 8.0f);

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Matrix Class
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Flattening Paths, Paths


GraphicsPath::GetBounds Methods

This topic lists the GetBounds methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • GetBounds(Rect* bounds, Matrix* matrix, Pen* pen)
  • GetBounds(RectF* bounds, Matrix* matrix, Pen* pen)


GraphicsPath::GetBounds(Rect* bounds, Matrix* matrix, Pen* pen)

The GetBounds method gets a bounding rectangle for this path.

Status GetBounds(
  Rect* bounds,
  const Matrix* matrix,
  const Pen* pen
);

Parameters

bounds
[out] Pointer to a Rect object that receives the bounding rectangle.
matrix
[in] Optional. Pointer to a Matrix object that specifies a transformation to be applied to this path before the bounding rectangle is calculated. This path is not permanently transformed; the transformation is used only during the process of calculating the bounding rectangle. The default value is NULL.
pen
[in] Optional. Pointer to a Pen object that influences the size of the bounding rectangle. The bounding rectangle received in bounds will be large enough to enclose this path when the path is drawn with the pen specified by this parameter. This ensures that the path is enclosed by the bounding rectangle even if the path is drawn with a wide pen. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The rectangle returned by this method might be larger than necessary to enclose the path as drawn by the specified pen. The rectangle is calculated to allow for the pen's miter limit at sharp corners and to allow for the pen's end caps.

Example Code [C++]

The following example creates a path that has one curve and one ellipse. The code draws the path with a thick yellow pen and a thin black pen. The GetBounds method receives the address of the thick yellow pen and calculates a bounding rectangle for the path. Then the code draws the bounding rectangle.

VOID GetBoundsExample(HDC hdc)
{
   Graphics graphics(hdc);
   Pen blackPen(Color(255, 0, 0, 0), 1);
   Pen yellowPen(Color(255, 255, 255, 0), 10);
   Pen redPen(Color(255, 255, 0, 0), 1);

   Point pts[] = {Point(120,120),
                  Point(200,130),
                  Point(150,200),
                  Point(130,180)};

   // Create a path that has one curve and one ellipse.
   GraphicsPath path;
   path.AddClosedCurve(pts, 4);
   path.AddEllipse(120, 220, 100, 40);

   // Draw the path with a thick yellow pen and a thin black pen.
   graphics.DrawPath(&yellowPen, &path);
   graphics.DrawPath(&blackPen, &path);

   // Get the path's bounding rectangle.
   Rect rect;
   path.GetBounds(&rect, NULL, &yellowPen);
   graphics.DrawRectangle(&redPen, rect);
}

Color(255, 0, 0, 0)Color(255, 255, 0,  0)

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Matrix, Pen, Rect
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::GetBounds(RectF* bounds, Matrix* matrix, Pen* pen)

The GetBounds method gets a bounding rectangle for this path.

Status GetBounds(
  RectF* bounds,
  const Matrix* matrix,
  const Pen* pen
);

Parameters

bounds
[out] Pointer to a RectF object that receives the bounding rectangle.
matrix
[in] Optional. Pointer to a Matrix object that specifies a transformation to be applied to this path before the bounding rectangle is calculated. This path is not permanently transformed; the transformation is used only during the process of calculating the bounding rectangle. The default value is NULL.
pen
[in] Optional. Pointer to a Pen object that influences the size of the bounding rectangle. The bounding rectangle received in bounds will be large enough to enclose this path when the path is drawn with the pen specified by this parameter. This ensures that the path is enclosed by the bounding rectangle even if the path is drawn with a wide pen. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The rectangle returned by this method might be larger than necessary to enclose the path as drawn by the specified pen. The rectangle is calculated to allow for the pen's miter limit at sharp corners and to allow for the pen's end caps.

Example Code [C++]

The following example creates a path that has one curve and one ellipse. The code draws the path with a thick yellow pen and a thin black pen. The GetBounds method receives the address of the thick yellow pen and calculates a bounding rectangle for the path. Then the code draws the bounding rectangle.

VOID GetBoundsExample(HDC hdc)
{
   Graphics graphics(hdc);
   Pen blackPen(Color(255, 0, 0, 0), 1);
   Pen yellowPen(Color(255, 255, 255, 0), 10);
   Pen redPen(Color(255, 255, 0, 0), 1);

   Point pts[] = {Point(120,120),
                  Point(200,130),
                  Point(150,200),
                  Point(130,180)};

   // Create a path that has one curve and one ellipse.
   GraphicsPath path;
   path.AddClosedCurve(pts, 4);
   path.AddEllipse(120, 220, 100, 40);

   // Draw the path with a thick yellow pen and a thin black pen.
   graphics.DrawPath(&yellowPen, &path);
   graphics.DrawPath(&blackPen, &path);

   // Get the path's bounding rectangle.
   RectF rect;
   path.GetBounds(&rect, NULL, &yellowPen);
   graphics.DrawRectangle(&redPen, rect);
}

Color(255, 0, 0, 0)Color(255, 255, 0,  0)

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Matrix, Pen, RectF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::GetFillMode()

The GetFillMode method gets the fill mode of this path.

FillMode GetFillMode(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the FillMode enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
FillMode, SetFillMode
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::GetLastPoint(lastPoint)

The GetLastPoint method gets the ending point of the last figure in this path.

Status GetLastPoint(
  PointF* lastPoint
);

Parameters

lastPoint
[out] Pointer to a PointF object that receives the last point.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a path, adds a sequence of three connected lines to the path, and then gets the last point in the path.

GraphicsPath path;
PointF lastPoint;
Point pts[] = {Point(20,20),
                Point(40,20),
                Point(40,40),
                Point(20,40) };
path.AddLines(pts, 4);
path.GetLastPoint(&lastPoint);

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddLines, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::GetLastStatus()

The GetLastStatus method returns a value that indicates the nature of this GraphicsPath object's most recent method failure.

Status GetLastStatus(void);

Parameters

This method has no parameters.

Return Values

The GetLastSatus method returns an element of the Status enumeration.

If no methods invoked on this GraphicsPath object have failed since the previous call to GetLastStatus, then GetLastStatus returns Ok.

If at least one method invoked on this GraphicsPath object has failed since the previous call to GetLastStatus, then GetLastStatus returns a value that indicates the nature of the most recent failure.

Remarks

You can call GetLastStatus immediately after constructing a GraphicsPath object to determine whether the constructor succeeded.

The first time you call the GetLastStatus method of a GraphicsPath object, it returns Ok if the constructor succeeded and all methods invoked so far on the GraphicsPath object succeeded. Otherwise, it returns a value that indicates the nature of the most recent failure.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Status
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::GetPathData(pathData)

The GetPathData method gets an array of points and an array of point types from this path. Together, these two arrays define the lines, curves, figures, and markers of this path.

Status GetPathData(
  PathData* pathData
);

Parameters

pathData
[out] Pointer to a PathData object that receives the path data. The Points data member of the PathData object receives a pointer to an array of PointF objects that contains the path points. The Types data member of the PathData object receives a pointer to an array of bytes that contains the point types. The Count data member of the PathData object receives an integer that indicates the number of elements in the Points array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A GraphicsPath object has an array of points and an array of types. Each element in the array of types is a byte that specifies the point type and a set of flags for the corresponding element in the array of points. Possible point types and flags are listed in the PathPointType enumeration.

You do not have to allocate or deallocate memory for the array of points or the array of types. The GetPathData method allocates memory for the arrays (points and types) that it returns. The PathData destructor deallocates the memory for those arrays.

Example Code [C++]

The following example creates and draws a path that has a line, a rectangle, an ellipse, and a curve. The code gets the path's points and types by passing the address of a PathData object to the GetPathData method. Then the code draws each of the path's data points.

VOID GetPathDataExample(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that has a line, a rectangle, an ellipse, and a curve.
   GraphicsPath path;

   PointF points[] = {
      PointF(200, 200),
      PointF(250, 240),
      PointF(200, 300),
      PointF(300, 310),
      PointF(250, 350)};

   path.AddLine(20, 100, 150, 200);
   path.AddRectangle(Rect(40, 30, 80, 60));
   path.AddEllipse(Rect(200, 30, 200, 100));
   path.AddCurve(points, 5);

   // Draw the path.
   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawPath(&pen, &path);

   // Get the path data.
   PathData pathData;
   path.GetPathData(&pathData);

   // Draw the path's data points.
   SolidBrush brush(Color(255, 255, 0, 0));
   for(INT j = 0; j < pathData.Count; ++j)
   {
      graphics.FillEllipse(
         &brush,
         pathData.Points[j].X - 3.0f,
         pathData.Points[j].Y - 3.0f,
         6.0f,
         6.0f);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetPathPoints Methods, GetPathTypes, GetPointCount, PathData, PathPointType, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::GetPathPoints Methods

This topic lists the GetPathPoints methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • GetPathPoints(Point* points, INT count)
  • GetPathPoints(PointF* points, INT count)


GraphicsPath::GetPathPoints(Point* points, INT count)

The GetPathPoints method gets this path's array of points. The array contains the endpoints and control points of the lines and Bézier splines that are used to draw the path.

Status GetPathPoints(
  Point* points,
  INT count
);

Parameters

points
[out] Pointer to an array of Point objects that receives the data points. You must allocate memory for this array. You can call the GetPointCount method to determine the required size of the array. The size, in bytes, should be the return value of GetPointCount multiplied by sizeof(Point).
count
[in] Integer that specifies the number of elements in the points array. Set this parameter equal to the return value of the GetPointCount method.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A GraphicsPath object has an array of points and an array of types. Each element in the array of types is a byte that specifies the point type and a set of flags for the corresponding element in the array of points. Possible point types and flags are listed in the PathPointType enumeration.

Example Code [C++]

The following example creates and draws a path that has a line, a rectangle, an ellipse, and a curve. The code calls the path's GetPointCount method to determine the number of data points that are stored in the path. The code allocates a buffer large enough to receive the array of data points and passes the address of that buffer to the GetPathPoints method. Finally, the code draws each of the path's data points.

VOID GetPathPointsExample(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that has a line, a rectangle, an ellipse, and a curve.
   GraphicsPath path;

   Point points[] = {
      Point(200, 200),
      Point(250, 240),
      Point(200, 300),
      Point(300, 310),
      Point(250, 350)};

   path.AddLine(20, 100, 150, 200);
   path.AddRectangle(Rect(40, 30, 80, 60));
   path.AddEllipse(Rect(200, 30, 200, 100));
   path.AddCurve(points, 5);

   // Draw the path.
   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawPath(&pen, &path);

   // Get the path points.
   INT count = path.GetPointCount();
   Point* dataPoints = new Point[count];
   path.GetPathPoints(dataPoints, count);

   // Draw the path's data points.
   SolidBrush brush(Color(255, 255, 0, 0));
   for(INT j = 0; j < count; ++j)
   {
      graphics.FillEllipse(
         &brush,
         dataPoints[j].X - 3.0f,
         dataPoints[j].Y - 3.0f,
         6.0f,
         6.0f);
   }
   delete [] dataPoints;
}
Color(255, 255, 0,  0)

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetPathData, GetPathTypes, GetPointCount, PathData, PathPointType, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::GetPathPoints(PointF* points, INT count)

The GetPathPoints method gets this path's array of points. The array contains the endpoints and control points of the lines and Bézier splines that are used to draw the path.

Status GetPathPoints(
  PointF* points,
  INT count
);

Parameters

points
[out] Pointer to an array of PointF objects that receives the data points. You must allocate memory for this array. You can call the GetPointCount method to determine the required size of the array. The size, in bytes, should be the return value of GetPointCount multiplied by sizeof(PointF).
count
[in] Integer that specifies the number of elements in the points array. Set this parameter equal to the return value of the GetPointCount method.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A GraphicsPath object has an array of points and an array of types. Each element in the array of types is a byte that specifies the point type and a set of flags for the corresponding element in the array of points. Possible point types and flags are listed in the PathPointType enumeration.

Example Code [C++]

The following example creates and draws a path that has a line, a rectangle, an ellipse, and a curve. The code calls the path's GetPointCount method to determine the number of data points that are stored in the path. The code allocates a buffer large enough to receive the array of data points and passes the address of that buffer to the GetPathPoints method. Finally, the code draws each of the path's data points.

VOID GetPathPointsExample(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that has a line, a rectangle, an ellipse, and a curve.
   GraphicsPath path;

   PointF points[] = {
      PointF(200, 200),
      PointF(250, 240),
      PointF(200, 300),
      PointF(300, 310),
      PointF(250, 350)};

   path.AddLine(20, 100, 150, 200);
   path.AddRectangle(Rect(40, 30, 80, 60));
   path.AddEllipse(Rect(200, 30, 200, 100));
   path.AddCurve(points, 5);

   // Draw the path.
   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawPath(&pen, &path);

   // Get the path points.
   INT count = path.GetPointCount();
   PointF* dataPoints = new PointF[count];
   path.GetPathPoints(dataPoints, count);

   // Draw the path's data points.
   SolidBrush brush(Color(255, 255, 0, 0));
   for(INT j = 0; j < count; ++j)
   {
      graphics.FillEllipse(
         &brush,
         dataPoints[j].X - 3.0f,
         dataPoints[j].Y - 3.0f,
         6.0f,
         6.0f);
   }
   delete [] dataPoints;
}
Color(255, 255, 0,  0)

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetPathData, GetPathTypes, GetPointCount, PathData, PathPointType, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::GetPathTypes(types, count)

The GetPathTypes method gets this path's array of point types.

Status GetPathTypes(
  BYTE* types,
  INT count
);

Parameters

types
[out] Pointer to an array that receives the point types. You must allocate memory for this array. You can call the GetPointCount method to determine the required size of the array.
count
[in] Integer that specifies the number of elements in the types array. Set this parameter equal to the return value of the GetPointCount method.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A GraphicsPath object has an array of points and an array of types. Each element in the array of types is a byte that specifies the point type and a set of flags for the corresponding element in the array of points. Possible point types and flags are listed in the PathPointType enumeration.

Example Code [C++]

The following example creates a path and adds a sequence of three connected lines to the path. The code calls the GetPointCount method to determine the number of bytes in the path's array of point types and then allocates a buffer large enough to hold that array. Then the code calls the GetPathTypes method to fill the buffer with the array of point types.

GraphicsPath path;
Point pts[] = {Point(0, 0), Point(2, 2), Point(3, 3), Point(0, 5)};
path.AddLines(pts, 4);
INT num = path.GetPointCount();
BYTE* pTypes = new BYTE[num];
path.GetPathTypes(pTypes, num);

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetPathData, GetPathPoints Methods, GetPointCount, PathData, PathPointType, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::GetPointCount()

The GetPointCount method gets the number of points in this path's array of data points. This is the same as the number of types in the path's array of point types.

INT GetPointCount(void);

Parameters

This method has no parameters.

Return Values

This method returns the number of points in the path's array of data points.

Remarks

A GraphicsPath object has an array of points and an array of types. Each element in the array of types is a byte that specifies the point type and a set of flags for the corresponding element in the array of points. Possible point types and flags are listed in the PathPointType enumeration.

Example Code [C++]

The following example creates a path that has one ellipse and one line. The code calls the GetPointCount method to determine the number of data points stored in the path. Then the code calls the GetPathPoints method to retrieve those data points. Finally, the code fills a small ellipse at each of the data points.

VOID GetPointCountExample(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that has one ellipse and one line.
   GraphicsPath path;
   path.AddEllipse(10, 10, 200, 100);
   path.AddLine(220, 120, 300, 160);

   // Find out how many data points are stored in the path.
   INT count = path.GetPointCount();

   // Draw the path points.
   SolidBrush redBrush(Color(255, 255, 0, 0));
   PointF* points = new PointF[count];
   path.GetPathPoints(points, count);

   for(INT j = 0; j < count; ++j)
      graphics.FillEllipse(
         &redBrush,
         points[j].X - 3.0f,
         points[j].Y - 3.0f,
         6.0f,
         6.0f);

   delete [] points;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetPathData, GetPathPoints Methods, GetPathTypes, PathData, PathPointType
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::IsOutlineVisible Methods

This topic lists the IsOutlineVisible methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • IsOutlineVisible(Point& point, Pen* pen, Graphics* g)
  • IsOutlineVisible(PointF& point, Pen* pen, Graphics* g)
  • IsOutlineVisible(INT x, INT y, Pen* pen, Graphics* g)
  • IsOutlineVisible(REAL x, REAL y, Pen* pen, Graphics* g)


GraphicsPath::IsOutlineVisible(Point& point, Pen* pen, Graphics* g)

The IsOutlineVisible method determines whether a specified point touches the outline of this path when the path is drawn by a specified Graphics object and a specified pen.

BOOL IsOutlineVisible(
  const Point& point,
  const Pen* pen,
  const Graphics* g
);

Parameters

point
[in] Reference to the point to be tested.
pen
[in] Pointer to a Pen object. This method determines whether the test point touches the path outline that would be drawn by this pen. More points will touch an outline drawn by a wide pen than will touch an outline drawn by a narrow pen.
g
[in] Optional. Pointer to a Graphics object that specifies a world-to-device transformation. If the value of this parameter is NULL, the test is done in world coordinates; otherwise, the test is done in device coordinates. The default value is NULL.

Return Values

If the test point touches the outline of this path, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates an elliptical path and draws that path with a wide yellow pen. Then the code tests each point in an array to see whether the point touches the outline (as it would be drawn by the wide yellow pen) of the path. Points that touch the outline are painted green, and points that don't touch the outline are painted red.

VOID Example_IsOutlineVisibleExample(HDC hdc)
{
   Graphics graphics(hdc);

   INT j;
   Pen yellowPen(Color(255, 255, 255, 0), 20);
   SolidBrush brush(Color(255, 255, 0, 0));

   // Create and draw a path.
   GraphicsPath path;
   path.AddEllipse(50, 50, 200, 100);
   graphics.DrawPath(&yellowPen, &path);

   // Create an array of three points, and determine whether each
   // point in the array touches the outline of the path.
   // If a point touches the outline, paint it green.
   // If a point does not touch the outline, paint it red.
   Point points[] = {
      Point(230, 138),
      Point(100, 120),
      Point(150, 170)};

   for(j = 0; j <= 2; ++j)
   {
      if(path.IsOutlineVisible(points[j], &yellowPen, &graphics))
         brush.SetColor(Color(255, 0, 255, 0));
      else
         brush.SetColor(Color(255, 255, 0, 0));

      graphics.FillEllipse(&brush, points[j].X - 3, points[j].Y - 3, 6, 6);
   }
}

Color(255, 255, 0,  0)Color(255, 255, 0,  0)

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Graphics Class, IsOutlineVisible Methods, IsVisible Methods, Pen, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Setting Pen Width and Alignment
Concepts
Paths, Pens, Lines, and Rectangles


GraphicsPath::IsOutlineVisible(PointF& point, Pen* pen, Graphics* g)

The IsOutlineVisible method determines whether a specified point touches the outline of this path when the path is drawn by a specified Graphics object and a specified pen.

BOOL IsOutlineVisible(
  const PointF& point,
  const Pen* pen,
  const Graphics* g
);

Parameters

point
[in] Reference to the point to be tested.
pen
[in] Pointer to a Pen object. This method determines whether the test point touches the path outline that would be drawn by this pen. More points will touch an outline drawn by a wide pen than will touch an outline drawn by a narrow pen.
g
[in] Optional. Pointer to a Graphics object that specifies a world-to-device transformation. If the value of this parameter is NULL, the test is done in world coordinates; otherwise, the test is done in device coordinates. The default value is NULL.

Return Values

If the test point touches the outline of this path, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates an elliptical path and draws that path with a wide yellow pen. Then the code tests each point in an array to see whether the point touches the outline (as it would be drawn by the wide yellow pen) of the path. Points that touch the outline are painted green, and points that don't touch the outline are painted red.

VOID Example_IsOutlineVisibleExample(HDC hdc)
{
   Graphics graphics(hdc);

   INT j;
   Pen yellowPen(Color(255, 255, 255, 0), 20);
   SolidBrush brush(Color(255, 255, 0,  0));

   // Create and draw a path.
   GraphicsPath path;
   path.AddEllipse(50, 50, 200, 100);
   graphics.DrawPath(&yellowPen, &path);

   // Create an array of three points, and determine whether each
   // point in the array touches the outline of the path.
   // If a point touches the outline, paint it green.
   // If a point does not touch the outline, paint it red.
   PointF points[] = {
      PointF(230, 138),
      PointF(100, 120),
      PointF(150, 170)};

   for(j = 0; j <= 2; ++j)
   {
      if(path.IsOutlineVisible(points[j], &yellowPen, NULL))
         brush.SetColor(Color(255, 0, 255,  0));
      else
         brush.SetColor(Color(255, 255, 0,  0));

      graphics.FillEllipse(&brush, points[j].X - 3.0f, points[j].Y - 3.0f, 6.0f, 6.0f);
   }
}

Color(255, 255, 0,  0)Color(255, 255, 0,  0)

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Graphics Class, IsOutlineVisible Methods, IsVisible Methods, Pen, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Setting Pen Width and Alignment
Concepts
Paths, Pens, Lines, and Rectangles


GraphicsPath::IsOutlineVisible(INT x, INT y, Pen* pen, Graphics* g)

The IsOutlineVisible method determines whether a specified point touches the outline of this path when the path is drawn by a specified Graphics object and a specified pen.

BOOL IsOutlineVisible(
  INT x,
  INT y,
  const Pen* pen,
  const Graphics* g
);

Parameters

x
[in] Integer that specifies the x-coordinate of the point to be tested.
y
[in] Integer that specifies the y-coordinate of the point to be tested.
pen
[in] Pointer to a Pen object. This method determines whether the test point touches the path outline that would be drawn by this pen. More points will touch an outline drawn by a wide pen than will touch an outline drawn by a narrow pen.
g
[in] Optional. Pointer to a Graphics object that specifies a world-to-device transformation. If the value of this parameter is NULL, the test is done in world coordinates; otherwise, the test is done in device coordinates. The default value is NULL.

Return Values

If the test point touches the outline of this path, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates an elliptical path and draws that path with a wide yellow pen. Then the code tests each point in an array to see whether the point touches the outline (as it would be drawn by the wide yellow pen) of the path. Points that touch the outline are painted green, and points that don't touch the outline are painted red.

VOID Example_IsOutlineVisibleExample(HDC hdc)
{
   Graphics graphics(hdc);

   INT j;
   Pen yellowPen(Color(255, 255, 255, 0), 20);
   SolidBrush brush(Color(255, 255, 0,  0));

   // Create and draw a path.
   GraphicsPath path;
   path.AddEllipse(50, 50, 200, 100);
   graphics.DrawPath(&yellowPen, &path);

   // Create an array of three points, and determine whether each
   // point in the array touches the outline of the path.
   // If a point touches the outline, paint it green.
   // If a point does not touch the outline, paint it red.
   Point points[] = {
      Point(230, 138),
      Point(100, 120),
      Point(150, 170)};

   for(j = 0; j <= 2; ++j)
   {
      if(path.IsOutlineVisible(points[j].X, points[j].Y, &yellowPen, NULL))
         brush.SetColor(Color(255, 0, 255,  0));
      else
         brush.SetColor(Color(255, 255, 0,  0));

      graphics.FillEllipse(&brush, points[j].X - 3, points[j].Y - 3, 6, 6);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Graphics Class, IsOutlineVisible Methods, IsVisible Methods, Pen, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Setting Pen Width and Alignment
Concepts
Paths, Pens, Lines, and Rectangles


GraphicsPath::IsOutlineVisible(REAL x, REAL y, Pen* pen, Graphics* g)

The IsOutlineVisible method determines whether a specified point touches the outline of this path when the path is drawn by a specified Graphics object and a specified pen.

BOOL IsOutlineVisible(
  REAL x,
  REAL y,
  const Pen* pen,
  const Graphics* g
);

Parameters

x
[in] Real number that specifies the x-coordinate of the point to be tested.
y
[in] Real number that specifies the x-coordinate of the point to be tested.
pen
[in] Pointer to a Pen object. This method determines whether the test point touches the path outline that would be drawn by this pen. More points will touch an outline drawn by a wide pen than will touch an outline drawn by a narrow pen.
g
[in] Optional. Pointer to a Graphics object that specifies a world-to-device transformation. If the value of this parameter is NULL, the test is done in world coordinates; otherwise, the test is done in device coordinates. The default value is NULL.

Return Values

If the test point touches the outline of this path, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates an elliptical path and draws that path with a wide yellow pen. Then the code tests each point in an array to see whether the point touches the outline (as it would be drawn by the wide yellow pen) of the path. Points that touch the outline are painted green, and points that don't touch the outline are painted red.

VOID Example_IsOutlineVisibleExample(HDC hdc)
{
   Graphics graphics(hdc);

   INT j;
   Pen yellowPen(Color(255, 255, 255, 0), 20);
   SolidBrush brush(Color(255, 255, 0,  0));

   // Create and draw a path.
   GraphicsPath path;
   path.AddEllipse(50, 50, 200, 100);
   graphics.DrawPath(&yellowPen, &path);

   // Create an array of three points, and determine whether each
   // point in the array touches the outline of the path.
   // If a point touches the outline, paint it green.
   // If a point does not touch the outline, paint it red.
   PointF points[] = {
      PointF(230, 138),
      PointF(100, 120),
      PointF(150, 170)};

   for(j = 0; j <= 2; ++j)
   {
      if(path.IsOutlineVisible(points[j].X, points[j].Y, &yellowPen, NULL))
         brush.SetColor(Color(255, 0, 255,  0));
      else
         brush.SetColor(Color(255, 255, 0,  0));

      graphics.FillEllipse(&brush, points[j].X - 3.0f, points[j].Y - 3.0f, 6.0f, 6.0f);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Graphics Class, IsOutlineVisible Methods, IsVisible Methods, Pen, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Setting Pen Width and Alignment
Concepts
Paths, Pens, Lines, and Rectangles


GraphicsPath::IsVisible Methods

This topic lists the IsVisible methods of the GraphicsPath class. For a complete list of methods for the GraphicsPath class, see GraphicsPath Methods.

  • IsVisible(Point& point, Graphics* g)
  • IsVisible(PointF& point, Graphics* g)
  • IsVisible(INT x, INT y, Graphics* g)
  • IsVisible(REAL x, REAL y, Graphics* g)


GraphicsPath::IsVisible(Point& point, Graphics* g)

The IsVisible method determines whether a specified point lies in the area that is filled when this path is filled by a specified Graphics object.

BOOL IsVisible(
  const Point& point,
  const Graphics* g
);

Parameters

point
[in] Reference to the point to be tested.
g
[in] Optional. Pointer to a Graphics object that specifies a world-to-device transformation. If the value of this parameter is NULL, the test is done in world coordinates; otherwise, the test is done in device coordinates. The default value is NULL.

Return Values

If the test point lies in the interior of this path, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates an elliptical path and draws that path with a narrow black pen. Then the code tests each point in an array to see whether the point lies in the interior of the path. Points that lie in the interior are painted green, and points that do not lie in the interior are painted red.

VOID IsVisibleExample(HDC hdc)
{
   Graphics graphics(hdc);

   INT j;
   Pen blackPen(Color(255, 0, 0, 0), 1);
   SolidBrush brush(Color(255, 255, 0,  0));

   // Create and draw a path.
   GraphicsPath path;
   path.AddEllipse(50, 50, 200, 100);
   graphics.DrawPath(&blackPen, &path);

   // Create an array of four points, and determine whether each
   // point in the array touches the outline of the path.
   // If a point touches the outline, paint it green.
   // If a point does not touch the outline, paint it red.
   Point points[] = {
      Point(50, 100),
      Point(250, 100),
      Point(150, 170),
      Point(180, 60)};

   for(j = 0; j <= 3; ++j)
   {
      if(path.IsVisible(points[j], &graphics))
         brush.SetColor(Color(255, 0, 255,  0));
      else
         brush.SetColor(Color(255, 255, 0,  0));

      graphics.FillEllipse(&brush, points[j].X - 3, points[j].Y - 3, 6, 6);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Graphics Class, IsOutlineVisible Methods, IsVisible Methods, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::IsVisible(PointF& point, Graphics* g)

The IsVisible method determines whether a specified point lies in the area that is filled when this path is filled by a specified Graphics object.

BOOL IsVisible(
  const PointF& point,
  const Graphics* g
);

Parameters

point
[in] Reference to the point to be tested.
g
[in] Optional. Pointer to a Graphics object that specifies a world-to-device transformation. If the value of this parameter is NULL, the test is done in world coordinates; otherwise, the test is done in device coordinates. The default value is NULL.

Return Values

If the test point lies in the interior of this path, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates an elliptical path and draws that path with a narrow black pen. Then the code tests each point in an array to see whether the point lies in the interior of the path. Points that lie in the interior are painted green, and points that do not lie in the interior are painted red.

VOID IsVisibleExample(HDC hdc)
{
   Graphics graphics(hdc);

   INT j;
   Pen blackPen(Color(255, 0, 0, 0), 1);
   SolidBrush brush(Color(255, 255, 0,  0));

   // Create and draw a path.
   GraphicsPath path;
   path.AddEllipse(50, 50, 200, 100);
   graphics.DrawPath(&blackPen, &path);

   // Create an array of four points, and determine whether each
   // point in the array touches the outline of the path.
   // If a point touches the outline, paint it green.
   // If a point does not touch the outline, paint it red.
   PointF points[] = {
      PointF(50, 100),
      PointF(250, 100),
      PointF(150, 170),
      PointF(180, 60)};

   for(j = 0; j <= 3; ++j)
   {
      if(path.IsVisible(points[j], &graphics))
         brush.SetColor(Color(255, 0, 255,  0));
      else
         brush.SetColor(Color(255, 255, 0,  0));

      graphics.FillEllipse(&brush, points[j].X - 3.0f, points[j].Y - 3.0f, 6.0f, 6.0f);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Graphics Class, IsOutlineVisible Methods, IsVisible Methods, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::IsVisible(INT x, INT y, Graphics* g)

The IsVisible method determines whether a specified point lies in the area that is filled when this path is filled by a specified Graphics object.

BOOL IsVisible(
  INT x,
  INT y,
  const Graphics* g
);

Parameters

x
[in] Integer that specifies the x-coordinate of the point to be tested.
y
[in] Integer that specifies the y-coordinate of the point to be tested.
g
[in] Optional. Pointer to a Graphics object that specifies a world-to-device transformation. If the value of this parameter is NULL, the test is done in world coordinates; otherwise, the test is done in device coordinates. The default value is NULL.

Return Values

If the test point lies in the interior of this path, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates an elliptical path and draws that path with a narrow black pen. Then the code tests each point in an array to see whether the point lies in the interior of the path. Points that lie in the interior are painted green, and points that do not lie in the interior are painted red.

VOID IsVisibleExample(HDC hdc)
{
   Graphics graphics(hdc);

   INT j;
   Pen blackPen(Color(255, 0, 0, 0), 1);
   SolidBrush brush(Color(255, 255, 0,  0));

   // Create and draw a path.
   GraphicsPath path;
   path.AddEllipse(50, 50, 200, 100);
   graphics.DrawPath(&blackPen, &path);

   // Create an array of four points, and determine whether each
   // point in the array touches the outline of the path.
   // If a point touches the outline, paint it green.
   // If a point does not touch the outline, paint it red.
   Point points[] = {
      Point(50, 100),
      Point(250, 100),
      Point(150, 170),
      Point(180, 60)};

   for(j = 0; j <= 3; ++j)
   {
      if(path.IsVisible(points[j].X, points[j].Y, &graphics))
         brush.SetColor(Color(255, 0, 255,  0));
      else
         brush.SetColor(Color(255, 255, 0,  0));

      graphics.FillEllipse(&brush, points[j].X - 3, points[j].Y - 3, 6, 6);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Graphics Class, IsOutlineVisible Methods, IsVisible Methods, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::IsVisible(REAL x, REAL y, Graphics* g)

The IsVisible method determines whether a specified point lies in the area that is filled when this path is filled by a specified Graphics object.

BOOL IsVisible(
  REAL x,
  REAL y,
  const Graphics* g
);

Parameters

x
[in] Real number that specifies the x-coordinate of the point to be tested.
y
[in] Real number that specifies the y-coordinate of the point to be tested.
g
[in] Optional. Pointer to a Graphics object that specifies a world-to-device transformation. If the value of this parameter is NULL, the test is done in world coordinates; otherwise, the test is done in device coordinates. The default value is NULL.

Return Values

If the test point lies in the interior of this path, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates an elliptical path and draws that path with a narrow black pen. Then the code tests each point in an array to see whether the point lies in the interior of the path. Points that lie in the interior are painted green, and points that do not lie in the interior are painted red.

VOID IsVisibleExample(HDC hdc)
{
   Graphics graphics(hdc);

   INT j;
   Pen blackPen(Color(255, 0, 0, 0), 1);
   SolidBrush brush(Color(255, 255, 0, 0));

   // Create and draw a path.
   GraphicsPath path;
   path.AddEllipse(50, 50, 200, 100);
   graphics.DrawPath(&blackPen, &path);

   // Create an array of four points, and determine whether each
   // point in the array touches the outline of the path.
   // If a point touches the outline, paint it green.
   // If a point does not touch the outline, paint it red.
   PointF points[] = {
      PointF(50, 100),
      PointF(250, 100),
      PointF(150, 170),
      PointF(180, 60)};

   for(j = 0; j <= 3; ++j)
   {
      if(path.IsVisible(points[j].X, points[j].Y, &graphics))
         brush.SetColor(Color(255, 0, 255,  0));
      else
         brush.SetColor(Color(255, 255, 0,  0));

      graphics.FillEllipse(&brush, points[j].X - 3.0f, points[j].Y - 3.0f, 6.0f, 6.0f);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Graphics Class, IsOutlineVisible Methods, IsVisible Methods, PointF
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::Outline(matrix, flatness)

The Outline method transforms and flattens this path, and then converts this path's data points so that they represent only the outline of the path.

Status Outline(
  const Matrix* matrix,
  REAL flatness
);

Parameters

matrix
[in] Optional. Pointer to a Matrix object that specifies the transformation. If this parameter is NULL, no transformation is applied. The default value is NULL.
flatness
[in] Optional. Real number that specifies the maximum error between the path and its flattened approximation. Reducing the flatness increases the number of line segments in the approximation. The default value is FlatnessDefault, which is a constant defined in Gdiplusenums.h.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A GraphicsPath object stores a collection of data points that represent lines and curves. The Outline method changes those data points, and the original data points are lost.

Example Code [C++]

The following example creates a GraphicsPath object and calls the AddClosedCurve method to add a closed cardinal spline to the path. The code calls the Widen method to widen the path and then draws the path. Next, the code calls the path's Outline method. The code calls the TranslateTransform method of a Graphics object so that the outlined path drawn by the subsequent call to DrawPath sits to the right of the first path.

VOID OutlineExample(HDC hdc)
{
   Graphics graphics(hdc);

   Pen bluePen(Color(255, 0, 0, 255));
   Pen greenPen(Color(255, 0, 255,  0), 10);

   PointF points[] = {
      PointF(20.0f, 20.0f),
      PointF(160.0f, 100.0f),
      PointF(140.0f, 60.0f),
      PointF(60.0f, 100.0f)};

   GraphicsPath path;
   path.AddClosedCurve(points, 4);

   path.Widen(&greenPen);
   graphics.DrawPath(&bluePen, &path);

   path.Outline();

   graphics.TranslateTransform(180.0f, 0.0f);
   graphics.DrawPath(&bluePen, &path);
}

The following illustration shows the output of the preceding code. The path on the left was drawn before the call to Outline, and the path on the right was drawn after the call to Outline.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Flatten, Matrix, Warp, Widen
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::Reset()

The Reset method empties the path and sets the fill mode to FillModeAlternate.

Status Reset(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a path, adds a sequence of connected lines to the path, and then clears the path by calling the Reset method.

GraphicsPath   path;
Point pts[] = {Point(0, 0),
               Point(20, 0),
               Point(20, 40),
               Point(0, 40),
               Point(0, 0)};
path.AddLines(pts, 5);
path.Reset();

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddLines Methods, GraphicsPath Constructors, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::Reverse()

The Reverse method reverses the order of the points that define this path's lines and curves.

Status Reverse(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A GraphicsPath object has an array of points and an array of types. Each element in the array of types is a byte that specifies the point type and a set of flags for the corresponding element in the array of points. Possible point types and flags are listed in the PathPointType enumeration.

This method reverses the order of the elements in the array of points and in the array of types.

Example Code [C++]

The following example creates a GraphicsPath object path, adds two lines to path, calls the Reverse method, and then draws path.

VOID ReverseExample(HDC hdc)
{
   Graphics graphics(hdc);
   GraphicsPath path;

   // Set up and call Reverse.
   Point pts[] = {Point(10, 60),
                  Point(50, 110),
                  Point(90, 60)};
   path.AddLines(pts, 3);
   path.Reverse();

   // Draw the path.
   graphics.DrawPath(&Pen(Color(128, 255, 0, 0), 2), &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
AddLines Methods, GetPathData, GetPathPoints Methods, GetPathTypes, Point
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::SetFillMode(fillmode)

The SetFillMode method sets the fill mode of this path.

Status SetFillMode(
  FillMode fillmode
);

Parameters

fillmode
[in] Element of the FillMode enumeration that specifies how to fill areas when the path intersects itself.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
FillMode
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::SetMarker()

The SetMarker method designates the last point in this path as a marker point.

Status SetMarker(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A GraphicsPath object has an array of points and an array of types. Each element in the array of types is a byte that specifies the point type and a set of flags for the corresponding element in the array of points. Possible point types and flags are listed in the PathPointType enumeration.

Each time you add a line, curve, or shape to a path, the point array and the type array are expanded. When you call SetMarker, a marker flag is placed in the last byte of the type array. That flag designates the last point of the point array as a marker point.

Markers divide a path into sections. You can use a GraphicsPathIterator object to draw selected sections of a path.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
CloseFigure, GetPathTypes, GraphicsPathIterator, NextMarker Methods, NextSubpath Methods, StartFigure
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::StartFigure()

The StartFigure method starts a new figure without closing the current figure. Subsequent points added to this path are added to the new figure.

Status StartFigure(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a path and adds two figures to that path. The first figure has three arcs, and the second figure has two arcs. The arcs within a figure are connected by straight lines, but there is no connecting line between the last arc in the first figure and the first arc in the second figure.

VOID StartFigureExample(HDC hdc)
{
   Graphics graphics(hdc);

   Pen pen(Color(255, 0, 0, 255));
   Rect rect(0, 0, 100, 50);
   GraphicsPath path;

   path.AddArc(0, 0, 100, 50, 0.0f, 180.0f);
   path.AddArc(0, 60, 100, 50, 0.0f, 180.0f);
   path.AddArc(0, 120, 100, 50, 0.0f, 180.0f);

   // Start a new figure (subpath).
   // Do not close the current figure.
   path.StartFigure();
   path.AddArc(0, 180, 100, 50, 0.0f, 180.0f);
   path.AddArc(0, 240, 100, 50, 0.0f, 180.0f);

   graphics.DrawPath(&pen, &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
CloseFigure, GraphicsPathIterator, NextSubpath Methods
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Paths


GraphicsPath::Transform(matrix)

The Transform method multiplies each of this path's data points by a specified matrix.

Status Transform(
  const Matrix* matrix
);

Parameters

matrix
[in] Pointer to a Matrix object that specifies the transformation.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object and adds a rectangle to the path. The code draws the path, transforms the path, and then draws the path again.

VOID TransformExample(HDC hdc)
{
   Graphics graphics(hdc);

   GraphicsPath path;
   path.AddRectangle(Rect(40, 10, 200, 50));

   // Draw the path in blue before applying a transformation.
   graphics.DrawPath(&Pen(Color(255, 0, 0, 255)), &path);

   // Transform the path.
   Matrix matrix;
   matrix.Rotate(30.0f);
   path.Transform(&matrix);

   // Draw the transformed path in red.
   graphics.DrawPath(&Pen(Color(255, 255, 0,  0)), &path);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Matrix
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient, Transformations
Concepts
Matrix Representation of Transformations, Paths


GraphicsPath::Warp(destPoints, count, srcRect, matrix, warpMode, flatness)

The Warp method applies a warp transformation to this path. The Warp method also flattens (converts to a sequence of straight lines) the path.

Status Warp(
  const PointF* destPoints,
  INT count,
  const RectF& srcRect,
  const Matrix* matrix,
  WarpMode warpMode,
  REAL flatness
);

Parameters

destPoints
[in] Pointer to an array of points that, along with the srcRect parameter, defines the warp transformation.
count
[in] Integer that specifies the number of points in the destPoints array. The value of this parameter must be 3 or 4.
srcRect
[in] Reference to a rectangle that, along with the destPoints parameter, defines the warp transformation.
matrix
[in] Optional. Pointer to a Matrix object that represents a transformation to be applied along with the warp. If this parameter is NULL, no transformation is applied. The default value is NULL.
warpMode
[in] Optional. Element of the WarpMode enumeration that specifies the kind of warp to be applied. The default value is WarpModePerspective.
flatness
[in] Optional. Real number that influences the number of line segments that are used to approximate the original path. Small values specify that many line segments are used, and large values specify that few line segments are used. The default value is FlatnessDefault, which is a constant defined in Gdiplusenums.h.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A GraphicsPath object stores a collection of data points that represent lines and curves. The Warp method converts those data points so that they represent only lines. The flatness parameter influences the number of lines that are stored. The original data points that represented curves are lost.

If the count parameter has a value of 4, the warp transformation is defined as shown in the following table.

Source point | Destination point
Upper-left corner of srcRect | destPoints[0]
Upper-right corner of srcRect | destPoints[1]
Lower-left corner of srcRect | destPoints[2]
Lower-right corner of srcRect | destPoints[3]

A transformation specified by a source rectangle and four destination points is capable of mapping a rectangle to an arbitrary quadrilateral that is not necessarily a parallelogram.

If the count parameter has a value of 3, the warp transformation is defined as shown in the following table.

Source point | Destination point
Upper-left corner of srcRect | destPoints[0]
Upper-right corner of srcRect | destPoints[1]
Lower-left corner of srcRect | destPoints[2]

A transformation specified by a source rectangle and three destination points maps rectangles to parallelograms.

Example Code [C++]

The following example creates a GraphicsPath object and adds a closed figure to the path. The code defines a warp transformation by specifying a source rectangle and an array of four destination points. The source rectangle and destination points are passed to the Warp method. The code draws the path twice: once before it has been warped and once after it has been warped.

VOID WarpExample(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path.
   PointF points[] ={
      PointF(20.0f, 60.0f),
      PointF(30.0f, 90.0f),
      PointF(15.0f, 110.0f),
      PointF(15.0f, 145.0f),
      PointF(55.0f, 145.0f),
      PointF(55.0f, 110.0f),
      PointF(40.0f, 90.0f),
      PointF(50.0f, 60.0f)};

   GraphicsPath path;
   path.AddLines(points, 8);
   path.CloseFigure();

   // Draw the path before applying a warp transformation.
   Pen bluePen(Color(255, 0, 0, 255));
   graphics.DrawPath(&bluePen, &path);

   // Define a warp transformation, and warp the path.
   RectF srcRect(10.0f, 50.0f, 50.0f, 100.0f);

   PointF destPts[] = {
      PointF(220.0f, 10.0f),
      PointF(280.0f, 10.0f),
      PointF(100.0f, 150.0f),
      PointF(400.0f, 150.0f)};

   path.Warp(destPts, 4, srcRect);

   // Draw the warped path.
   graphics.DrawPath(&bluePen, &path);

   // Draw the source rectangle and the destination polygon.
   Pen blackPen(Color(255, 0, 0, 0));
   graphics.DrawRectangle(&blackPen, srcRect);
   graphics.DrawLine(&blackPen, destPts[0], destPts[1]);
   graphics.DrawLine(&blackPen, destPts[0], destPts[2]);
   graphics.DrawLine(&blackPen, destPts[1], destPts[3]);
   graphics.DrawLine(&blackPen, destPts[2], destPts[3]);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Flatten, Matrix, Outline, Widen, WarpMode
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Flattening Paths, Paths


GraphicsPath::Widen(pen, matrix, flatness)

The Widen method replaces this path with curves that enclose the area that is filled when this path is drawn by a specified pen. The Widen method also flattens the path.

Status Widen(
  const Pen* pen,
  const Matrix* matrix,
  REAL flatness
);

Parameters

pen
[in] Pointer to a Pen object. The path is made as wide as it would be when drawn by this pen.
matrix
[in] Optional. Pointer to a Matrix object that specifies a transformation to be applied along with the widening. If this parameter is NULL, no transformation is applied. The default value is NULL.
flatness
[in] Optional. Real number that specifies the maximum error between the path and its flattened approximation. Reducing the flatness increases the number of line segments in the approximation. The default value is FlatnessDefault, which is a constant defined in Gdiplusenums.h.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object and adds a closed curve to the path. The code creates a green pen that has a width of 10 and passes the address of that pen to the Widen method. Then the code draws the path with a blue pen of width 1.

VOID WidenExample(HDC hdc)
{
   Graphics graphics(hdc);
   Pen bluePen(Color(255, 0, 0, 255));
   Pen greenPen(Color(255, 0, 255,  0), 10);

   PointF points[] = {
      PointF(20.0f, 20.0f),
      PointF(160.0f, 100.0f),
      PointF(140.0f, 60.0f),
      PointF(60.0f, 100.0f)};

   GraphicsPath path;
   path.AddClosedCurve(points, 4);
   path.Widen(&greenPen);
   graphics.DrawPath(&bluePen, &path);
}

The following illustration shows the output of the preceding code. Note that although the green pen is used to specify the extent of the widening, the green pen is not used to draw the path. The path is drawn by a blue pen that has a width of 1.

The Widen method respects the dash style of the specified pen (the green pen in this case). If you add the statement greenPen.SetDashStyle(DashStyleDash); to the preceding code before the call to Widen, you will get the following output.

The Widen method also respects the transformation of the specified pen. In the preceding code, replace the statement Pen greenPen(Color(255, 0, 255, 0), 10); with the following two statements:

Pen greenPen(Color(255, 0, 255, 0));
greenPen.ScaleTransform(3.0f, 20.0f);

Then you will get the output shown in the following illustration. Note that the width changes as you move along the path. That is because the green pen is wider vertically that it is horizontally.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Flatten, Matrix, Outline, Pen, Widen
Tasks and Examples
Clipping with a Region, Constructing and Drawing Paths, Creating a Path Gradient
Concepts
Flattening Paths, Paths


GraphicsPathIterator Class

This GraphicsPathIterator class provides methods for isolating selected subsets of the path stored in a GraphicsPath object. A path consists of one or more figures. You can use a GraphicsPathIterator to isolate one or more of those figures. A path can also have markers that divide the path into sections. You can use a GraphicsPathIterator object to isolate one or more of those sections.

Inheritance

GdiplusBase
GraphicsPathIterator

Constructors

Constructor | Description
GraphicsPathIterator | Creates and initializes a new GraphicsPathIterator object.

Methods

Method | Description
CopyData | Copies a specified subset of the path data.
Enumerate | Gets the path data.
GetCount | Gets the number of data points in the path.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetSubpathCount | Gets the number of subpaths in the path.
HasCurve | Determines whether the path has at least one curve.
NextMarker | Overloaded. Gets the next marker-delimited section of the path.
NextPathType | Gets the next group of path data points that all have the same type.
NextSubPath | Overloaded. Gets the next figure in the path.
Rewind | Rewinds the iterator to the beginning of the path.
~GraphicsPathIterator | GraphicsPathIterator object destructor.


GraphicsPathIterator::GraphicsPathIterator(path)

Creates a new GraphicsPathIterator object and associates it with a GraphicsPath object.

GraphicsPathIterator(
  GraphicsPath* path
);

Parameters

path
[in] Pointer to a GraphicsPath object that will be associated with this GraphicsPathIterator object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GraphicsPath


GraphicsPathIterator Methods

This topic lists the methods of the GraphicsPathIterator class. For a complete class listing, see GraphicsPathIterator Class.

  • CopyData(points, types, startIndex, endIndex)
  • Enumerate(points, types, count)
  • GetCount()
  • GetLastStatus()
  • GetSubpathCount()
  • HasCurve()
  • NextMarker(path)
  • NextMarker(startIndex, endIndex)
  • NextPathType(pathType, startIndex, endIndex)
  • NextSubpath(path, isClosed)
  • NextSubpath(startIndex, endIndex, isClosed)
  • Rewind()


GraphicsPathIterator::CopyData(points, types, startIndex, endIndex)

The CopyData method copies a subset of the path's data points to a PointF array and copies a subset of the path's point types to a BYTE array.

INT CopyData(
  PointF* points,
  BYTE* types,
  INT startIndex,
  INT endIndex
);

Parameters

points
[out] Pointer to an array that receives a subset of the path's data points.
types
[out] Pointer to an array that receives a subset of the path's point types.
startIndex
[in] Integer that specifies the starting index of the points and types to be copied.
endIndex
[in] Integer that specifies the ending index of the points and types to be copied.

Return Values

This method returns the number of points copied. This is the same as the number of types copied.

Remarks

This GraphicsPathIterator object is associated with a GraphicsPath object. That GraphicsPath object has an array of points and an array of types. Each element in the array of types is a byte that specifies the point type and a set of flags for the corresponding element in the array of points. Possible point types and flags are listed in the PathPointType enumeration.

You can call the GraphicsPathIterator::GetCount method to determine the number of data points in the path.

Example Code [C/C++]

The following example creates a GraphicsPath object and adds three lines to the path. The code creates a GraphicsPathIterator object and calls its CopyData method to retrieve the path's points and point types. Then the code displays the count returned by the CopyData method.

// String for MessageBox display
TCHAR numPointsCopied[24];

// Create the points for three lines in a path.
Point pts[] = {Point(20, 20),
               Point(100, 20),
               Point(100, 50),
               Point(20, 50)};

GraphicsPath path;
path.AddLines(pts, 4); // Add the lines to the path.

// Create a GraphicsPathIterator object, and associate it with the path.
GraphicsPathIterator pathIterator(&path);

// Create destination arrays, and copy the path data to them.
PointF* pCopiedPoints = new PointF[4];
BYTE* pTypes = new BYTE[4];
INT count = pathIterator.CopyData(pCopiedPoints, pTypes, 0, 3);

// Confirm that the points were copied.
wsprintf(numPointsCopied, TEXT("%d points were copied."), count);
MessageBox(NULL, numPointsCopied, TEXT("CopyData"), 0);

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Enumerate, GetCount, GetPathData, GetPathPoints Methods, GetPathTypes, GetPointCount, GraphicsPath
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


GraphicsPathIterator::Enumerate(points, types, count)

The Enumerate method copies the path's data points to a PointF array and copies the path's point types to a BYTE array.

INT Enumerate(
  PointF* points,
  BYTE* types,
  INT count
);

Parameters

points
[out] Pointer to an array that receives the path's data points.
types
[out] Pointer to an array that receives the path's point types.
count
[in] Integer that specifies the number of elements in the points array. This is the same as the number of elements in the types array.

Return Values

This method returns the number of points retrieved.

Remarks

This GraphicsPathIterator object is associated with a GraphicsPath object. That GraphicsPath object has an array of points and an array of types. Each element in the array of types is a byte that specifies the point type and a set of flags for the corresponding element in the array of points. Possible point types and flags are listed in the PathPointType enumeration.

You can call the GraphicsPathIterator::GetCount method to determine the number of data points in the path. The points parameter points to a buffer that receives the data points, and the types parameter points to a buffer that receives the types. Before you call the Enumerate method, you must allocate memory for those buffers. The size of the points buffer should be the return value of GetCount multiplied by sizeof(PointF). The size of the types buffer should be the return value of GetCount.

Example Code [C/C++]

The following example creates a GraphicsPath object and adds three lines to the path. The code creates a GraphicsPathIterator object and calls its Enumerate method to retrieve the path's data points and point types. Then the code displays the count returned by the Enumerate method.

// String for MessageBox display
TCHAR numPointsEnum[24];

// Create four lines in a path.
Point pts[] = {Point(20, 20),
               Point(100, 20),
               Point(100, 50),
               Point(20, 50)};

GraphicsPath path;
path.AddLines(pts, 4);

// Create a GraphicsPathIterator object, and associate it with the path.
GraphicsPathIterator pathIterator(&path);

// Create destination arrays, and copy the path data to them.
PointF* pEnumPoints = new PointF[4];
BYTE* pTypes = new BYTE[4];
INT count = pathIterator.Enumerate(pEnumPoints, pTypes, 4);

// Confirm that the points were enumerated.
wsprintf(numPointsEnum, TEXT("%d points were enumerated."), count);
MessageBox(NULL, numPointsEnum, TEXT("Enumerate"), 0);

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
CopyData, GetCount, GetPathData, GetPathPoints Methods, GetPathTypes, GetPointCount, GraphicsPath
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


GraphicsPathIterator::GetCount()

The GetCount method returns the number of data points in the path.

INT GetCount(void);

Parameters

This method has no parameters.

Return Values

This method returns the number of data points in the path.

Remarks

This GraphicsPathIterator object is associated with a GraphicsPath object. That GraphicsPath object has an array of points and an array of types. Each element in the array of types is a byte that specifies the point type and a set of flags for the corresponding element in the array of points. Possible point types and flags are listed in the PathPointType enumeration.

Example Code [C/C++]

The following example creates a GraphicsPath object and then adds a rectangle and an ellipse to the path. The code passes the address of that GraphicsPath object to a GraphicsPathIterator constructor to create an iterator that is associated with the path. The code calls the iterator's GetCount method to determine the number of data points in the path. The call to Enumerate retrieves two arrays from the path: one that holds the path's data points and one that holds the path's point types. After the data points have been retrieved, the code calls the FillEllipse method of a Graphics object to draw each of the data points.

VOID GetCountExample(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that has a rectangle and an ellipse.
   GraphicsPath path;
   path.AddRectangle(Rect(20, 20, 60, 30));
   path.AddEllipse(Rect(20, 70, 100, 50));

   // Create an iterator, and associate it with the path.
   GraphicsPathIterator iterator(&path);

   // Get the number of data points in the path.
   INT count = iterator.GetCount();

   // Get the data points.
   PointF* points = new PointF[count];
   BYTE* types = new BYTE[count];
   iterator.Enumerate(points, types, count);

   // Draw the data points.
   SolidBrush brush(Color(255, 255, 0, 0));
   for(INT j = 0; j < count; ++j)
      graphics.FillEllipse(
         &brush,
         points[j].X - 3.0f,
         points[j].Y - 3.0f,
         6.0f,
         6.0f);

   delete points;
   delete types;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
CopyData, Enumerate, GetPathData, GetPathPoints Methods, GetPathTypes, GetPointCount, GraphicsPath
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


GraphicsPathIterator::GetLastStatus()

The GetLastStatus method returns a value that indicates the nature of this GraphicsPathIterator object's most recent method failure.

Status GetLastStatus(void);

Parameters

This method has no parameters.

Return Values

The GetLastStatus method returns an element of the Status enumeration.

If no methods invoked on this GraphicsPathIterator object have failed since the previous call to GetLastStatus, then GetLastStatus returns Ok.

If at least one method invoked on this GraphicsPathIterator object has failed since the previous call to GetLastStatus, then GetLastStatus returns a value that indicates the nature of the most recent failure.

Remarks

You can call GetLastStatus immediately after constructing a GraphicsPathIterator object to determine whether the constructor succeeded.

The first time you call the GetLastStatus method of a GraphicsPathIterator object, it returns Ok if the constructor succeeded and all methods invoked so far on the GraphicsPathIterator object succeeded. Otherwise, it returns a value that indicates the nature of the most recent failure.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Status
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


GraphicsPathIterator::GetSubpathCount()

The GetSubpathCount method returns the number of subpaths (also called figures) in the path.

INT GetSubpathCount(void);

Parameters

This method has no parameters.

Return Values

This method returns the number of subpaths (also called figures) in the path.

Example Code [C/C++]

The following example creates a GraphicsPath object and adds three subpaths (figures) to the path. The code creates a GraphicsPathIterator object and calls its GetSubpathCount method to determine the number of subpaths in the path. Then the code displays the count.

// String for MessageBox
TCHAR numSubpaths[24];

Point pts[] = {Point(20, 20),
               Point(40, 20),
               Point(40, 40)};

GraphicsPath     path;
path.AddLines(pts, 3);

path.StartFigure();
path.AddLine(20, 20, 100, 100);

path.StartFigure();
Rect rect(20, 20, 100, 50);
path.AddRectangle(rect);

// Create a GraphicsPathIterator object, and get the number of subpaths.
GraphicsPathIterator pathIterator(&path);
INT subpathCount = pathIterator.GetSubpathCount();

// Confirm that the subpaths were counted correctly.
wsprintf(numSubpaths, TEXT("There are %d subpaths."), subpathCount);
MessageBox(NULL, numSubpaths, TEXT("SubpathCount"), 0);

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
CloseFigure, GraphicsPath, NextSubpath Methods, StartFigure
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


GraphicsPathIterator::HasCurve()

The HasCurve method determines whether the path has any curves.

BOOL HasCurve(void);

Parameters

This method has no parameters.

Return Values

If the path has at least one curve, this method returns TRUE; otherwise, it returns FALSE.

Remarks

All curves in a path are stored as sequences of Bézier splines. For example, when you add an ellipse to a path, you specify the upper-left corner, the width, and the height of the ellipse's bounding rectangle. Those numbers (upper-left corner, width, and height) are not stored in the path; instead; the ellipse is converted to a sequence of four Bézier splines. The path stores the endpoints and control points of those Bézier splines.

A path stores an array of data points, each of which belongs to a line or a Bézier spline. If some of the points in the array belong to Bézier splines, then HasCurve returns TRUE. If all points in the array belong to lines, then HasCurve returns FALSE.

Certain methods flatten a path, which means that all the curves in the path are converted to sequences of lines. After a path has been flattened, HasCurve will always return FALSE. Flattening happens when you call the Flatten, Widen, or Warp method of the GraphicsPath class.

Example Code [C/C++]

The following example creates a GraphicsPath object and adds a cardinal spline (AddCurve) to the path. The code creates a GraphicsPathIterator object and calls its HasCurve method to determine whether there is a curve in the path.

// Create an array of points for the curve.
Point points[] = {Point(40, 60), Point(50, 70), Point(30, 90)};

// Create a path and add a curve.
GraphicsPath path;
path.AddCurve(points, 3);

// Determine whether the path has a curve.
GraphicsPathIterator pathIterator(&path);
BOOL isCurve = pathIterator.HasCurve();

// Display the result.
if(isCurve == TRUE)
   MessageBox(NULL, TEXT("There is a curve"), TEXT("HasCurve"), 0);
else
   MessageBox(NULL, TEXT("There is no curve"), TEXT("HasCurve"), 0);

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
CopyData, Flatten, GraphicsPath, Widen, Warp
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


GraphicsPathIterator::NextMarker Methods

This topic lists the NextMarker methods of the GraphicsPathIterator class. For a complete list of methods for the GraphicsPathIterator class, see GraphicsPathIterator Methods.

  • NextMarker(path)
  • NextMarker(startIndex, endIndex)


GraphicsPathIterator::NextMarker(path)

The NextMarker method gets the next marker-delimited section of this iterator's associated path.

INT NextMarker(
  GraphicsPath* path
);

Parameters

path
[out] Pointer to a GraphicsPath object. This method sets the data points of this GraphicsPath object to match the data points of the retrieved section.

Return Values

This method returns the number of data points in the retrieved section. If there are no more marker-delimited sections to retrieve, this method returns 0.

Remarks

A path has an array of data points that define its lines and curves. You can call a path's SetMarker method to designate certain points in the array as markers. Those marker points divide the path into sections.

The first time you call the NextMarker method of an iterator, it gets the first marker-delimited section of that iterator's associated path. The second time, it gets the second section, and so on. Each time you call NextSubpath, it returns the number of data points in the retrieved section. When there are no sections remaining, it returns 0.

Example Code [C++]

The following example creates a GraphicsPath object and adds five figures to the path. The calls to the SetMarker method place two markers in the path. The first marker is at the end of a figure, and the second marker is in the middle of a figure. The code passes the address of the GraphicsPath object to a GraphicsPathIterator constructor to create an iterator that is associated with the path. Then the code calls the iterator's NextMarker method twice to obtain the second marker-delimited section of the path. Finally, the code draws the retrieved section of the path.

VOID NextMarkerExample(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a graphics path with five figures (subpaths).
   GraphicsPath path;

   path.AddRectangle(Rect(20, 20, 60, 30));
   path.SetMarker();                          // first marker

   path.AddLine(100, 20, 160, 50);
   path.AddArc(180, 20, 60, 30, 0.0f, 180.0f);

   path.AddRectangle(Rect(260, 20, 60, 30));

   path.AddLine(340, 20, 400, 50);
   path.SetMarker();                          // second marker
   path.AddArc(340, 20, 60, 30, 0.0f, 180.0f);
   path.CloseFigure();

   path.AddRectangle(Rect(420, 20, 60, 30));

   // Create an iterator, and associate it with the path.
   GraphicsPathIterator iterator(&path);

   // Get the second marker-delimited section by calling NextMarker twice.
   GraphicsPath section;
   INT count;
   count = iterator.NextMarker(&section);
   count = iterator.NextMarker(&section);

   // The variable "count" now holds the number of
   // data points in the second marker-delimited section.

   // Draw the retrieved section.
   Pen bluePen(Color(255, 0, 0, 255));
   graphics.DrawPath(&bluePen, &section);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetPathData, GraphicsPath, NextMarker Methods, NextSubpath Methods
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


GraphicsPathIterator::NextMarker(startIndex, endIndex)

The NextMarker method gets the starting index and the ending index of the next marker-delimited section in this iterator's associated path.

INT NextMarker(
  INT* startIndex,
  INT* endIndex
);

Parameters

startIndex
[out] Pointer to an INT that receives the starting index.
endIndex
[out] Pointer to an INT that receives the ending index.

Return Values

This method returns the number of data points in the retrieved section. If there are no more marker-delimited sections to retrieve, this method returns 0.

Remarks

A path has an array of data points that define its lines and curves. You can call a path's SetMarker method to designate certain points in the array as markers. Those marker points divide the path into sections.

The first time you call the NextMarker method of an iterator, it gets the first marker-delimited section of that iterator's associated path. The second time, it gets the second section, and so on. Each time you call NextSubpath, it returns the number of data points in the retrieved section. When there are no sections remaining, it returns 0.

Example Code [C++]

The following example creates a GraphicsPath object and adds five figures to the path. The calls to the SetMarker method place two markers in the path. The first marker is at the end of a figure, and the second marker is in the middle of a figure. The code passes the address of the GraphicsPath object to a GraphicsPathIterator constructor to create an iterator that is associated with the path. Then the code calls the iterator's NextMarker method twice to obtain the starting and ending indices of the second marker-delimited section of the path. Finally, the code draws the data points that belong to the second marker-delimited section of the path.

VOID NextMarkerExample2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a graphics path with five figures (subpaths).
   GraphicsPath path;

   path.AddRectangle(Rect(20, 20, 60, 30));

   path.SetMarker();                          // first marker
   path.AddLine(100, 20, 160, 50);
   path.AddArc(180, 20, 60, 30, 0, 180);

   path.AddRectangle(Rect(260, 20, 60, 30));
   path.AddLine(340, 20, 400, 50);
   path.SetMarker();                          // second marker
   path.AddArc(340, 20, 60, 30, 0, 180);
   path.CloseFigure();

   path.AddRectangle(Rect(420, 20, 60, 30));

   // Create an iterator, and associate it with the path.
   GraphicsPathIterator iterator(&path);

   // Get the second marker-delimited section by calling NextMarker twice.
   INT start;
   INT end;
   INT count;
   count = iterator.NextMarker(&start, &end);
   count = iterator.NextMarker(&start, &end);

   // Get the data points of the second marker-delimited section.
   PointF* points = new PointF[count];
   BYTE* types = new BYTE[count];
   iterator.CopyData(points, types, start, end);

   // Draw the data points of the second marker-delimited section.
   SolidBrush brush(Color(255, 255, 0, 0));
   for(INT j = 0; j < count; ++j)
      graphics.FillEllipse(
         &brush,
         points[j].X - 3.0f,
         points[j].Y - 3.0f,
         6.0f,
         6.0f);

   delete points;
   delete types;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
CopyData, GraphicsPath, NextMarker Methods, NextSubpath Methods
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


GraphicsPathIterator::NextPathType(pathType, startIndex, endIndex)

The NextPathType method gets the starting index and the ending index of the next group of data points that all have the same type.

INT NextPathType(
  BYTE* pathType,
  INT* startIndex,
  INT* endIndex
);

Parameters

pathType
[out] Pointer to a BYTE that receives the point type shared by all points in the group. Possible values are PathPointTypeLine and PathPointTypeBezier, which are elements of the PathPointType enumeration.
startIndex
[out] Pointer to an INT that receives the starting index of the group of points.
endIndex
[out] Pointer to an INT that receives the ending index of the group of points.

Return Values

This method returns the number of data points in the group. If there are no more groups in the path, this method returns 0.

Remarks

A path has an array of data points that define its lines and curves. All curves in the path are represented as Bézier splines, so a given point in the array has one of two types: PathPointTypeLine or PathPointTypeBezier.

The first time you call the NextSubpath method of an iterator, it gets the starting and ending indices of the first group of points that all have the same type. The second time, it gets the second group, and so on. Each time you call NextSubpath, it returns the number of data points in the obtained group. When there are no groups remaining, it returns 0.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
CopyData, GraphicsPath, NextMarker Methods, NextSubpath Methods
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


GraphicsPathIterator::NextSubpath Methods

This topic lists the NextSubpath methods of the GraphicsPathIterator class. For a complete list of methods for the GraphicsPathIterator class, see GraphicsPathIterator Methods.

  • NextSubpath(path, isClosed)
  • NextSubpath(startIndex, endIndex, isClosed)


GraphicsPathIterator::NextSubpath(path, isClosed)

The NextSubpath method gets the next figure (subpath) from this iterator's associated path.

INT NextSubpath(
  GraphicsPath* path,
  BOOL* isClosed
);

Parameters

path
[out] Pointer to a GraphicsPath object. This method sets the data points of this GraphicsPath object to match the data points of the retrieved figure.
isClosed
[out] Pointer to a BOOL that receives a value that indicates whether the retrieved figure is closed. If the figure is closed, the received value is TRUE; otherwise, the received value is FALSE.

Return Values

This method returns the number of data points in the retrieved figure. If there are no more figures to retrieve, this method returns 0.

Remarks

The first time you call the NextSubpath method of an iterator, it gets the first figure (subpath) of that iterator's associated path. The second time, it gets the second figure, and so on. Each time you call NextSubpath, it returns the number of data points in the retrieved figure. When there are no figures remaining, it returns 0.

Example Code [C++]

The following example creates a GraphicsPath object and adds five figures (also called subpaths) to the path. The code passes the address of the GraphicsPath object to a GraphicsPathIterator constructor to create an iterator that is associated with the path. The code calls the iterator's NextSubpath method twice to retrieve the second figure (subpath) from the path. Then the code calls the DrawPath method of a Graphics object to draw that individual subpath.

VOID NextSubpathExample(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a graphics path with five figures (subpaths).
   GraphicsPath path;

   path.AddRectangle(Rect(20, 20, 60, 30));   // Subpath count is 1.

   path.AddLine(100, 20, 160, 50);            // Subpath count is 2.
   path.AddArc(180, 20, 60, 30, 0.0f, 180.0f);

   path.AddRectangle(Rect(260, 20, 60, 30));  // Subpath count is 3.

   path.AddLine(340, 20, 400, 50);            // Subpath count is 4.
   path.AddArc(340, 20, 60, 30, 0.0f, 180.0f);
   path.CloseFigure();

   path.AddRectangle(Rect(420, 20, 60, 30));  // Subpath count is 5.

   // Create an iterator, and associate it with the path.
   GraphicsPathIterator iterator(&path);

   // Get the second subpath by calling NextSubpath twice.
   GraphicsPath subpath;
   BOOL isClosed;
   INT count;
   count = iterator.NextSubpath(&subpath, &isClosed);
   count = iterator.NextSubpath(&subpath, &isClosed);

   // The variable "count" now holds the number of
   // data points in the second subpath.

   // Draw the retrieved subpath.
   Pen bluePen(Color(255, 0, 0, 255));
   graphics.DrawPath(&bluePen, &subpath);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetPathData, GetSubpathCount, GraphicsPath, NextMarker Methods, NextSubpath Methods
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


GraphicsPathIterator::NextSubpath(startIndex, endIndex, isClosed)

The NextSubpath method gets the starting index and the ending index of the next subpath (figure) in this iterator's associated path.

INT NextSubpath(
  INT* startIndex,
  INT* endIndex,
  BOOL* isClosed
);

Parameters

startIndex
[out] Pointer to an INT that receives the starting index.
endIndex
[out] Pointer to an INT that receives the ending index.
isClosed
[out] Pointer to a BOOL that receives a value that indicates whether the obtained figure is closed. If the figure is closed, the received value is TRUE; otherwise, the received value is FALSE.

Return Values

This method returns the number of data points in the next figure. If there are no more figures in the path, this method returns 0.

Remarks

The first time you call the NextSubpath method of an iterator, it gets the indices for the first figure (subpath) of that iterator's associated path. The second time, it gets the indices for the second figure, and so on. Each time you call NextSubpath, it returns the number of data points in the figure whose indices were retrieved. When there are no figures remaining, it returns 0.

Example Code [C++]

The following example creates a GraphicsPath object and adds five figures to the path. The code passes the address of that GraphicsPath object to a GraphicsPathIterator constructor to create an iterator that is associated with the path. The code calls the iterator's NextSubpath method three times to obtain the starting index and the ending index of the path's third figure. Then the code calls the iterator's CopyData method to retrieve the third figure's data points.

VOID NextSubpathExample2(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a graphics path with five figures (subpaths).
   GraphicsPath path;

   path.AddRectangle(Rect(20, 20, 60, 30));   // Subpath count is 1.

   path.AddLine(100, 20, 160, 50);            // Subpath count is 2.
   path.AddArc(180, 20, 60, 30, 0.0f, 180.0f);

   path.AddRectangle(Rect(260, 20, 60, 30));  // Subpath count is 3.

   path.AddLine(340, 20, 400, 50);            // Subpath count is 4.
   path.AddArc(340, 20, 60, 30, 0.0f, 180.0f);
   path.CloseFigure();

   path.AddRectangle(Rect(420, 20, 60, 30));  // Subpath count is 5.

   // Create an iterator, and associate it with the path.
   GraphicsPathIterator iterator(&path);

   // Call NextSubpath three times to get the starting and ending
   // indices for the third figure.
   INT start;
   INT end;
   BOOL isClosed;
   INT count;
   count = iterator.NextSubpath(&start, &end, &isClosed);
   count = iterator.NextSubpath(&start, &end, &isClosed);
   count = iterator.NextSubpath(&start, &end, &isClosed);

   // Get the third figure's data points.
   PointF* points = new PointF[count];
   BYTE* types = new BYTE[count];
   iterator.CopyData(points, types, start, end);

   // Draw the third figure's data points.
   SolidBrush brush(Color(255, 255, 0, 0));
   for(INT j = 0; j < count; ++j)
      graphics.FillEllipse(
         &brush,
         points[j].X - 3.0f,
         points[j].Y - 3.0f,
         6.0f,
         6.0f);

   delete points;
   delete types;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
CopyData, GetPathData, GetSubpathCount, GraphicsPath, NextMarker Methods, NextSubpath Methods
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


GraphicsPathIterator::Rewind()

The Rewind method rewinds this iterator to the beginning of its associated path.

VOID Rewind(void);

Parameters

This method has no parameters.

Return Values

This method does not return a value.

Remarks

The first time you call the NextSubpath method of an iterator, it gets the first figure (subpath) of that iterator's associated path. The second time, it gets the second figure, and so on. When you call Rewind, the sequence starts over; that is, after you call Rewind, the next call to NextSubpath gets the first figure in the path. The NextMarker and NextPathType methods behave similarly.

Example Code [C/C++]

The following example creates a GraphicsPath object and adds five figures to the path. The code passes the address of that GraphicsPath object to a GraphicsPathIterator constructor to create an iterator that is associated with the path. The code calls the iterator's NextSubpath method twice to retrieve the second figure in the path. The Graphics::DrawPath method draws that path in blue. Next, the code calls the Rewind method and then calls NextSubpath once to obtain the first figure in the path. The Graphics::DrawPath method draws that figure in red.

VOID RewindExample(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a graphics path with five figures (subpaths).
   GraphicsPath path;

   path.AddRectangle(Rect(20, 20, 60, 30));   // Subpath count is 1.

   path.AddLine(100, 20, 160, 50);            // Subpath count is 2.
   path.AddArc(180, 20, 60, 30, 0.0f, 180.0f);

   path.AddRectangle(Rect(260, 20, 60, 30));  // Subpath count is 3.

   path.AddLine(340, 20, 400, 50);            // Subpath count is 4.
   path.AddArc(340, 20, 60, 30, 0.0f, 180.0f);
   path.CloseFigure();

   path.AddRectangle(Rect(420, 20, 60, 30));  // Subpath count is 5.

   // Create an iterator, and associate it with the path.
   GraphicsPathIterator iterator(&path);

   // Get the second subpath by calling NextSubpath twice.
   GraphicsPath subpath;
   BOOL isClosed;
   INT count;
   count = iterator.NextSubpath(&subpath, &isClosed);
   count = iterator.NextSubpath(&subpath, &isClosed);

   // Draw the second figure in blue.
   Pen bluePen(Color(255, 0, 0, 255));
   graphics.DrawPath(&bluePen, &subpath);

   // Rewind the iterator, and get the first figure in the path.
   iterator.Rewind();
   count = iterator.NextSubpath(&subpath, &isClosed);

   // Draw the first figure in red.
   Pen redPen(Color(255, 255, 0, 0));
   graphics.DrawPath(&redPen, &subpath);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, NextMarker Methods, NextPathType, NextSubpath Methods
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


HatchBrush Class

This HatchBrush class defines a rectangular brush with a hatch style, a foreground color, and a background color. There are six hatch styles. The foreground color defines the color of the hatch lines; the background color defines the color over which the hatch lines are drawn.

Inheritance

GdiplusBase
Brush
HatchBrush

Constructors

Constructor | Description
HatchBrush | Initializes a new HatchBrush object.

Methods

Uninherited

Method | Description
GetBackgroundColor | Gets the background color.
GetForegroundColor | Gets the foreground color.
GetHatchStyle | Gets the hatch style.

Inherited from Brush

Method | Description
Clone | Creates a new Brush object based on this brush.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetType | Gets the type of this brush.

Remarks

Hatches are applied to shape interiors in the device space. As a result, they maintain their appearance in device space and are unaffected by current transformations in the graphics context. Such brushes are also called nonscalable brushes. Hatches are aligned at the upper-left corner of the display device. When the graphics engine uses a HatchBrush object to paint a shape, it first transforms the shape to device space before applying the hatch to the interiors. Hatches are always tiled to paint the interiors.


HatchBrush::HatchBrush(hatchStyle, foreColor, backColor)

Creates a HatchBrush object based on a hatch style, a foreground color, and a background color.

HatchBrush(
  HatchStyle hatchStyle,
  const Color& foreColor,
  const Color& backColor
);

Parameters

hatchStyle
[in] Element of the HatchStyle enumeration that specifies the pattern of hatch lines that will be used.
foreColor
[in] Reference to a color to use for the hatch lines.
backColor
[in] Optional. Reference to a color to use for the background. The default value is Color() (a Color object created by the default Color constructor).

Return Values

This method does not return a value.

Example Code [C++]

The following example draws six of the available hatch styles.

VOID Example_HatchBrushConstructor(HDC hdc)
{
   Graphics graphics(hdc);

   // Set colors.
   Color black(255,0,0,0);
   Color white(255,255,255,255);

   // Set and then draw the first hatch style.
   HatchBrush brush(HatchStyleHorizontal, black, white);
   graphics.FillRectangle(&brush, 20, 20, 100, 50);

   // Set and then draw the second hatch style.
   HatchBrush brush1(HatchStyleVertical, black, white);
   graphics.FillRectangle(&brush1, 120, 20, 100, 50);

   // Set and then draw the third hatch style.
   HatchBrush brush2(HatchStyleForwardDiagonal, black, white);
   graphics.FillRectangle(&brush2, 220, 20, 100, 50);

   // Set and then draw the fourth hatch style.
   HatchBrush brush3(HatchStyleBackwardDiagonal, black, white);
   graphics.FillRectangle(&brush3, 320, 20, 100, 50);

   // Set and then draw the fifth hatch style.
   HatchBrush brush4(HatchStyleCross, black, white);
   graphics.FillRectangle(&brush4, 420, 20, 100, 50);

   // Set and then draw the sixth hatch style.
   HatchBrush brush5(HatchStyleDiagonalCross, black, white);
   graphics.FillRectangle(&brush5, 520, 20, 100, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, HatchStyle
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


HatchBrush Methods

This topic lists the methods of the HatchBrush class. For a complete class listing, see HatchBrush Class.

  • Clone()
  • GetBackgroundColor(color)
  • GetForegroundColor(color)
  • GetHatchStyle()
  • GetLastStatus()
  • GetType()


HatchBrush::GetBackgroundColor(color)

The GetBackgroundColor method gets the background color of this hatch brush.

Status GetBackgroundColor(
  Color* color
) const;

Parameters

color
[out] Pointer to a Color object that receives the background color. The background color defines the color over which the hatch lines are drawn.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example sets up three Color objects: black, turquoise, and current (initialized to black). A rectangle is painted by using turquoise as the background color and black as the foreground color. Then the GetBackgroundColor method is used to get the current color of the brush (which at the time is turquoise). The address of the current Color object (initialized to black) is passed as the return point for the call to GetBackgroundColor. When the rectangle is painted again, note that the background color is again turquoise (not black). This shows that the call to GetBackgroundColor was successful.

VOID Example_GetBackgroundColor(HDC hdc)
{
   Graphics graphics(hdc);

   // Set colors.
   Color black(255, 0, 0, 0);         // foreground
   Color turquoise(255, 0, 255, 255); // background
   Color current(255, 0, 0, 0);       // new background

   // Set and then draw the first hatch style.
   HatchBrush brush(HatchStyleHorizontal, black, turquoise);
   graphics.FillRectangle(&brush, 20, 20, 100, 50);

   // Get the background color of the current brush.
   brush.GetBackgroundColor(&current);

   // Draw the rectangle again using the current color.
   HatchBrush brush2(HatchStyleDiagonalCross, black, current);
   graphics.FillRectangle(&brush2, 130, 20, 100, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, GetForegroundColor, HatchStyle
Tasks and Examples
Filling a Shape with a Hatch Pattern
Concepts
Brushes and Filled Shapes


HatchBrush::GetForegroundColor(color)

The GetForegroundColor method gets the foreground color of this hatch brush.

Status GetForegroundColor(
  Color* color
) const;

Parameters

color
[out] Pointer to a Color object that receives the foreground color. The foreground color defines the color of the hatch lines.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example sets up three Color objects blue, turquoise, and current (initialized to black). A rectangle is painted by using turquoise as the background color and blue as the foreground color. Then the GetBackgroundColor method is used to get the current color of the brush (which at the time is blue). The address of the current Color object (initialized to black) is passed as the return point for the call to GetBackgroundColor. When the rectangle is painted again, notice that the foreground color is again blue (not black). This shows that the call to GetForegroundColor was successful.

VOID Example_GetForegroundColor(HDC hdc)
{
   Graphics graphics(hdc);

   // Set colors.
   Color blue(255, 0, 0, 255);        // foreground
   Color turquoise(255, 0, 255, 255); // background
   Color current(255, 0, 0, 0);       // new foreground

   // Set and then draw the first hatch style.
   HatchBrush brush(HatchStyleHorizontal, blue, turquoise);
   graphics.FillRectangle(&brush, 20, 20, 100, 50);

   // Get the current foreground color of the brush.
   brush.GetForegroundColor(&current);

   // Draw the rectangle again using the current color.
   HatchBrush brush2(HatchStyleDiagonalCross, current, turquoise);
   graphics.FillRectangle(&brush2, 130, 20, 100, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, GetForegroundColor, HatchStyle
Tasks and Examples
Filling a Shape with a Hatch Pattern
Concepts
Brushes and Filled Shapes


HatchBrush::GetHatchStyle()

The GetHatchStyle method gets the hatch style of this hatch brush.

HatchStyle GetHatchStyle(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the hatch style, which is one of the elements of the HatchStyle enumeration.

Example Code [C++]

The following example sets up two hatch styles: horiz and current (initialized to HatchStyleDiagonalCross). A rectangle that uses horiz as the hatch style is painted. Then the GetHatchStyle method is used to get the current hatch style of the brush (which at the time is HatchStyleHorizontal). The address of the current HatchStyle object (initialized to HatchStyleDiagonalCross) is passed as the return point for the call to GetHatchStyle. When the rectangle is painted again, notice that the hatch style is again HatchStyleHorizontal (not HatchStyleDiagonalCross). This shows that the call to GetHatchStyle was successful.

VOID Example_GetHatchStyle(HDC hdc)
{
   Graphics graphics(hdc);

   // Set colors.
   Color blue(255, 0, 0, 255);        // foreground
   Color turquoise(255, 0, 255, 255); // background

   // Set hatch styles.
   HatchStyle horiz(HatchStyleHorizontal);
   HatchStyle current(HatchStyleDiagonalCross);

   // Set and then draw the first hatch style.
   HatchBrush brush(horiz, blue, turquoise);
   graphics.FillRectangle(&brush, 20, 20, 100, 50);

   // Get the current hatch style of the brush.
   current = brush.GetHatchStyle();

   // Draw the rectangle again using the current hatch style.
   HatchBrush brush2(current, blue, turquoise);
   graphics.FillRectangle(&brush2, 130, 20, 100, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, HatchStyle
Tasks and Examples
Filling a Shape with a Hatch Pattern
Concepts
Brushes and Filled Shapes


Image Class

The Image class provides methods for loading and saving raster images (bitmaps) and vector images (metafiles). An Image object encapsulates a bitmap or a metafile and stores attributes that you can retrieve by calling various Get methods. You can construct Image objects from a variety of file types including BMP, ICON, GIF, JPEG, Exif, PNG, TIFF, WMF, and EMF.

Inheritance

GdiplusBase
Image

Constructors

Constructor | Description
Image | Overloaded. Creates an Image object based on a file or a stream.

Methods

Method | Description
Clone | Creates a new Image object and initializes it with the contents of this Image object.
FromFile | Creates an Image object based on a file.
FromStream | Creates an Image object based on a stream.
GetAllPropertyItems | Gets all the property items (pieces of metadata) stored in this Image object.
GetBounds | Gets the bounding rectangle for this image.
GetEncoderParameterList | Gets a list of the parameters supported by a specified image encoder.
GetEncoderParameterListSize | Gets the size, in bytes, of the parameter list for a specified image encoder.
GetFlags | Gets a set of flags that indicate certain attributes of this Image object.
GetFrameCount | Gets the number of frames in a specified dimension of this Image object.
GetFrameDimensionsCount | Gets the number of frame dimensions in this Image object.
GetFrameDimensionsList | Gets the frame dimension IDs of this Image object.
GetHeight | Gets the height, in pixels, of this image.
GetHorizontalResolution | Gets the horizontal resolution, in dots per inch, of this image.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetPalette | Gets the color palette of this Image object.
GetPaletteSize | Gets the size, in bytes, of the color palette of this Image object.
GetPhysicalDimension | Gets the width and height of this image.
GetPixelFormat | Gets the pixel format of this image.
GetPropertyCount | Gets the number of property items (pieces of metadata) stored in this Image object.
GetPropertyIdList | Gets a list of the property IDs stored in this Image object.
GetPropertyItem | Gets a specified property item (piece of metadata) from this Image object.
GetPropertyItemSize | Gets the size (in bytes) of a specified property item (piece of metadata) stored in this Image object.
GetPropertySize | Gets the total size, in bytes, of the property items stored in this Image object. Also gets the number of property items.
GetRawFormat | Gets a GUID that identifies the format of this Image object.
GetThumbnailImage | Gets a thumbnail image from this Image object.
GetType | Gets the image type (bitmap or metafile).
GetVerticalResolution | Gets the vertical resolution, in dots per inch, of this image.
GetWidth | Gets the width, in pixels, of this image.
RemovePropertyItem | Removes a property item (piece of metadata) from this Image object.
RotateFlip | Rotates this image.
Save | Overloaded. Saves this image to a file or to a stream.
SaveAdd | Overloaded. Adds a frame to the file or stream specified in a previous call to the Save method.
SelectActiveFrame | Selects a specified frame of this Image object.
SetPalette | Sets the color palette of this Image object.
SetPropertyItem | Sets a specified property item (piece of metadata) of this Image object.
~Image | Image object destructor.


Image Constructors

This topic lists the constructors of the Image class. For a complete class listing, see Image Class.

  • Image(filename, useEmbeddedColorManagement)
  • Image(stream, useEmbeddedColorManagement)


Image::Image(filename, useEmbeddedColorManagement)

Creates an Image object based on a file.

Image(
  const WCHAR* filename,
  BOOL useEmbeddedColorManagement
);

Parameters

filename
[in] Pointer to a wide-character string that specifies the name of the file.
useEmbeddedColorManagement
[in] Optional. Boolean value that specifies whether the new Image object applies color correction according to color management information that is embedded in the image file. Embedded information can include International Color Consortium (ICC) profiles, gamma values, and chromaticity information. TRUE specifies that color correction is enabled, and FALSE specifies that color correction is not enabled. The default value is FALSE.

Remarks

You can construct Image objects based on files of a variety of types including BMP, GIF, JPEG, PNG, TIFF, and EMF.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, Clone, FromFile, FromStream, Image Constructors
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Basic Color Management Concepts, Drawing, Positioning, and Cloning Images


Image::Image(stream, useEmbeddedColorManagement)

Creates an Image object based on a stream.

Image(
  IStream* stream,
  BOOL useEmbeddedColorManagement
);

Parameters

stream
[in] Pointer to an IStream interface. The implementation of IStream must include the Seek, Read, and Stat methods.
useEmbeddedColorManagement
[in] Optional. Boolean value that specifies whether the new Image object applies color correction according to color management information that is embedded in the stream. Embedded information can include International Color Consortium (ICC) profiles, gamma values, and chromaticity information. TRUE specifies that color correction is enabled, and FALSE specifies that color correction is not enabled. The default value is FALSE.

Example Code [C++]

The following example creates two Image objects. Each Image object is based on a stream that is part of a compound file. For an example of creating a compound file, see Image::Save(stream, clsidEncoder, encoderParams). The code calls StgOpenStorage to open the compound file and get a pointer to its IStorage interface. Then the code calls IStorage::OpenStream to get a pointer to an IStream interface that represents one of the streams in the compound file. The code constructs an Image object based on that IStream pointer and then calls Graphics::DrawImage to display the image on the screen. The code uses a similar process to construct an Image object based on a second stream that is part of the same compound file.

VOID Example_ImageStream(HDC hdc)
{
   Graphics graphics(hdc);

   Image* pImage1 = NULL;
   Image* pImage2 = NULL;

   IStorage* pIStorage = NULL;
   IStream* pIStream1 = NULL;
   IStream* pIStream2 = NULL;
   HRESULT hr;
   Status stat;

   // Open an existing compound file, and get a pointer
   // to its IStorage interface.
   hr = StgOpenStorage(
      L"CompoundFile.cmp",
      NULL,
      STGM_READ|STGM_SHARE_EXCLUSIVE,
      NULL,
      0,
      &pIStorage);

   if(FAILED(hr))
      goto Exit;

   // Get a pointer to the stream StreamImage1 in the compound file.
   hr = pIStorage->OpenStream(
      L"StreamImage1",
      NULL,
      STGM_READ|STGM_SHARE_EXCLUSIVE,
      0,
      &pIStream1);

   if(FAILED(hr))
      goto Exit;

   // Get a pointer to the stream StreamImage2 in the compound file.
   hr = pIStorage->OpenStream(
      L"StreamImage2",
      NULL,
      STGM_READ|STGM_SHARE_EXCLUSIVE,
      0,
      &pIStream2);

   if(FAILED(hr))
      goto Exit;

   // Construct a new Image object based on StreamImage1.
   pImage1 = new Image(pIStream1);
   stat = pImage1->GetLastStatus();
   if(stat != Ok)
      goto Exit;

   graphics.DrawImage(pImage1, 10, 10);

   // Construct a new Image object based on StreamImage2.
   pImage2 = new Image(pIStream2);
   stat = pImage2->GetLastStatus();
   if(stat != Ok)
      goto Exit;

   graphics.DrawImage(pImage2, 200, 10);

Exit:
   if(pImage1)
      delete pImage1;
   if(pImage2)
      delete pImage2;
   if(pIStream1)
      pIStream1->Release();
   if(pIStream2)
      pIStream2->Release();
   if(pIStorage)
      pIStorage->Release();
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, Clone, FromFile, FromStream, Image Constructors, IStorage, IStream, StgOpenStorage
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Basic Color Management Concepts, Drawing, Positioning, and Cloning Images


Image Methods

This topic lists the methods of the Image class. For a complete class listing, see Image Class.

  • Clone()
  • FromFile(filename, useEmbeddedColorManagement)
  • FromStream(stream, useEmbeddedColorManagement)
  • GetAllPropertyItems(totalBufferSize, numProperties, allItems)
  • GetBounds(srcRect, srcUnit)
  • GetEncoderParameterList(clsidEncoder, size, buffer)
  • GetEncoderParameterListSize(clsidEncoder)
  • GetFlags()
  • GetFrameCount(dimensionID)
  • GetFrameDimensionsCount()
  • GetFrameDimensionsList(dimensionIDs, count)
  • GetHeight()
  • GetHorizontalResolution()
  • GetLastStatus()
  • GetPalette(palette, size)
  • GetPaletteSize()
  • GetPhysicalDimension(size)
  • GetPixelFormat()
  • GetPropertyCount()
  • GetPropertyIdList(numOfProperty, list)
  • GetPropertyItem(propId, propSize, buffer)
  • GetPropertyItemSize(propId)
  • GetPropertySize(totalBufferSize, numProperties)
  • GetRawFormat(format)
  • GetThumbnailImage(thumbWidth, thumbHeight, callback, callbackData)
  • GetType()
  • GetVerticalResolution()
  • GetWidth()
  • RemovePropertyItem(propId)
  • RotateFlip(rotateFlipType)
  • SelectActiveFrame(dimensionID, frameIndex)
  • SetPalette(palette)
  • SetPropertyItem(item)


Image::Clone()

The Clone method creates a new Image object and initializes it with the contents of this Image object.

virtual Image* Clone(void);

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new Image object.

Example Code [C++]

The following example creates an Image object based on a JPEG file. The code creates a second Image object by cloning the first. Then the code calls the Graphics::DrawImage method twice to draw the two images.

VOID Example_Clone(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object, and then clone it.
   Image image1(L"Crayons.jpg");
   Image* pImage2 = image1.Clone();

   // Draw the original image and the cloned image.
   graphics.DrawImage(&image1, 20, 20);
   graphics.DrawImage(pImage2, 250, 20);

   delete pImage2;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, FromFile, FromStream, Image Constructors
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Drawing, Positioning, and Cloning Images


Image::FromFile(filename, useEmbeddedColorManagement)

The FromFile method creates an Image object based on a file.

static Image* FromFile(
  const WCHAR* filename,
  BOOL useEmbeddedColorManagement
);

Parameters

filename
[in] Pointer to a wide-character string that specifies the name of the file.
useEmbeddedColorManagement
[in] Optional. Boolean value that specifies whether the new Image object applies color correction according to color management information that is embedded in the image file. Embedded information can include International Color Consortium (ICC) profiles, gamma values, and chromaticity information. TRUE specifies that color correction is enabled, and FALSE specifies that color correction is not enabled. The default value is FALSE.

Return Values

This method returns a pointer to the new Image object.

Remarks

You can create Image objects based on files of a variety of types including BMP, GIF, JPEG, PNG, TIFF, and EMF.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, Clone, FromStream, Image Constructors
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Basic Color Management Concepts, Drawing, Positioning, and Cloning Images


Image::FromStream(stream, useEmbeddedColorManagement)

The FromStream method creates a new Image object based on a stream.

static Image* FromStream(
  IStream* stream
  BOOL useEmbeddedColorManagement
);

Parameters

stream
[in] Pointer to an IStream interface. The implementation of IStream must include the Seek, Read, and Stat methods.
useEmbeddedColorManagement
[in] Optional. Boolean value that specifies whether the new Image object applies color correction according to color management information that is embedded in the stream. Embedded information can include International Color Consortium (ICC) profiles, gamma values, and chromaticity information. TRUE specifies that color correction is enabled, and FALSE specifies that color correction is not enabled. The default value is FALSE.

Return Values

This method returns a pointer to the new Image object.

Example Code [C++]

The following example creates two Image objects. Each Image object is based on a stream that is part of a compound file. For an example of creating a compound file, see Image::Save(stream, clsidEncoder, encoderParams). The code calls StgOpenStorage to open the compound file and get a pointer to its IStorage interface. Then the code calls IStorage::OpenStream to get a pointer to an IStream interface that represents one of the streams in the compound file. The code calls Image::FromStream to create an Image object based on that IStream pointer and then calls Graphics::DrawImage to display the image on the screen. The code uses a similar process to create an Image object based on a second stream that is part of the same compound file.

VOID Example_FromStream(HDC hdc)
{
   Graphics graphics(hdc);

   Image* pImage1 = NULL;
   Image* pImage2 = NULL;

   IStorage* pIStorage = NULL;
   IStream* pIStream1 = NULL;
   IStream* pIStream2 = NULL;
   HRESULT hr;
   Status stat;

   // Open an existing compound file, and get a pointer
   // to its IStorage interface.
   hr = StgOpenStorage(
      L"CompoundFile.cmp",
      NULL,
      STGM_READ|STGM_SHARE_EXCLUSIVE,
      NULL,
      0,
      &pIStorage);

   if(FAILED(hr))
      goto Exit;

   // Get a pointer to the stream StreamImage1 in the compound file.
   hr = pIStorage->OpenStream(
      L"StreamImage1",
      NULL,
      STGM_READ|STGM_SHARE_EXCLUSIVE,
      0,
      &pIStream1);

   if(FAILED(hr))
      goto Exit;

   // Get a pointer to the stream StreamImage2 in the compound file.
   hr = pIStorage->OpenStream(
      L"StreamImage2",
      NULL,
      STGM_READ|STGM_SHARE_EXCLUSIVE,
      0,
      &pIStream2);

   if(FAILED(hr))
      goto Exit;

   // Create a new Image object based on StreamImage1.
   pImage1 = Image::FromStream(pIStream1);
   stat = pImage1->GetLastStatus();
   if(stat != Ok)
      goto Exit;

   graphics.DrawImage(pImage1, 10, 10);

   // Create a new Image object based on StreamImage2.
   pImage2 = Image::FromStream(pIStream2);
   stat = pImage2->GetLastStatus();
   if(stat != Ok)
      goto Exit;

   graphics.DrawImage(pImage2, 200, 10);

Exit:
   if(pImage1)
      delete pImage1;
   if(pImage2)
      delete pImage2;
   if(pIStream1)
      pIStream1->Release();
   if(pIStream2)
      pIStream2->Release();
   if(pIStorage)
      pIStorage->Release();
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, Clone, FromFile, Image Constructors IStorage, IStream, StgOpenStorage
Tasks and Examples
Loading and Displaying Bitmaps
Concepts
Basic Color Management Concepts, Drawing, Positioning, and Cloning Images


Image::GetAllPropertyItems(totalBufferSize, numProperties, allItems)

The GetAllPropertyItems method gets all the property items (metadata) stored in this Image object.

Status GetAllPropertyItems(
  UINT totalBufferSize,
  UINT numProperties,
  PropertyItem* allItems
);

Parameters

totalBufferSize
[in] Integer that specifies the size, in bytes, of the allItems buffer. Call the GetPropertySize method to obtain the required size.
numProperties
[in] Integer that specifies the number of properties in the image. Call the GetPropertySize method to obtain this number.
allItems
[out] Pointer to an array of PropertyItem objectsthat receives the property items.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Some image files contain metadata that you can read to determine features of the image. For example, a digital photograph might contain metadata that you can read to determine the make and model of the camera used to capture the image.

GDI+ stores an individual piece of metadata in a PropertyItem object. The GetAllPropertyItems method returns an array of PropertyItem objects. Before you call GetAllPropertyItems, you must allocate a buffer large enough to receive that array. You can call the GetPropertySize method of an Image object to get the size, in bytes, of the required buffer. The GetPropertySize method also gives you the number of properties (pieces of metadata) in the image.

Several enumerations and constants related to image metadata are defined in Gdiplusimaging.h.

Example Code [C++]

The following example creates an Image object based on a JPEG file. The code calls the GetAllPropertyItems method of that Image object to obtain its property items (metadata).

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   // Create an Image object based on a JPEG file.
   Image* image = new Image(L"FakePhoto.jpg");

   // Find out how many property items are in the image, and find out the
   // required size of the buffer that will receive those property items.
   UINT totalBufferSize;
   UINT numProperties;
   image->GetPropertySize(&totalBufferSize, &numProperties);

   // Allocate the buffer that will receive the property items.
   PropertyItem* pAllItems = (PropertyItem*)malloc(totalBufferSize);

   // Fill the buffer.
   image->GetAllPropertyItems(totalBufferSize, numProperties, pAllItems);

// Print the id data member of each property item.
   for(UINT j = 0; j < numProperties; ++j)
   {
      printf("%x\n", pAllItems[j].id);
   }

   free(pAllItems);
   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, FakePhoto.jpg, produced the following output:

320
10f
110
9003
829a
5090
5091

The preceding output shows a hexadecimal ID number for each property item. You can look up those ID numbers in Gdiplusimaging.h and find out that they represent the following property tags.

Hexadecimal value | Property tag
0x0320 0x010f 0x0110 0x9003 0x829a 0x5090 0x5091 | PropertyTagImageTitle PropertyTagEquipMake PropertyTagEquipModel PropertyTagExifDTOriginal PropertyTagExifExposureTime PropertyTagLuminanceTable PropertyTagChrominanceTable

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetPropertyCount, GetPropertyIdList, GetPropertyItem, GetPropertyItemSize, GetPropertySize, PropertyItem, RemovePropertyItem, SetPropertyItem
Tasks and Examples
Reading and Writing Metadata


Image::GetBounds(srcRect, srcUnit)

The GetBounds method gets the bounding rectangle for this image.

Status GetBounds(
  RectF* srcRect,
  Unit* srcUnit
);

Parameters

srcRect
[out] Pointer to a RectF object that receives the bounding rectangle.
srcUnit
[out] Pointer to a variable that receives an element of the Unit enumeration that indicates the unit of measure for the bounding rectangle.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The bounding rectangle for a metafile does not necessarily have (0, 0) as its upper-left corner. The coordinates of the upper-left corner can be negative or positive, depending on the drawing commands that were issued during the recording of the metafile. For example, suppose a metafile consists of a single ellipse that was recorded with the following statement:

DrawEllipse(&pen, 200, 100, 80, 40);

Then the bounding rectangle for the metafile will enclose that one ellipse. The upper-left corner of the bounding rectangle will not be (0, 0); rather, it will be a point near (200, 100).

Example Code [C++]

The following example creates an Image object based on a metafile and then draws the image. Next, the code calls the GetBounds method to get the bounding rectangle for the image. The code makes two attempts to display 75 percent of the image. The first attempt fails because it specifies (0, 0) for the upper-left corner of the source rectangle. The second attempt succeeds because it uses the X and Y data members returned by GetBounds to specify the upper-left corner of the source rectangle.

VOID Example_GetBounds(HDC hdc)
{
   Graphics graphics(hdc);

   Image image(L"SampleMetafile2.emf");
   graphics.DrawImage(&image, 0, 0);

   // Get the bounding rectangle for the image (metafile).
   RectF boundsRect;
   Unit unit;
   image.GetBounds(&boundsRect, &unit);

   // Attempt to draw 75 percent of the image.
   // We will see less than 75 percent of the image because the
   // upper-left corner of the image's bounding rectangle is not (0, 0).
   RectF dstRect(250.0f, 0.0f, 100.0f, 50.0f);
   graphics.DrawImage(
      &image,
      dstRect,                  // destination rectangle
      0.0f, 0.0f,               // upper-left corner of source rectangle
      0.75f*boundsRect.Width,   // width of source rectangle
      boundsRect.Height,        // height of source rectangle
      UnitPixel);

   // Draw 75 percent of the image.
   dstRect.Y = 80.0f;
   graphics.DrawImage(
      &image,
      dstRect,                       // destination rectangle
      boundsRect.X, boundsRect.Y,    // upper-left corner of source rectangle
      0.75f*boundsRect.Width,        // width of source rectangle
      boundsRect.Height,             // height of source rectangle
      UnitPixel);
}

The preceding code, along with a particular file, SampleMetafile2.emf, produced the following output. Note that the first attempt (upper-right) to draw 75 percent of the image shows only about 30 percent of the image.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetWidth, GetHeight, RectF, Unit
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Image::GetEncoderParameterList(clsidEncoder, size, buffer)

The GetEncoderParameterList method gets a list of the parameters supported by a specified image encoder.

Status GetEncoderParameterList(
  const CLSID* clsidEncoder,
  UINT size,
  EncoderParameters* buffer
);

Parameters

clsidEncoder
[in] Pointer to a CLSID that specifies the encoder.
size
[in] Integer that specifies the size, in bytes, of the buffer array. Call the GetEncoderParameterListSize method to obtain the required size.
buffer
[out] Pointer to an EncoderParameters object that receives the list of supported parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The GetEncoderParameterList method returns an array of EncoderParameter objects. Before you call GetEncoderParameterList, you must allocate a buffer large enough to receive that array, which is part of an EncoderParameters object. You can call the GetEncoderParameterListSize method to get the size, in bytes, of the required EncoderParameters object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetEncoderParameterListSize, GetImageEncoders, GetImageEncodersSize
Tasks and Examples
Using Image Encoders and Decoders


Image::GetEncoderParameterListSize(clsidEncoder)

The GetEncoderParameterListSize method gets the size, in bytes, of the parameter list for a specified image encoder.

UINT GetEncoderParameterListSize(
  const CLSID* clsidEncoder
);

Parameters

clsidEncoder
[in] Pointer to a CLSID that specifies the encoder.

Return Values

This method returns the size, in bytes, of the parameter list.

Remarks

The GetEncoderParameterList method returns an array of EncoderParameter objects. Before you call GetEncoderParameterList, you must allocate a buffer large enough to receive that array, which is part of an EncoderParameters object. You can call the GetEncoderParameterListSize method to get the size, in bytes, of the required EncoderParameters object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetEncoderParameterList, GetImageEncoders, GetImageEncodersSize
Tasks and Examples
Using Image Encoders and Decoders


Image::GetFlags()

The GetFlags method gets a set of flags that indicate certain attributes of this Image object.

UINT GetFlags(void);

Parameters

This method has no parameters.

Return Values

This method returns a value that holds a set of single-bit flags. The flags are defined in the ImageFlags enumeration.

Example Code [C++]

The following console application creates an Image object based on a PNG file. The code calls the GetFlags method of that Image object to obtain its collection of flags. The code prints the hexadecimal value of the flag collection and then determines whether certain individual flags are set.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image = new Image(L"Mosaic.png");

   UINT flags = image->GetFlags();
   printf("The value of flags, in hexadecimal form, is %x.\n", flags);

   // Is the ColorSpaceRGB flag set?
   if(flags & ImageFlagsColorSpaceRGB)
      printf("The ColorSpaceRGB flag is set.\n");
   else
     printf("The ColorSpaceRGB flag is not set.\n");

   // Is the HasAlpha flag set?
   if(flags & ImageFlagsHasAlpha)
      printf("The HasAlpha flag is set.\n");
   else
      printf("The HasAlpha flag is not set.\n");

   delete(image);
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, Mosaic.png, produced the following output:

The value of flags, in hexadecimal form, is 13010.
The ColorSpaceRGB flag is set.
The HasAlpha flag is not set.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
ImageFlags
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Image::GetFrameCount(dimensionID)

The GetFrameCount method gets the number of frames in a specified dimension of this Image object.

UINT GetFrameCount(
  const GUID* dimensionID
);

Parameters

dimensionID
[in] Pointer to a GUID that specifies the dimension. GUIDs that identify various dimensions are defined in Gdiplusimaging.h.

Return Values

This method returns the number of frames in the specified dimension of this Image object.

Example Code [C++]

The following console application creates an Image object based on a TIFF file. The code calls the GetFrameDimensionsCount method to find out how many frame dimensions the Image object has. Each of those frame dimensions is identified by a GUID, and the call to GetFrameDimensionsList retrieves those GUIDs. The first GUID is at index 0 in the pDimensionIDs array. The call to the GetFrameCount method determines the number of frames in the dimension identified by the first GUID.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image = new Image(L"Multiframe.tif");

   // How many frame dimensions does the Image object have?
   UINT count = 0;
   count = image->GetFrameDimensionsCount();
   printf("The number of dimensions is %d.\n", count);
   GUID* pDimensionIDs = (GUID*)malloc(sizeof(GUID)*count);

   // Get the list of frame dimensions from the Image object.
   image->GetFrameDimensionsList(pDimensionIDs, count);

   // Display the GUID of the first (and only) frame dimension.
   WCHAR strGuid[39];
   StringFromGUID2(pDimensionIDs[0], strGuid, 39);
   wprintf(L"The first (and only) dimension ID is %s.\n", strGuid);

   // Get the number of frames in the first dimension.
   UINT frameCount = image->GetFrameCount(&pDimensionIDs[0]);
   printf("The number of frames in that dimension is %d.\n", frameCount);

   free(pDimensionIDs);
   delete(image);
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, Multiframe.tif, produced the following output:

The number of dimensions is 1.
The first (and only) dimension ID is {7462DC86-6180-4C7E-8E3F-EE7333A7A483}.
The number of frames in that dimension is 4.

You can look up the displayed GUID in Gdiplusimaging.h and see that it is the identifier for the page dimension. So the program output tells us that the file Multiframe.tif has four pages; that is, four frames in the page dimension.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
EncoderParameter, GetFrameDimensionsCount, GetFrameDimensionsList, SaveAdd Methods
Tasks and Examples
Copying Individual Frames from a Multiple-Frame Image, Creating and Saving a Multiple-Frame Image


Image::GetFrameDimensionsCount()

The GetFrameDimensionsCount method gets the number of frame dimensions in this Image object.

UINT GetFrameDimensionsCount(void);

Parameters

This method has no parameters.

Return Values

This method returns the number of frame dimensions in this Image object.

Remarks

This method returns information about multiple-frame images, which come in two styles: multiple page and multiple resolution.

A multiple-page image is an image that contains more than one image. Each page contains a single image (or frame). These pages (or images, or frames) are typically displayed in succession to produce an animated sequence, such as in an animated GIF file.

A multiple-resolution image is an image that contains more than one copy of an image at different resolutions.

GDI+ can support an arbitrary number of pages (or images, or frames), as well as an arbitrary number of resolutions.

Example Code [C++]

The following console application creates an Image object based on a TIFF file. The code calls the GetFrameDimensionsCount method to find out how many frame dimensions the Image object has. Each of those frame dimensions is identified by a GUID, and the call to GetFrameDimensionsList retrieves those GUIDs. The first GUID is at index 0 in the pDimensionIDs array. The call to the GetFrameCount method determines the number of frames in the dimension identified by the first GUID.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image = new Image(L"Multiframe.tif");

   // How many frame dimensions does the Image object have?
   UINT count = 0;
   count = image->GetFrameDimensionsCount();
   printf("The number of dimensions is %d.\n", count);
   GUID* pDimensionIDs = (GUID*)malloc(sizeof(GUID)*count);

   // Get the list of frame dimensions from the Image object.
   image->GetFrameDimensionsList(pDimensionIDs, count);

   // Display the GUID of the first (and only) frame dimension.
   WCHAR strGuid[39];
   StringFromGUID2(pDimensionIDs[0], strGuid, 39);
   wprintf(L"The first (and only) dimension ID is %s.\n", strGuid);

   // Get the number of frames in the first dimension.
   UINT frameCount = image->GetFrameCount(&pDimensionIDs[0]);
   printf("The number of frames in that dimension is %d.\n", frameCount);

   free(pDimensionIDs);
   delete(image);
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, Multiframe.tif, produced the following output:

The number of dimensions is 1.
The first (and only) dimension ID is {7462DC86-6180-4C7E-8E3F-EE7333A7A483}.
The number of frames in that dimension is 4.

You can look up the displayed GUID in Gdiplusimaging.h and see that it is the identifier for the page dimension. So the program output tells us that the file Multiframe.tif has four pages; that is, four frames in the page dimension.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
EncoderParameter, GetFrameCount, GetFrameDimensionsList, SaveAdd Methods
Tasks and Examples
Copying Individual Frames from a Multiple-Frame Image, Creating and Saving a Multiple-Frame Image


Image::GetFrameDimensionsList(dimensionIDs, count)

The GetFrameDimensionsList method gets the identifiers for the frame dimensions of this Image object.

Status GetFrameDimensionsList(
  GUID* dimensionIDs,
  UINT count
);

Parameters

dimensionIDs
[out] Pointer to an array that receives the identifiers. GUIDs that identify various dimensions are defined in Gdiplusimaging.h.
count
[in] Integer that specifies the number of elements in the dimensionIDs array. Call the GetFrameDimensionCount method to determine this number.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

This method returns information about multiple-frame images, which come in two styles: multiple page and multiple resolution.

A multiple-page image is an image that contains more than one image. Each page contains a single image (or frame). These pages (or images, or frames) are typically displayed in succession to produce an animated sequence, such as in an animated GIF file.

A multiple-resolution image is an image that contains more than one copy of an image at different resolutions.

GDI+ can support an arbitrary number of pages (or images, or frames), as well as an arbitrary number of resolutions.

Example Code [C++]

The following console application creates an Image object based on a TIFF file. The code calls the GetFrameDimensionsCount method to find out how many frame dimensions the Image object has. Each of those frame dimensions is identified by a GUID, and the call to GetFrameDimensionsList retrieves those GUIDs. The first GUID is at index 0 in the pDimensionIDs array. The call to the GetFrameCount method determines the number of frames in the dimension identified by the first GUID.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image = new Image(L"Multiframe.tif");

   // How many frame dimensions does the Image object have?
   UINT count = 0;
   count = image->GetFrameDimensionsCount();
   printf("The number of dimensions is %d.\n", count);
   GUID* pDimensionIDs = (GUID*)malloc(sizeof(GUID)*count);

   // Get the list of frame dimensions from the Image object.
   image->GetFrameDimensionsList(pDimensionIDs, count);

   // Display the GUID of the first (and only) frame dimension.
   WCHAR strGuid[39];
   StringFromGUID2(pDimensionIDs[0], strGuid, 39);
   wprintf(L"The first (and only) dimension ID is %s.\n", strGuid);

   // Get the number of frames in the first dimension.
   UINT frameCount = image->GetFrameCount(&pDimensionIDs[0]);
   printf("The number of frames in that dimension is %d.\n", frameCount);

   free(pDimensionIDs);
   delete(image);
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, Multiframe.tif, produced the following output:

The number of dimensions is 1.
The first (and only) dimension ID is {7462DC86-6180-4C7E-8E3F-EE7333A7A483}.
The number of frames in that dimension is 4.

You can look up the displayed GUID in Gdiplusimaging.h and see that it is the identifier for the page dimension. So the program output tells us that the file Multiframe.tif has four pages; that is, four frames in the page dimension.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
EncoderParameter, GetFrameCount, GetFrameDimensionsCount, SaveAdd Methods
Tasks and Examples
Copying Individual Frames from a Multiple-Frame Image, Creating and Saving a Multiple-Frame Image


Image::GetHeight()

The GetHeight method gets the image height, in pixels, of this image.

UINT GetHeight(void);

Parameters

This method has no parameters.

Return Values

This method returns the height, in pixels, of this image.

Example Code [C++]

The following console application creates an Image object based on a JPEG file. The code obtains the height of the image by calling the GetHeight method.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image = new Image(L"Crayons.jpg");
   UINT imageHeight = image->GetHeight();
   printf("The height of the image is %u.\n", imageHeight);

   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, GetHorizontalResolution, GetVerticalResolution, GetWidth
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Image::GetHorizontalResolution()

The GetHorizontalResolution method gets the horizontal resolution, in dots per inch, of this image.

REAL GetHorizontalResolution(void);

Parameters

This method has no parameters.

Return Values

This method returns the horizontal resolution, in dots per inch, of this image.

Example Code [C++]

The following console application creates an Image object based on a JPEG file. The code obtains the horizontal resolution of the image by calling the GetHorizontalResolution method.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image = new Image(L"Crayons.jpg");
   REAL res = image->GetHorizontalResolution();
   printf("The horizontal resolution is %f dots per inch.\n", res);

   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, GetHeight, GetVerticalResolution, GetWidth
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Image::GetLastStatus()

The GetLastStatus method returns a value that indicates the nature of this Image object's most recent method failure.

Status GetLastStatus(void);

Parameters

This method has no parameters.

Return Values

The GetLastStatus method returns an element of the Status enumeration.

If no methods invoked on this Image object have failed since the previous call to GetLastStatus, then GetLastStatus returns Ok.

If at least one method invoked on this Image object has failed since the previous call to GetLastStatus, then GetLastStatus returns a value that indicates the nature of the most recent failure.

Remarks

You can call GetLastStatus immediately after constructing an Image object to determine whether the constructor succeeded.

The first time you call the GetLastStatus method of an Image object, it returns Ok if the constructor succeeded and all methods invoked so far on the Image object succeeded. Otherwise, it returns a value that indicates the nature of the most recent failure.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, Status
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Image::GetPalette(palette, size)

The GetPalette method gets the color palette of this Image object.

Status GetPalette(
  ColorPalette* palette,
  INT size
);

Parameters

palette
[out] Pointer to a ColorPalette structure that receives the palette.
size
[in] Integer that specifies the size, in bytes, of the palette. Call the GetPaletteSize method to determine the size.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates an Image object based on a BMP file. The image in that file uses 8 bits per pixel. The code calls the GetPaletteSize method of the Image object to determine the size of the image's palette. The call to malloc allocates a buffer large enough to receive the palette, and the call to GetPalette fills that buffer. The code displays the number of colors in the palette (palette->Count) and then displays the ARGB values of the first five colors in the palette.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image = new Image(L"Stripes8Bit.bmp");

   UINT size = image->GetPaletteSize();
   printf("The size of the palette is %d bytes.\n", size);
   ColorPalette* palette = (ColorPalette*)malloc(size);

   image->GetPalette(palette, size);

   if(size > 0)
   {
      printf("There are %u colors in the palette.\n", palette->Count);
      printf("The first five colors in the palette are as follows:\n");

      for(INT j = 0; j <= 4; ++j)
         printf("%x\n", palette->Entries[j]);
   }

   delete(image);
   free(palette);
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, Stripes8Bit.bmp, produced the following output:

The size of the palette is 1032 bytes.
There are 256 colors in the palette.
The first five colors in the palette are as follows:
ff000000
ff800000
ff008000
ff808000
ff000080

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, Color, ColorPalette, GetPaletteSize, SetPalette
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Image::GetPaletteSize()

The GetPaletteSize method gets the size, in bytes, of the color palette of this Image object.

INT GetPaletteSize(void);

Parameters

This method has no parameters.

Return Values

This method returns the size, in bytes, of the color palette of this Image object.

Example Code [C++]

The following example creates an Image object based on a BMP file. The image in that file uses 8 bits per pixel. The code calls the GetPaletteSize method of the Image object to determine the size of the image's palette. The call to malloc allocates a buffer large enough to receive the palette, and the call to GetPalette fills that buffer. The code displays the number of colors in the palette (palette->Count) and then displays the ARGB values of the first five colors in the palette.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image = new Image(L"Stripes8Bit.bmp");

   UINT size = image->GetPaletteSize();
   printf("The size of the palette is %d bytes.\n", size);
   ColorPalette* palette = (ColorPalette*)malloc(size);

   image->GetPalette(palette, size);
   printf("There are %d colors in the palette.\n", palette->Count);

   printf("The first five colors in the palette are as follows:\n");

   for(INT j = 0; j <= 4; ++j)
      printf("%x\n", palette->Entries[j]);

   delete(image);
   free(palette);
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, Stripes8Bit.bmp, produced the following output:

The size of the palette is 1032 bytes.
There are 256 colors in the palette.
The first five colors in the palette are as follows:
ff000000
ff800000
ff008000
ff808000
ff000080

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, Color, ColorPalette, GetPaletteSize
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Image::GetPhysicalDimension(size)

The GetPhysicalDimension method gets the width and height of this image.

Status GetPhysicalDimension(
  SizeF* size
);

Parameters

size
[out] Pointer to a SizeF object that receives the width and height of this image.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following console application creates an Image object based on a JPEG file. The code obtains the width and height of the image by calling the GetPhysicalDimension method.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image = new Image(L"Crayons.jpg");
   SizeF size;
   image->GetPhysicalDimension(&size);
   printf("The width of the image is %f.\n", size.Width);
   printf("The height of the image is %f.\n", size.Height);

   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetBounds, GetHeight, GetHorizontalResolution, GetVerticalResolution, GetWidth
Tasks and Examples
Cropping and Scaling Images, Improving Performance by Avoiding Automatic Scaling
Concepts
Cropping and Scaling Images


Image::GetPixelFormat()

The GetPixelFormat method gets the pixel format of this Image object.

PixelFormat GetPixelFormat(void);

Parameters

This method has no parameters.

Return Values

This method returns an integer that indicates the pixel format of this Image object. The PixelFormat data type and constants that represent various pixel formats are defined in Gdipluspixelformats.h. For more information about pixel format constants, see Image Pixel Format Constants.

Example Code [C++]

The following console application creates two Image objects: one based on a PNG file and the other based on a BMP file. The code gets the pixel format of each Image object and then compares the obtained values to particular pixel format constants.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image1 = new Image(L"Mosaic.png");
   Image* image2 = new Image(L"Stripes8Bit.bmp");

   PixelFormat pixelFormat1 = image1->GetPixelFormat();
   PixelFormat pixelFormat2 = image2->GetPixelFormat();

   if(pixelFormat1 == PixelFormat24bppRGB)
      printf("The pixel format of image 1 is 24bppRGB.\n");

   if(pixelFormat2 == PixelFormat8bppIndexed)
      printf("The pixel format of image 2 is 8bppIndexed.\n");

   delete image1;
   delete image2;
   GdiplusShutdown(gdiplusToken);
   return 0;

The preceding code, along with two particular files, Mosaic.png and Stripes8Bit.bmp, produced the following output:

The pixel format of image 1 is 24bppRGB.
The pixel format of image 2 is 8bppIndexed.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Image Pixel Format Constants
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Types of Bitmaps


Image::GetPropertyCount()

The GetPropertyCount method gets the number of properties (pieces of metadata) stored in this Image object.

UINT GetPropertyCount(void);

Parameters

This method has no parameters.

Return Values

This method returns the number of properties stored in this Image object.

Example Code [C++]

The following example creates an Image object based on a JPEG file. The code calls the GetPropertyCount method of that Image object to find out how many properties are stored in the image. Then the code calls the GetPropertyIdList method to get a list of the property types.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   UINT count = 0;
   Image* image = new Image(L"FakePhoto.jpg");

   // How many properties (pieces of metadata) are in the image?
   count = image->GetPropertyCount();
   if(count == 0)
      return 0;

   // Allocate a buffer to receive an array of PROPIDs.
   PROPID* propIDs = new PROPID[count];

   image->GetPropertyIdList(count, propIDs);

   // List the retrieved IDs.
   for(UINT j = 0; j < count; ++j)
      printf("%x\n", propIDs[j]);

   delete [] propIDs;
   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, FakePhoto.jpg, produced the following output:

320
10f
110
9003
829a
5090
5091

The preceding output shows the hexadecimal value of each property identifier. You can look up those numbers in Gdiplusimaging.h and find out that they represent the following property tags.

Hexadecimal value | Property tag
0x0320 0x010f 0x0110 0x9003 0x829a 0x5090 0x5091 | PropertyTagImageTitle PropertyTagEquipMake PropertyTagEquipModel PropertyTagExifDTOriginal PropertyTagExifExposureTime PropertyTagLuminanceTable PropertyTagChrominanceTable

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetAllPropertyItems, GetPropertyIdList, GetPropertyItem, GetPropertyItemSize, GetPropertySize, PropertyItem, RemovePropertyItem, SetPropertyItem
Tasks and Examples
Reading and Writing Metadata


Image::GetPropertyIdList(numOfProperty, list)

The GetPropertyIdList method gets a list of the property identifiers used in the metadata of this Image object.

Status GetPropertyIdList(
  UINT numOfProperty,
  PROPID* list
);

Parameters

numOfProperty
[in] Integer that specifies the number of elements in the list array. Call the GetPropertyCount method to determine this number.
list
[out] Pointer to an array that receives the property identifiers.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The GetPropertyIdList method returns an array of PROPIDs. Before you call GetPropertyIdList, you must allocate a buffer large enough to receive that array. You can call the GetPropertyCount method of an Image object to determine the size of the required buffer. The size of the buffer should be the return value of GetPropertyCount multiplied by sizeof(PROPID).

Example Code [C++]

The following example creates an Image object based on a JPEG file. The code calls the GetPropertyIdList method of that Image object to find out what types of metadata are stored in the image.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   UINT count = 0;
   Image* image = new Image(L"FakePhoto.jpg");

   // How many types of metadata are in the image?
   count = image->GetPropertyCount();
   if(count == 0)
      return 0;

   // Allocate a buffer to receive an array of PROPIDs.
   PROPID* propIDs = new PROPID[count];

   image->GetPropertyIdList(count, propIDs);

   // List the retrieved IDs.
   for(UINT j = 0; j < count; ++j)
      printf("%x\n", propIDs[j]);

   delete [] propIDs;
   delete image;

   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, FakePhoto.jpg, produced the following output:

320
10f
110
9003
829a
5090
5091

The preceding output shows the hexadecimal value of each property identifier. You can look up those numbers in Gdiplusimaging.h and find out that they represent the following property tags.

Hexadecimal value | Property tag
0x0320 0x010f 0x0110 0x9003 0x829a 0x5090 0x5091 | PropertyTagImageTitle PropertyTagEquipMake PropertyTagEquipModel PropertyTagExifDTOriginal PropertyTagExifExposureTime PropertyTagLuminanceTable PropertyTagChrominanceTable

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetAllPropertyItems, GetPropertyCount, GetPropertyItem, GetPropertyItemSize, GetPropertySize, PropertyItem, RemovePropertyItem, SetPropertyItem
Tasks and Examples
Reading and Writing Metadata


Image::GetPropertyItem(propId, propSize, buffer)

The GetPropertyItem method gets a specified property item (piece of metadata) from this Image object.

Status GetPropertyItem(
  PROPID propId,
  UINT propSize,
  PropertyItem* buffer
);

Parameters

propId
[in] Integer that identifies the property item to be retrieved.
propSize
[in] Integer that specifies the size, in bytes, of the property item to be retrieved. Call the GetPropertyItemSize method to determine the size.
buffer
[out] Pointer to a PropertyItem object that receives the property item.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The GetPropertyItem method returns a PropertyItem object. Before you call GetPropertytem, you must allocate a buffer large enough to receive that object — the size varies according to data type and value of the property item. You can call the GetPropertyItemSize method of an Image object to get the size, in bytes, of the required buffer.

Example Code [C++]

The following example creates an Image object based on a JPEG file. The code gets the make of the camera that captured the image by passing the PropertyTagEquipMake constant to the GetPropertyItem method of the Image object.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   UINT size = 0;
   PropertyItem* propertyItem = NULL;
   Image* image = new Image(L"FakePhoto.jpg");

   // Assume that the image has a property item of type PropertyItemEquipMake.
   // Get the size of that property item.
   size = image->GetPropertyItemSize(PropertyTagEquipMake);

   // Allocate a buffer to receive the property item.
   propertyItem = (PropertyItem*)malloc(size);

   // Get the property item.
   image->GetPropertyItem(PropertyTagEquipMake, size, propertyItem);

   // Display the members of the retrieved PropertyItem object.
   printf("The length of the property item is %u.\n", propertyItem->length);
   printf("The data type of the property item is %u.\n", propertyItem->type);

   if(propertyItem->type == PropertyTagTypeASCII)
      printf("The value of the property item is %s.\n", propertyItem->value);

   free(propertyItem);
   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, FakePhoto.jpg, produced the following output. Note that the data type is 2, the value of the PropertyTagTypeASCII constant that is defined in Gdiplusimaging.h.

The length of the property item is 17.
The data type of the property item is 2.
The value of the property item is Northwind Traders.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetAllPropertyItems, GetPropertyCount, GetPropertyIdList, GetPropertyItemSize, GetPropertySize, PropertyItem, RemovePropertyItem, SetPropertyItem
Tasks and Examples
Reading and Writing Metadata


Image::GetPropertyItemSize(propId)

The GetPropertyItemSize method gets the size, in bytes, of a specified property item of this Image object.

UINT GetPropertyItemSize(
  PROPID propId
);

Parameters

propId
[in] Integer that identifies the property item.

Return Values

This method returns the size, in bytes, of a specified property item of this Image object.

Remarks

The GetPropertyItem method returns a PropertyItem object. Before you call GetPropertytem, you must allocate a buffer large enough to receive that object — the size varies according to data type and value of the property item. You can call the GetPropertyItemSize method of an Image object to get the size, in bytes, of the required buffer.

Example Code [C++]

The following example creates an Image object based on a JPEG file. The code calls the GetPropertyItemSize method of that Image object to get the size of the property item that holds the make of the camera used to capture the image. Then the code calls the GetPropertyItem method to retrieve that property item.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   UINT size = 0;
   PropertyItem* propertyItem = NULL;
   Image* image = new Image(L"FakePhoto.jpg");

   // Assume that the image has a property item of type PropertyItemEquipMake.
   // Get the size of that property item.
   size = image->GetPropertyItemSize(PropertyTagEquipMake);

   // Allocate a buffer to receive the property item.
   propertyItem = (PropertyItem*)malloc(size);

   // Get the property item.
   image->GetPropertyItem(PropertyTagEquipMake, size, propertyItem);

   // Display the members of the retrieved PropertyItem object.
   printf("The length of the property item is %u.\n", propertyItem->length);
   printf("The data type of the property item is %u.\n", propertyItem->type);

   if(propertyItem->type == PropertyTagTypeASCII)
      printf("The value of the property item is %s.\n", propertyItem->value);

   free(propertyItem);
   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, FakePhoto.jpg, produced the following output. Note that the data type is 2, which is the value of the PropertyTagTypeASCII constant that is defined in Gdiplusimaging.h.

The length of the property item is 17.
The data type of the property item is 2.
The value of the property item is Northwind Traders.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetAllPropertyItems, GetPropertyCount, GetPropertyIdList, GetPropertyItem, GetPropertySize, PropertyItem, RemovePropertyItem, SetPropertyItem
Tasks and Examples
Reading and Writing Metadata


Image::GetPropertySize(totalBufferSize, numProperties)

The GetPropertySize method gets the total size, in bytes, of all the property items stored in this Image object. The GetPropertySize method also gets the number of property items stored in this Image object.

Status GetPropertySize(
  UINT* totalBufferSize,
  UINT* numProperties
);

Parameters

totalBufferSize
[out] Pointer to a UINT that receives the total size, in bytes, of all the property items.
numProperties
[out] Pointer to a UINT that receives the number of property items.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

GDI+ stores an individual piece of metadata in a PropertyItem object. The GetAllPropertyItems method returns an array of PropertyItem objects. Before you call GetAllPropertyItems, you must allocate a buffer large enough to receive that array. You can call the GetPropertySize method of an Image object to get the size, in bytes, of the required buffer. The GetPropertySize method also gives you the number of properties (pieces of metadata) in the image.

Example Code [C++]

The following example creates an Image object based on a JPEG file. The code calls the GetAllPropertyItems method of that Image object to obtain its property items (metadata).

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   // Create an Image object based on a JPEG file.
   Image* image = new Image(L"FakePhoto.jpg");

  // Find out how many property items are in the image, and find out the
   // required size of the buffer that will receive those property items.
   UINT totalBufferSize;
   UINT numProperties;
   image->GetPropertySize(&totalBufferSize, &numProperties);

   // Allocate the buffer that will receive the property items.
   PropertyItem* pAllItems = (PropertyItem*)malloc(totalBufferSize);

   // Fill the buffer.
   image->GetAllPropertyItems(totalBufferSize, numProperties, pAllItems);

   // Print the ID of each property item.
   for(UINT j = 0; j < numProperties; ++j)
   {
      printf("%x\n", pAllItems[j].id);
   }

   free(pAllItems);
   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, FakePhoto.jpg, produced the following output:

320
10f
110
9003
829a
5090
5091

The preceding output shows a hexadecimal ID number for each property item. You can look up those ID numbers in Gdiplusimaging.h and find out that they represent the following property tags.

Hexadecimal value | Property tag
0x0320 0x010f 0x0110 0x9003 0x829a 0x5090 0x5091 | PropertyTagImageTitle PropertyTagEquipMake PropertyTagEquipModel PropertyTagExifDTOriginal PropertyTagExifExposureTime PropertyTagLuminanceTable PropertyTagChrominanceTable

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetAllPropertyItems, GetPropertyCount, GetPropertyIdList, GetPropertyItem, GetPropertyItemSize, PropertyItem, RemovePropertyItem, SetPropertyItem
Tasks and Examples
Reading and Writing Metadata


Image::GetRawFormat(format)

The GetRawFormat method gets a globally unique identifier (GUID) that identifies the format of this Image object. GUIDs that identify various file formats are defined in Gdiplusimaging.h.

Status GetRawFormat(
  GUID* format
);

Parameters

format
[out] Pointer to a GUID that receives the format identifier.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates an Image object based on a JPEG file. The code obtains and displays the GUID that identifies the format of the image. Then the code verifies that the image format is JPEG.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image = new Image(L"FakePhoto.jpg");
   GUID guid;
   WCHAR strGuid[39];

   // Get the GUID that identifies the image format.
   image->GetRawFormat(&guid);

   // Convert the GUID to a string and display it.
   StringFromGUID2(guid, strGuid, 39);
   wprintf(L"The GUID is %s.\n", strGuid);

   // Did we get the GUID that identifies the JPEG format?
   if(guid == ImageFormatJPEG)
      printf("The format is JPEG.\n");

   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, FakePhoto.jpg, produced the following output:

The GUID is {B96B3CAE-0728-11D3-9D7B-0000F81EF32E}.
The format is JPEG.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, GetType, ImageType
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Image::GetThumbnailImage(thumbWidth, thumbHeight, callback, callbackData)

The GetThumbnailImage method gets a thumbnail image from this Image object.

Image* GetThumbnailImage(
  UINT thumbWidth,
  UINT thumbHeight,
  GetThumbnailImageAbort callback,
  VOID* callbackData
);

Parameters

thumbWidth
[in] Width, in pixels, of the requested thumbnail image.
thumbHeight
[in] Height, in pixels, of the requested thumbnail image.
callback
[in] Optional. Callback function that you provide. During the process of creating or retrieving the thumbnail image, GDI+ calls this function to give you the opportunity to abort the process. The default value is NULL.
callbackData
Optional. Pointer to a block of memory that contains data to be used by the callback function. The default value is NULL.

Return Values

This method returns a pointer to an Image object that contains the thumbnail image.

Remarks

A thumbnail image is a small copy of an image. Some image files have a thumbnail image embedded in the file. In such cases, this method retrieves the embedded thumbnail image. If there is no embedded thumbnail image, this method creates a thumbnail image by scaling the main image to the size specified in the thumbWidth and thumbHeight parameters. If both of those parameters are 0, a system-defined size is used.

Example Code [C++]

The following example creates an Image object based on a JPEG file. The code calls the GetThumbnailImage method of that Image object and then displays the thumbnail image along with the main image.

VOID Example_GetThumbnail(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an image and a thumbnail of the image.
   Image image(L"Crayons.jpg");
   Image* pThumbnail = image.GetThumbnailImage(40, 40, NULL, NULL);

   // Draw the original and the thumbnail images.
   graphics.DrawImage(&image, 10, 10, image.GetWidth(), image.GetHeight());
   graphics.DrawImage(
      pThumbnail,
      150,
      10,
      pThumbnail->GetWidth(),
      pThumbnail->GetHeight());

   delete pThumbnail;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap
Tasks and Examples
Creating Thumbnail Images
Concepts
Images, Bitmaps, and Metafiles


Image::GetType()

The GetType method gets the type (bitmap or metafile) of this Image object.

ImageType GetType(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the ImageType enumeration that indicates the image type.

Example Code [C++]

The following example creates two Image objects: one based on a JPEG file and one based on an EMF file. The code calls the GetType method of each Image object. Then the code verifies that the JPEG file is a bitmap and the EMF file is a metafile.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image1 = new Image(L"FakePhoto.jpg");
   Image* image2 = new Image(L"SampleMetafile.emf");

   ImageType type1 = image1->GetType();
   ImageType type2 = image2->GetType();

   if(type1 == ImageTypeBitmap)
      printf("The type of image1 is ImageTypeBitmap.\n");

   if(type2 == ImageTypeMetafile)
      printf("The type of image2 is ImageTypeMetafile.\n");

   delete image1;
   delete image2;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with two particular files, FakePhoto.jpg and SampleMetafile.emf, produced the following output:

The type of image1 is ImageTypeBitmap.
The type of image2 is ImageTypeMetafile.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
ImageType
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Types of Bitmaps


Image::GetVerticalResolution()

The GetVerticalResolution method gets the vertical resolution, in dots per inch, of this image.

REAL GetVerticalResolution(void);

Parameters

This method has no parameters.

Return Values

This method returns the vertical resolution, in dots per inch, of this image.

Example Code [C++]

The following console application creates an Image object from a JPEG file. The code obtains the vertical resolution of the image, in dots per inch, by calling the GetVerticalResolution method.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image = new Image(L"Crayons.jpg");
   REAL res = image->GetVerticalResolution();
   printf("The vertical resolution is %f dots per inch.\n", res);

   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, GetHeight, GetHorizontalResolution, GetWidth
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Image::GetWidth()

The GetWidth method gets the width, in pixels, of this image.

UINT GetWidth(void);

Parameters

This method has no parameters.

Return Values

This method returns the width, in pixels, of this image.

Example Code [C++]

The following console application creates an Image object based on a JPEG file. The code obtains the width of the image, in pixels, by calling the GetWidth method.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image = new Image(L"Crayons.jpg");
   UINT imageWidth = image->GetWidth();
   printf("The width of the image is %u.\n", imageWidth);

   delete image;

   GdiplusShutdown(gdiplusToken);
   return 0;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, GetHeight, GetHorizontalResolution, GetVerticalResolution
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Image::RemovePropertyItem(propId)

The RemovePropertyItem method removes a property item (piece of metadata) from this Image object.

Status RemovePropertyItem(
  PROPID propId
);

Parameters

propId
[in] Integer that identifies the property item to be removed.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The RemovePropertyItem method removes a specified property from an Image object, but that property item is not removed from the file or stream that was used to construct the Image object. To save the image (with the property item removed) to a new JPEG file or stream, call the Save method of the Image object.

Example Code [C++]

The following example creates an Image object based on a JPEG file. The code removes the PropertyTagEquipMake property item from the Image object by calling its RemovePropertyItem method. The code calls GetPropertyItemSize twice (once before and once after removing the item) to determine the size of the PropertyTagEquipMake property item. The code does not remove the property item from the image file; it removes the property item only from the Image object.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image = new Image(L"FakePhoto3.jpg");
   UINT size = 0;

   size = image->GetPropertyItemSize(PropertyTagEquipMake);
   printf("The size of the PropertyTagEquipMake item is %u.\n", size);

   image->RemovePropertyItem(PropertyTagEquipMake);

   size = image->GetPropertyItemSize(PropertyTagEquipMake);
   printf("The size of the PropertyTagEquipMake item is %u.\n", size);

   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code, along with a particular file, FakePhoto3.jpg, produced the following output:

The size of the PropertyTagEquipMake item is 33.
The size of the PropertyTagEquipMake item is 0.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetAllPropertyItems, GetPropertyCount, GetPropertyIdList, GetPropertyItem, GetPropertyItemSize, GetPropertySize, PropertyItem, SetPropertyItem
Tasks and Examples
Reading and Writing Metadata


Image::RotateFlip(rotateFlipType)

The RotateFlip method rotates and flips this image.

Status RotateFlip(
  RotateFlipType rotateFlipType
);

Parameters

rotateFlipType
[in] Element of the RotateFlipType enumeration that specifies the type of rotation and the type of flip.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates an Image object based on a JPEG file. The code calls the RotateFlip method to rotate the image clockwise 90 degrees and then flip the image vertically. The code draws the image twice: once before and once after the call to RotateFlip.

VOID Example_RotateFlip(HDC hdc)
{
   Graphics graphics(hdc);
   Image image(L"Crayons.jpg");

   graphics.DrawImage(&image, 10, 10, image.GetWidth(), image.GetHeight());
   image.RotateFlip(Rotate90FlipY);
   graphics.DrawImage(&image, 160, 10, image.GetWidth(), image.GetHeight());
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, RotateFlipType
Tasks and Examples
Rotating, Reflecting, and Skewing Images


Image::Save Methods

This topic lists the Save methods of the Image class. For a complete list of methods for the Image class, see Image Methods.

  • Save(filename, clsidEncoder, encoderParams)
  • Save(stream, clsidEncoder, encoderParams)


Image::Save(filename, clsidEncoder, encoderParams)

The Save method saves this image to a file.

Status Save(
  const WCHAR* filename,
  const CLSID* clsidEncoder,
  const EncoderParameters* encoderParams
);

Parameters

filename
[in] Pointer to a null-terminated string that specifies the path name for the saved image.
clsidEncoder
[in] Pointer to a CLSID that specifies the encoder to use to save the image.
encoderParams
[in] Optional. Pointer to an EncoderParameters object that holds parameters used by the encoder. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

GDI+ does not allow you to save an image to the same file that you used to construct the image. The following code creates an Image object by passing the file name MyImage.jpg to an Image constructor. That same file name is passed to the Save method of the Image object, so the Save method fails.

Image image(L"myImage.jpg");

// Do other operations.

// Save the image to the same file name. (This operation will fail.)
image.Save(L"myImage.jpg", ...);

Example Code [C++]

The following example creates an Image object from a PNG file and then creates a Graphics object based on that Image object. The code draws the image, alters the image, and draws the image again. Finally, the code saves the altered image to a file.

The code relies on a helper function, GetEncoderClsid, to get the class identifier for the PNG encoder. The GetEncoderClsid function is shown in Retrieving the Class Identifier for an Encoder.

The technique of constructing a Graphics object based on an image works only for certain image formats. For example, you cannot construct a Graphics object based on an image that has a color depth of 4 bits per pixel. For more information about which formats are supported by the Graphics constructor, see Graphics::Graphics(image).

VOID Example_SaveFile(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object based on a PNG file.
   Image  image(L"Mosaic.png");

   // Draw the image.
   graphics.DrawImage(&image, 10, 10);

   // Construct a Graphics object based on the image.
   Graphics imageGraphics(&image);

   // Alter the image.
   SolidBrush brush(Color(255, 0, 0, 255));
   imageGraphics.FillEllipse(&brush, 20, 30, 80, 50);

   // Draw the altered image.
   graphics.DrawImage(&image, 200, 10);

   // Save the altered image.
   CLSID pngClsid;
   GetEncoderClsid(L"image/png", &pngClsid);
   image.Save(L"Mosaic2.png", &pngClsid, NULL);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
EncoderParameter, EncoderParameters, GetImageEncoders, Save Methods, SaveAdd Methods
Tasks and Examples
Using Image Encoders and Decoders


Image::Save(stream, clsidEncoder, encoderParams)

The Save method saves this image to a stream.

Status Save(
  IStream* stream,
  const CLSID* clsidEncoder,
  const EncoderParameters* encoderParams
);

Parameters

stream
[in] Pointer to an IStream COM interface. The implementation of IStream must include the Seek, Read, Write, and Stat methods.
clsidEncoder
[in] Pointer to a CLSID that specifies the encoder to use to save the image.
encoderParams
[in] Optional. Pointer to an EncoderParameters object that holds parameters used by the encoder. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates two Image objects: one constructed from a JPEG file and one constructed from a PNG file. The code creates a compound file with two streams and saves the two images to those streams.

Status MakeCompoundFile()
{
   IStorage* pIStorage = NULL;
   IStream* pIStream1 = NULL;
   IStream* pIStream2 = NULL;
   HRESULT hr;
   Status stat = Ok;

   // Create two Image objects from existing files.
   Image image1(L"Crayons.jpg");
   Image image2(L"Mosaic.png");

   hr = CoInitialize(NULL);
   if(FAILED(hr))
      goto Exit;

   // Create a compound file object, and get
   // a pointer to its IStorage interface.
   hr = StgCreateDocfile(
      L"CompoundFile.cmp",
      STGM_READWRITE|STGM_CREATE|STGM_SHARE_EXCLUSIVE,
      0,
      &pIStorage);

   if(FAILED(hr))
      goto Exit;

   // Create a stream in the compound file.
   hr = pIStorage->CreateStream(
      L"StreamImage1",
      STGM_READWRITE|STGM_SHARE_EXCLUSIVE,
      0,
      0,
      &pIStream1);

   if(FAILED(hr))
      goto Exit;

   // Create a second stream in the compound file.
   hr = pIStorage->CreateStream(
      L"StreamImage2",
      STGM_READWRITE|STGM_SHARE_EXCLUSIVE,
      0,
      0,
      &pIStream2);

   if(FAILED(hr))
      goto Exit;

   // Get the class identifier for the JPEG encoder.
   CLSID jpgClsid;
   GetEncoderClsid(L"image/jpeg", &jpgClsid);

   // Get the class identifier for the PNG encoder.
   CLSID pngClsid;
   GetEncoderClsid(L"image/png", &pngClsid);

   // Save image1 as a stream in the compound file.
   stat = image1.Save(pIStream1, &jpgClsid);
   if(stat != Ok)
      goto Exit;

   // Save image2 as a stream in the compound file.
   stat = image2.Save(pIStream2, &pngClsid);

Exit:
   if(pIStream1)
      pIStream1->Release();
   if(pIStream2)
      pIStream2->Release();
   if(pIStorage)
      pIStorage->Release();

   if(stat != Ok || FAILED(hr))
      return GenericError;

   return Ok;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
EncoderParameter, EncoderParameters, GetImageEncoders, GetImageEncodersSize, IStorage, IStream, StgOpenStorage, Save Methods, SaveAdd Methods
Tasks and Examples
Using Image Encoders and Decoders


Image::SaveAdd Methods

This topic lists the SaveAdd methods of the Image class. For a complete list of methods for the Image class, see Image Methods.

  • SaveAdd(encoderParams)
  • SaveAdd(newImage, encoderParams)


Image::SaveAdd(encoderParams)

The SaveAdd method adds a frame to a file or stream specified in a previous call to the Save method. Use this method to save selected frames from a multiple-frame image to another multiple-frame image.

Status SaveAdd(
  const EncoderParameters* encoderParams
);

Parameters

encoderParams
[in] Pointer to an EncoderParameters object that holds parameters required by the image encoder used by the save-add operation.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates an Image object based on a TIFF file that has four frames. The code calls the SelectActiveFrame method to navigate to the second frame in the page dimension of that Image object. (The page dimension is the only dimension in this case.) Then the code calls the Save method to save the second frame to a new file named TwoFrames.tif. The code calls the SelectActiveFrame method again to navigate to the fourth frame of the Image object. Then the code calls the SaveAdd method to add the fourth frame to TwoFrames.tif. The code calls the SaveAdd method a second time to close TwoFrames.tif, and then draws the two frames that were saved in that file.

VOID Example_SaveAdd(HDC hdc)
{
   Graphics graphics(hdc);
   EncoderParameters encoderParameters;
   ULONG parameterValue;
   GUID dimension = FrameDimensionPage;

   // An EncoderParameters object has an array of
   // EncoderParameter objects. In this case, there is only
   // one EncoderParameter object in the array.
   encoderParameters.Count = 1;

   // Initialize the one EncoderParameter object.
   encoderParameters.Parameter[0].Guid = EncoderSaveFlag;
   encoderParameters.Parameter[0].Type = EncoderParameterValueTypeLong;
   encoderParameters.Parameter[0].NumberOfValues = 1;
   encoderParameters.Parameter[0].Value = &parameterValue;

   // Get the CLSID of the TIFF encoder.
   CLSID encoderClsid;
   GetEncoderClsid(L"image/tiff", &encoderClsid);

   // Create an image object based on a TIFF file that has four frames.
   Image fourFrames(L"FourFrames.tif");

   // Save the second page (frame).
   parameterValue = EncoderValueMultiFrame;
   fourFrames.SelectActiveFrame(&dimension, 1);
   fourFrames.Save(L"TwoFrames.tif", &encoderClsid, &encoderParameters);

   // Save the fourth page (frame).
   parameterValue = EncoderValueFrameDimensionPage;
   fourFrames.SelectActiveFrame(&dimension, 3);
   fourFrames.SaveAdd(&encoderParameters);

   // Close the multiframe file.
   parameterValue = EncoderValueFlush;
   fourFrames.SaveAdd(&encoderParameters);

   // Draw the two frames of TwoFrames.tif.
   Image twoFrames(L"TwoFrames.tif");
   twoFrames.SelectActiveFrame(&dimension, 0);
   graphics.DrawImage(&twoFrames, 10, 10);
   twoFrames.SelectActiveFrame(&dimension, 1);
   graphics.DrawImage(&twoFrames, 150, 10);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
EncoderParameter, EncoderParameters, GetImageEncoders, Save Methods, SaveAdd Methods
Tasks and Examples
Using Image Encoders and Decoders


Image::SaveAdd(newImage, encoderParams)

The SaveAdd method adds a frame to a file or stream specified in a previous call to the Save method.

Status SaveAdd(
  Image* newImage,
  const EncoderParameters* encoderParams
);

Parameters

newImage
[in] Pointer to an Image object that holds the frame to be added.
encoderParams
[in] Pointer to an EncoderParameters object that contains parameters required by the image encoder used in the save-add operation.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

For a code example, see Creating and Saving a Multiple-Frame Image.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
EncoderParameter, EncoderParameters, GetImageEncoders, Save Methods, SaveAdd Methods, SelectActiveFrame
Tasks and Examples
Using Image Encoders and Decoders


Image::SelectActiveFrame(dimensionID, frameIndex)

The SelectActiveFrame method selects the frame in this Image object specified by a dimension and an index.

Status SelectActiveFrame(
  const GUID* dimensionID,
  UINT frameIndex
);

Parameters

dimensionID
[in] Pointer to a GUID that specifies the frame dimension. GUIDs that identify various frame dimensions are defined in Gdiplusimaging.h.
frameIndex
[in] Integer that specifies the index of the frame within the specified frame dimension.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

When you call the SelectActiveFrame method, all changes that you made to the previously active frame are discarded. If you want to retain changes that you make to a frame, call the Save method before you switch to a different frame.

Among all the image formats currently supported by GDI+, the only formats that support multiple-frame images are GIF and TIFF. When you call the SelectActiveFrame method on a GIF image, you should use FrameDimensionTime. When you call the SelectActiveFrame method on a TIFF image, you should use FrameDimensionPage.

Example Code [C++]

For a code example, see Copying Individual Frames from a Multiple-Frame Image.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
EncoderParameter, EncoderParameters, GetImageEncoders, Save Methods, SaveAdd Methods
Tasks and Examples
Using Image Encoders and Decoders


Image::SetPalette(palette)

The SetPalette method sets the color palette of this Image object.

Status SetPalette(
  const ColorPalette* palette
);

Parameters

palette
[in] Pointer to a ColorPalette structure that specifies the palette.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Bitmap, Color, ColorPalette, GetPaletteSize, GetPalette
Tasks and Examples
Using Images, Bitmaps, and Metafiles
Concepts
Images, Bitmaps, and Metafiles


Image::SetPropertyItem(item)

The SetPropertyItem method sets a property item (piece of metadata) for this Image object. If the item already exists, then its contents are updated; otherwise, a new item is added.

Status SetPropertyItem(
  const PropertyItem* item
);

Parameters

item
[in] Pointer to a PropertyItem object that specifies the property item to be set.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Certain image formats (for example, ICON and EMF) don't support properties. If you call the SetPropertyItem method on an image that doesn't support properties, it will return PropertyNotSupported.

Example Code [C++]

The following console application creates a Image object based on a JPEG file. The code calls the SetPropertyItem method of that Image object to set the title of the image. Then the code retrieves and displays the new title.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   // Create an Image object based on a JPEG file.
   Image* image = new Image(L"FakePhoto.jpg");

   // Set the image title.
   PropertyItem* propItem = new PropertyItem;
   CHAR newTitleValue[] = "Fake Photograph 2";

   propItem->id = PropertyTagImageTitle;
   propItem->length = strlen(newTitleValue);
   propItem->type = PropertyTagTypeASCII;
   propItem->value = newTitleValue;

   image->SetPropertyItem(propItem);

   // Get and display the new image title.
   UINT size = image->GetPropertyItemSize(PropertyTagImageTitle);
   PropertyItem* title = (PropertyItem*)malloc(size);
   image->GetPropertyItem(PropertyTagImageTitle, size, title);
   printf("The image title is %s.\n", title->value);

   free(title);
   delete propItem;
   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetPropertyCount, GetPropertyIdList, GetPropertyItem, GetPropertyItemSize, GetPropertySize, PropertyItem, RemovePropertyItem
Tasks and Examples
Reading and Writing Metadata


ImageAttributes Class

An ImageAttributes object contains information about how bitmap and metafile colors are manipulated during rendering. An ImageAttributes object maintains several color-adjustment settings, including color-adjustment matrices, grayscale-adjustment matrices, gamma-correction values, color-map tables, and color-threshold values.

Inheritance

GdiplusBase
ImageAttributes

Constructors

Constructor | Description
ImageAttributes | Creates and initializes an ImageAttributes object.

Methods

Method | Description
ClearBrushRemapTable | Clears the brush color-remap table for a specified category.
ClearColorKey | Clears the color key for a specified category.
ClearColorMatrices | Clears the color-adjustment matrix and the grayscale-adjustment matrix for a specified category.
ClearColorMatrix | Clears the color-adjustment matrix for a specified category.
ClearGamma | Clears the gamma value for a specified category.
ClearNoOp | Clears the NoOp setting for a specified category.
ClearOutputChannel | Clears the CMYK output channel setting for a specified category.
ClearOutputChannelColorProfile | Clears the output channel color profile setting for a specified category.
ClearRemapTable | Clears the color-remap table for a specified category.
ClearThreshold | Clears the threshold for a specified category.
Clone | Makes a copy of this ImageAttributes object.
GetAdjustedPalette | Gets the color-adjusted palette for a specified category.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
Reset | Resets a category so that it uses the default adjustment settings.
SetBrushRemapTable | Sets the color-remap table for the brush category.
SetColorKey | Sets the color key for a specified category.
SetColorMatrices | Sets the color-adjustment matrix and the grayscale-adjustment matrix for a specified category.
SetColorMatrix | Sets the color-adjustment matrix for a specified category.
SetGamma | Sets the gamma value for a specified category.
SetNoOp | Temporarily clears all adjustment settings for a specified category.
SetOutputChannel | Sets the CMYK output channel for a specified category.
SetOutputChannelColorProfile | Sets the output channel color profile for a specified category.
SetRemapTable | Sets the color-remap table for a specified category.
SetThreshold | Sets the threshold value for a specified category.
SetToIdentity | Sets the color-adjustment matrix of a specified category to the identity matrix.
SetWrapMode | Sets the wrap mode of this ImageAttributes object.
~ImageAttributes | ImageAttributes object destructor.

Remarks

The colors in an image can be manipulated during rendering. They can be corrected, darkened, lightened, removed, and so on. To apply such manipulations, initialize an ImageAttributes object and pass the address of that ImageAttributes object (along with the address of an Image object) to the Graphics::DrawImage method.


ImageAttributes::ImageAttributes()

Creates an ImageAttributes object. This is the default constructor.

ImageAttributes(void);

Parameters

This method has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.


ImageAttributes Methods

This topic lists the methods of the ImageAttributes class. For a complete class listing, see ImageAttributes Class.

  • ClearBrushRemapTable()
  • ClearColorKey(type)
  • ClearColorMatrices(type)
  • ClearColorMatrix(type)
  • ClearGamma(type)
  • ClearNoOp(type)
  • ClearOutputChannel(type)
  • ClearOutputChannelColorProfile(type)
  • ClearRemapTable(type)
  • ClearThreshold(type)
  • Clone()
  • GetAdjustedPalette(colorPalette, colorAdjustType)
  • GetLastStatus()
  • Reset(type)
  • SetBrushRemapTable(mapSize, map)
  • SetColorKey(colorLow, colorHigh, type)
  • SetColorMatrices(colorMatrix, grayMatrix, mode, type)
  • SetColorMatrix(colorMatrix, mode, type)
  • SetGamma(gamma, type)
  • SetNoOp(type)
  • SetOutputChannel(channelFlags, type)
  • SetOutputChannelColorProfile(colorProfileFilename, type)
  • SetRemapTable(mapSize, map, type)
  • SetThreshold(threshold, type)
  • SetToIdentity(type)
  • SetWrapMode(wrap, color, clamp)


ImageAttributes::ClearBrushRemapTable()

The ClearBrushRemapTable method clears the brush color-remap table of this ImageAttributes object.

Status ClearBrushRemapTable(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify one color-remap table for the default category, a different color-remap table for the bitmap category, and still a different color-remap table for the brush category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the brush category, then the default settings apply to the brush category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a default remap table that converts red to green and you specify a default gamma value of 1.8. If you call SetBrushRemapTable, then the default remap table (red to green) and the default gamma value (1.8) will not apply to brushes. If you later call ClearBrushRemapTable, the brush category will not revert to the default remap table; rather, the brush category will have no remap table. Similarly, the brush category will not revert to the default gamma value; rather, the brush category will have no gamma value.

Example Code [C++]

The following example creates an Image object from an EMF file. The code also creates an ImageAttributes object. The call to SetRemapTable sets the default color-remap table of the ImageAttributes object to a table that converts red to blue. The call to SetBrushRemapTable sets the brush remap table of the ImageAttributes object to a table that converts red to green.

The code calls Graphics::DrawImage once to draw the image with no color adjustment. Then the code calls DrawImage three more times, each time passing the address of the Image object and the address of the ImageAttributes object. The second time the image is drawn (after the call to SetRemapTable), all of the red is converted to blue. The third time the image is drawn (after the call to SetBrushRemapTable), all of the red painted with a brush is converted to green, and the rest of the red is converted to blue. The fourth time the image is drawn (after the call to ClearBrushRemapTable), all the red painted with a brush remains unchanged, and the rest of the red is converted to blue.

VOID Example_SetClearBrushRemap(HDC hdc)
{
   Graphics graphics(hdc);

   Image image(L"TestMetafile4.emf");
   ImageAttributes imAtt;

   ColorMap defaultMap;
   defaultMap.oldColor = Color(255, 255, 0, 0);   // red converted to blue
   defaultMap.newColor = Color(255, 0, 0, 255);

   ColorMap brushMap;
   brushMap.oldColor = Color(255, 255, 0, 0);     // red converted to green
   brushMap.newColor = Color(255, 0, 255, 0);

   // Set the default color-remap table.
   imAtt.SetRemapTable(1, &defaultMap, ColorAdjustTypeDefault);

   // Draw the image (metafile) using no color adjustment.
   graphics.DrawImage(
      &image,
      Rect(10, 10, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),          // source rect
      UnitPixel);

   // Draw the image (metafile) using default color adjustment.
   // All red is converted to blue.
   graphics.DrawImage(
      &image,
      Rect(10, 90, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),          // source rect
      UnitPixel,
      &imAtt);

   // Set the brush remap table.
   imAtt.SetBrushRemapTable(1, &brushMap);

   // Draw the image (metafile) using default and brush adjustment.
   // Red painted with a brush is converted to green.
   // All other red is converted to blue (default).
   graphics.DrawImage(
      &image,
      Rect(10, 170, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),           // source rect
      UnitPixel,
      &imAtt);

   // Clear the brush remap table.
   imAtt.ClearBrushRemapTable();

   // Draw the image (metafile) using only default color adjustment.
   // Red painted with a brush gets no color adjustment.
   // All other red is converted to blue (default).
   graphics.DrawImage(
      &image,
      Rect(10, 250, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),           // source rect
      UnitPixel,
      &imAtt);
}

The preceding code, along with a particular file, Testmetafile4.emf, produced the following output. The ellipses in the left column were drawn with a pen, and the ellipses in the right column were filled with a brush. Note that the default remap table applies to the ellipses drawn with a pen. The remap table that applies to the ellipses filled with a brush varies according to the SetBrushRemapTable and ClearBrushRemapTable calls.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ClearRemapTable, Color, ColorAdjustType, ColorMap, Image, Metafile, SetBrushRemapTable, SetRemapTable
Tasks and Examples
Recoloring


ImageAttributes::ClearColorKey(type)

The ClearColorKey method clears the color key (transparency range) for a specified category.

Status ClearColorKey(
  ColorAdjustType type
);

Parameters

type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the color key is cleared. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify one color key for the default category, a different color key for the bitmap category, and still a different color key for the pen category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the pen category, then the default settings apply to the pen category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a default color key that makes any color with a red component from 200 through 255 transparent and you specify a default gamma value of 1.8. If you set the color key of the pen category by calling SetColorKey, then the default color key and the default gamma value will not apply to pens. If you later clear the pen color key by calling ClearColorKey, the pen category will not revert to the default color key; rather, the pen category will have no color key. Similarly, the pen category will not revert to the default gamma value; rather, the pen category will have no gamma value.

Example Code [C++]

The following example creates an Image object from an EMF file. The code also creates an ImageAttributes object. The first call to SetColorKey sets the default color key of the ImageAttributes object so that colors with a red component from 80 through 120 are transparent. The second call to SetColorKey sets the pen color key of the ImageAttributes object so that all colors with a red component from 135 through 175 are transparent.

The code calls Graphics::DrawImage once to draw the image with no color adjustment. Then the code calls DrawImage three more times, each time passing the address of the Image object and the address of the ImageAttributes object. The second time the image is drawn (after the call that sets the default color key), all of the red from 80 through 120 is transparent. The third time the image is drawn (after the call that sets the pen color key), all of the red from 135 through 175 that is drawn with a pen is transparent. Also, all of the red from 80 through 120 that is not drawn with a pen is transparent. The fourth time the image is drawn (after the call to ClearColorKey), none of the red drawn with a pen is transparent. Also, all of the red from 80 through 120 that is not drawn with a pen is transparent.

VOID Example_SetClearColorKey(HDC hdc)
{
   Graphics graphics(hdc);

   Image image(L"TestMetafile5.emf");
   ImageAttributes imAtt;

   // Draw the image (metafile) using no color adjustment.
   graphics.DrawImage(
      &image,
      Rect(0, 0, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),        // source rect
      UnitPixel);

   // Set the default color key.
   imAtt.SetColorKey(
      Color(0, 80, 0, 0),
      Color(255, 120, 255, 255),
      ColorAdjustTypeDefault);

   // Draw the image (metafile) using default color adjustment.
   // Colors with red components from 80 through 120 are transparent.
   graphics.DrawImage(
      &image,
      Rect(0, 100, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),          // source rect
      UnitPixel,
      &imAtt);

   // Set the pen color key.
   imAtt.SetColorKey(
      Color(0, 135, 0, 0),
      Color(255, 175, 255, 255),
      ColorAdjustTypePen);

   // Draw the image (metafile) using default and pen adjustment.
   // Colors drawn with a pen that have red components from 135 through 175
   // are transparent. Colors not drawn with a pen that have red components
   // from 80 to 120 are transparent.
   graphics.DrawImage(
      &image,
      Rect(0, 200, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),          // source rect
      UnitPixel,
      &imAtt);

   // Clear the pen color key.
   imAtt.ClearColorKey(ColorAdjustTypePen);

   // Draw the image (metafile) using only default color adjustment.
   // No colors drawn with a pen are transparent. Colors not drawn with
   // a pen that have red components from 80 to 120 are transparent.
   graphics.DrawImage(
      &image,
      Rect(0, 300, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),          // source rect
      UnitPixel,
      &imAtt);
}

The preceding code, along with a particular file, TestMetafile5.png, produced the following output. The bars in the left column were drawn with a pen, and the bars in the right column were filled with a brush. The default color key applies to the bars filled with a brush. The color key that applies to the bars drawn with a pen varies according to the SetColorKey and ClearColorKey calls.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ClearThreshold, Color, ColorAdjustType, Image, Metafile, SetColorKey, SetThreshold
Tasks and Examples
Recoloring


ImageAttributes::ClearColorMatrices(type)

The ClearColorMatrices method clears the color-adjustment matrix and the grayscale-adjustment matrix for a specified category.

Status ClearColorMatrices(
  ColorAdjustType type
);

Parameters

type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the adjustment matrices are cleared. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify a pair (color and grayscale) of adjustment matrices for the default category, a different pair of adjustment matrices for the bitmap category, and still a different pair of adjustment matrices for the pen category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the pen category, then the default settings apply to the pen category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a pair (color and grayscale) of adjustment matrices and a gamma value for the default category. If you set a pair of adjustment matrices for the pen category by calling SetColorMatrices, then the default adjustment matrices will not apply to pens. If you later clear the pen adjustment matrices by calling ClearColorMatrices, the pen category will not revert to the default adjustment matrices; rather, the pen category will have no adjustment matrices. Similarly, the pen category will not revert to the default gamma value; rather, the pen category will have no gamma value.

Example Code [C++]

The following example creates an Image object from an EMF file. The code also creates an ImageAttributes object. The first call to SetColorMatrices sets the default color-adjustment matrix and the default grayscale-adjustment matrix of the ImageAttributes object. The second call to SetColorMatrices sets the pen color-adjustment matrix and the pen grayscale-adjustment matrix of the ImageAttributes object. The four matrices perform as follows:

  • Default color: multiplies the red component by 1.5.
  • Default grayscale: multiplies the green component by 1.5.
  • Pen color: multiplies the blue component by 1.5.
  • Pen grayscale: multiplies red, green, and blue components by 1.5.

The code calls Graphics::DrawImage once to draw the image with no color adjustment. Then the code calls DrawImage three more times, each time passing the address of the Image object and the address of the ImageAttributes object. The second time the image is drawn (after the call that sets the default matrices), all the colors have their red components increased by 50 percent, and all the grays have their green components increased by 50 percent. The third time the image is drawn (after the call that sets the pen matrices), all the colors drawn by a pen have their blue components increased by 50 percent, and all the grays drawn by a pen have their red, green, and blue components increased by 50 percent. The fourth time the image is drawn (after the call to ClearColorMatrices), no adjustments are applied to colors and grays drawn by a pen.

VOID Example_SetClearColorMatrices(HDC hdc)
{
   Graphics graphics(hdc);

   Image            image(L"TestMetafile6.emf");
   ImageAttributes  imAtt;
   RectF            rect;
   Unit             unit;

   image.GetBounds(&rect, &unit);

   ColorMatrix defaultColorMatrix = {  // Multiply red component by 1.5.
      1.5f,  0.0f,  0.0f,  0.0f,  0.0f,
      0.0f,  1.0f,  0.0f,  0.0f,  0.0f,
      0.0f,  0.0f,  1.0f,  0.0f,  0.0f,
      0.0f,  0.0f,  0.0f,  1.0f,  0.0f,
      0.0f,  0.0f,  0.0f,  0.0f,  1.0f};

   ColorMatrix defaultGrayMatrix = {  // Multiply green component by 1.5.
      1.0f,  0.0f,  0.0f,  0.0f,  0.0f,
      0.0f,  1.5f,  0.0f,  0.0f,  0.0f,
      0.0f,  0.0f,  1.0f,  0.0f,  0.0f,
      0.0f,  0.0f,  0.0f,  1.0f,  0.0f,
      0.0f,  0.0f,  0.0f,  0.0f,  1.0f};

   ColorMatrix penColorMatrix = {     // Multiply blue component by 1.5.
      1.0f,  0.0f,  0.0f,  0.0f,  0.0f,
      0.0f,  1.0f,  0.0f,  0.0f,  0.0f,
      0.0f,  0.0f,  1.5f,  0.0f,  0.0f,
      0.0f,  0.0f,  0.0f,  1.0f,  0.0f,
      0.0f,  0.0f,  0.0f,  0.0f,  1.0f};

   ColorMatrix penGrayMatrix = {      // Multiply all components by 1.5.
      1.5f,  0.0f,  0.0f,  0.0f,  0.0f,
      0.0f,  1.5f,  0.0f,  0.0f,  0.0f,
      0.0f,  0.0f,  1.5f,  0.0f,  0.0f,
      0.0f,  0.0f,  0.0f,  1.0f,  0.0f,
      0.0f,  0.0f,  0.0f,  0.0f,  1.0f};

   // Set the default color- and grayscale-adjustment matrices.
   imAtt.SetColorMatrices(
      &defaultColorMatrix,
      &defaultGrayMatrix,
      ColorMatrixFlagsAltGray,
      ColorAdjustTypeDefault);

   graphics.DrawImage(&image, 10.0f, 10.0f, rect.Width, rect.Height);

   graphics.DrawImage(
      &image,
      RectF(10.0f, 50.0f, rect.Width, rect.Height),  // destination rectangle
      rect.X, rect.Y,                // upper-left corner of source rectangle
      rect.Width,                    // width of source rectangle
      rect.Height,                   // height of source rectangle
      UnitPixel,
      &imAtt);

   // Set the pen color- and grayscale-adjustment matrices.
   imAtt.SetColorMatrices(
      &penColorMatrix,
      &penGrayMatrix,
      ColorMatrixFlagsAltGray,
      ColorAdjustTypePen);

   graphics.DrawImage(
      &image,
      RectF(10.0f, 90.0f, rect.Width, rect.Height),  // destination rectangle
      rect.X, rect.Y,                // upper-left corner of source rectangle
      rect.Width,                    // width of source rectangle
      rect.Height,                   // height of source rectangle
      UnitPixel,
      &imAtt);

   imAtt.ClearColorMatrices(ColorAdjustTypePen);

   graphics.DrawImage(
      &image,
      RectF(10.0f, 130.0f, rect.Width, rect.Height),  // destination rectangle
      rect.X, rect.Y,                // upper-left corner of source rectangle
      rect.Width,                    // width of source rectangle
      rect.Height,                   // height of source rectangle
      UnitPixel,
      &imAtt);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ClearColorMatrix, Color, ColorAdjustType, ColorMatrix, Image, Metafile, SetColorMatrices, SetColorMatrix, SetToIdentity
Tasks and Examples
Recoloring


ImageAttributes::ClearColorMatrix(type)

The ClearColorMatrix method clears the color-adjustment matrix for a specified category.

Status ClearColorMatrix(
  ColorAdjustType type
);

Parameters

type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the color-adjustment matrix is cleared. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify a color-adjustment matrix for the default category, a different color-adjustment matrix for the bitmap category, and still a different color-adjustment matrix for the pen category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the pen category, then the default settings apply to the pen category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a color-adjustment matrix and a gamma value for the default category. If you set a color-adjustment matrix for the pen category by calling SetColorMatrix, then the default color-adjustment matrix will not apply to pens. If you later clear the pen color-adjustment matrix by calling ClearColorMatrix, the pen category will not revert to the default adjustment matrix; rather, the pen category will have no adjustment matrix. Similarly, the pen category will not revert to the default gamma value; rather, the pen category will have no gamma value.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ClearColorMatrices, Color, ColorAdjustType, ColorMatrix, Image, Metafile, SetColorMatrices, SetColorMatrix, SetToIdentity
Tasks and Examples
Recoloring


ImageAttributes::ClearGamma(type)

The ClearGamma method disables gamma correction for a specified category.

Status ClearGamma(
  ColorAdjustType type
);

Parameters

type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which gamma correction is disabled. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify a gamma value for the default category, a different gamma value for the bitmap category, and still a different gamma value for the pen category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the pen category, then the default settings apply to the pen category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a gamma value and a color-adjustment matrix for the default category. If you set the gamma value for the pen category by calling SetGamma, then the default gamma value will not apply to pens. If you later clear the pen gamma value by calling ClearGamma, the pen category will not revert to the default gamma value; rather, the pen category will have no gamma value. Similarly, the pen category will not revert to the default color-adjustment matrix; rather, the pen category will have no color-adjustment matrix.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ColorAdjustType, Image, Metafile, SetGamma
Tasks and Examples
Recoloring


ImageAttributes::ClearNoOp(type)

The ClearNoOp method clears the NoOp setting for a specified category.

Status ClearNoOp(
  ColorAdjustType type
);

Parameters

type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the NoOp setting is cleared. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

You can disable color adjustment for a certain object type by calling the SetNoOp method. Later, you can reinstate color adjustment for that object type by calling the ClearNoOp method. For example, the following statement disables color adjustment for brushes:

myImageAttributes.SetNoOp(ColorAdjustTypeBrush);

The following statement reinstates the brush color adjustment that was in place before the call to SetNoOp:

myImageAttributes.ClearNoOp(ColorAdjustTypeBrush);

Example Code [C++]

The following example creates an Image object from an EMF file. The code also creates an ImageAttributes object. The SetColorMatrix call sets the brush color-adjustment matrix of that ImageAttributes object to a matrix that converts red to green.

The code calls Graphics::DrawImage three times, each time passing the address of the Image object and the address of the ImageAttributes object. When the image is drawn the first time, all the red painted by brushes is converted to green. (The red drawn by pens is not changed.) Before the image is drawn the second time, the code calls the SetNoOp method of the ImageAttributes object. So when the image is drawn the second time, no color adjustment is applied to brushes. Before the image is drawn the third time, the code calls the ClearNoOp method, which reinstates the brush color-adjustment settings. So when the image is drawn the third time, all the red painted by brushes is converted to green.

VOID Example_SetClearNoOp(HDC hdc)
{
   Graphics graphics(hdc);

   Image image(L"TestMetafile4.emf");
   ImageAttributes imAtt;

    ColorMatrix brushMatrix = {     // red converted to green
      0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
      0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
      0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
      0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
      0.0f, 0.0f, 0.0f, 0.0f, 1.0f};

   imAtt.SetColorMatrix(
      &brushMatrix,
      ColorMatrixFlagsDefault,
      ColorAdjustTypeBrush);

   // Draw the image (metafile) using brush color adjustment.
   // Items filled with a brush change from red to green.
   graphics.DrawImage(
      &image,
      Rect(0, 0, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),        // source rect
      UnitPixel,
      &imAtt);

   // Temporarily disable brush color adjustment.
   imAtt.SetNoOp(ColorAdjustTypeBrush);

   // Draw the image (metafile) without brush color adjustment.
   // There is no change from red to green.
   graphics.DrawImage(
      &image,
      Rect(0, 80, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),          // source rect
      UnitPixel,
      &imAtt);

   // Reinstate brush color adjustment.
   imAtt.ClearNoOp(ColorAdjustTypeBrush);

   // Draw the image (metafile) using brush color adjustment.
   // Items filled with a brush change from red to green.
   graphics.DrawImage(
      &image,
      Rect(0, 160, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),          // source rect
      UnitPixel,
      &imAtt);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ColorAdjustType, Image, Metafile, Reset, SetNoOp, SetToIdentity
Tasks and Examples
Recoloring


ImageAttributes::ClearOutputChannel(type)

The ClearOutputChannel method clears the CMYK output channel setting for a specified category.

Status ClearOutputChannel(
  ColorAdjustType type
);

Parameters

type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the output channel setting is cleared. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify an output channel for the default category and a different output channel for the bitmap category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the bitmap category, then the default settings apply to the bitmap category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify an output channel and an adjustment matrix for the default category. If you set the output channel for the bitmap category by calling SetOutputChannel, then the default output channel will not apply to bitmaps. If you later clear the bitmap output channel by calling ClearOutputChannel, the bitmap category will not revert to the default output channel; rather, the bitmap category will have no output channel setting. Similarly, the bitmap category will not revert to the default color-adjustment matrix; rather, the bitmap category will have no color-adjustment matrix.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
ClearOutputChannelColorProfile, ColorAdjustType, ColorChannelFlags, SetOutputChannel, SetOutputChannelColorProfile


ImageAttributes::ClearOutputChannelColorProfile(type)

The ClearOutputChannelColorProfile method clears the output channel color profile setting for a specified category.

Status ClearOutputChannelColorProfile(
  ColorAdjustType type
);

Parameters

type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the output channel profile setting is cleared. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify an output channel profile for the default category and a different output channel profile for the bitmap category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the bitmap category, then the default settings apply to the bitmap category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify an output channel profile and an adjustment matrix for the default category. If you set the output channel profile for the bitmap category by calling SetOutputChannelColorProfile, then the default output channel profile will not apply to bitmaps. If you later clear the bitmap output channel profile by calling ClearOutputChannelColorProfile, the bitmap category will not revert to the default output channel profile; rather, the bitmap category will have no output channel profile setting. Similarly, the bitmap category will not revert to the default color-adjustment matrix; rather, the bitmap category will have no color-adjustment matrix.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
ClearOutputChannel, ColorAdjustType, ColorChannelFlags, SetOutputChannel, SetOutputChannelColorProfile


ImageAttributes::ClearRemapTable(type)

The ClearRemapTable method clears the color-remap table for a specified category.

Status ClearRemapTable(
  ColorAdjustType type
);

Parameters

type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the remap table is cleared. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify a remap table for the default category, a different remap table for the bitmap category, and still a different remap table for the pen category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the pen category, then the default settings apply to the pen category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a remap table and a gamma value for the default category. If you set the remap table for the pen category by calling SetRemapTable, then the default remap table will not apply to pens. If you later clear the pen remap table by calling ClearRemapTable, the pen category will not revert to the default remap table; rather, the pen category will have no remap table. Similarly, the pen category will not revert to the default gamma value; rather, the pen category will have no gamma value.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, Color, ColorMap, ColorAdjustType, Image, Metafile, SetRemapTable
Tasks and Examples
Recoloring


ImageAttributes::ClearThreshold(type)

The ClearThreshold method clears the threshold value for a specified category.

Status ClearThreshold(
  ColorAdjustType type
);

Parameters

type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the threshold is cleared. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The threshold is a value from 0 through 1 that specifies a cutoff point for each color component. For example, suppose the threshold is set to 0.7, and suppose you are rendering a color whose red, green, and blue components are 230, 50, and 220. The red component, 230, is greater than 0.7×255, so the red component will be changed to 255 (full intensity). The green component, 50, is less than 0.7×255, so the green component will be changed to 0. The blue component, 220, is greater than 0.7×255, so the blue component will be changed to 255.

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify a threshold for the default category, a different threshold for the bitmap category, and still a different threshold for the pen category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the pen category, then the default settings apply to the pen category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a threshold and a gamma value for the default category. If you set the threshold for the pen category by calling SetThreshold, then the default threshold will not apply to pens. If you later clear the pen threshold by calling ClearThreshold, the pen category will not revert to the default threshold; rather, the pen category will have no threshold. Similarly, the pen category will not revert to the default gamma value; rather, the pen category will have no gamma value.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ClearColorKey, ColorAdjustType, Image, Metafile, SetColorKey, SetThreshold
Tasks and Examples
Recoloring


ImageAttributes::Clone()

The Clone method makes a copy of this ImageAttributes object.

ImageAttributes* Clone(void);

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new ImageAttributes object.

Example Code [C++]

The following example clones an ImageAttributes object:

ImageAttributes imageAttr;
ImageAttributes* pImageAttr2 = imageAttr.Clone();

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, Image, Metafile
Tasks and Examples
Recoloring


ImageAttributes::GetAdjustedPalette(colorPalette, colorAdjustType)

The GetAdjustedPalette method adjusts the colors in a palette according to the adjustment settings of a specified category.

Status GetAdjustedPalette(
  ColorPalette* colorPalette,
  ColorAdjustType colorAdjustType
);

Parameters

colorPalette
[in, out] Pointer to a ColorPalette structure that on input, contains the palette to be adjusted and, on output, receives the adjusted palette.
colorAdjustType
[in] Element of the ColorAdjustType enumeration that specifies the category whose adjustment settings will be applied to the palette.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify a color-remap table for the default category, a different color-remap table for the bitmap category, and still a different color-remap table for the pen category.

When you call GetAdjustedPalette, you can specify the adjustment category that is used to adjust the palette colors. For example, if you pass ColorAdjustTypeBitmap to the GetAdjustedPalette method, then the adjustment settings of the bitmap category are used to adjust the palette colors.

Example Code [C++]

The following example initializes a ColorPalette structure with four colors: aqua, black, red, and green. The code also creates an ImageAttributes object and sets its bitmap remap table so that green will be converted to blue. Then the code adjusts the palette colors by passing the address of the palette to the GetAdjustedPalette method of the ImageAttributes object. The code displays the four palette colors twice: once before the adjustment and once after the adjustment.

VOID Example_GetAdjustedPalette(HDC hdc)
{
   Graphics graphics(hdc);
   INT j;

   // Create a palette that has four entries.
   ColorPalette* palette =
      (ColorPalette*)malloc(sizeof(ColorPalette) + 3 * sizeof(ARGB));
   palette->Flags = 0;
   palette->Count = 4;

   palette->Entries[0] = 0xFF00FFFF;   // aqua
   palette->Entries[1] = 0xFF000000;   // black
   palette->Entries[2] = 0xFFFF0000;   // red
   palette->Entries[3] = 0xFF00FF00;   // green

   // Display the four palette colors with no adjustment.
   SolidBrush brush(Color());
   for(j = 0; j < 4; ++j)
   {
      brush.SetColor(palette->Entries[j]);
      graphics.FillRectangle(&brush, 30*j, 0, 20, 20);
   }

   // Create a remap table that converts green to blue.
   ColorMap map;
      map.oldColor = Color(255, 0, 255, 0);  // green
      map.newColor = Color(255, 0, 0, 255);  // blue

   // Create an ImageAttributes object, and set its bitmap remap table.
   ImageAttributes imAtt;
   imAtt.SetRemapTable(1, &map, ColorAdjustTypeBitmap);

   // Adjust the palette.
   imAtt.GetAdjustedPalette(palette, ColorAdjustTypeBitmap);

   // Display the four palette colors after the adjustment.
   for(j = 0; j < 4; ++j)
   {
      brush.SetColor(palette->Entries[j]);
      graphics.FillRectangle(&brush, 30*j, 30, 20, 20);
   }
}

The following illustration shows the output of the preceding code. Note that the green in the original palette was changed to blue.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, Color, ColorAdjustType, ColorMap, ColorPalette, Image, Metafile, PaletteFlags
Tasks and Examples
Recoloring


ImageAttributes::GetLastStatus()

The GetLastStatus method returns a value that indicates the nature of this ImageAttributes object's most recent method failure.

Status GetLastStatus(void);

Parameters

This method has no parameters.

Return Values

The GetLastStatus method returns an element of the Status enumeration.

If no methods invoked on this ImageAttributes object have failed since the previous call to GetLastStatus, then GetLastStatus returns Ok.

If at least one method invoked on this ImageAttributes object has failed since the previous call to GetLastStatus, then GetLastStatus returns a value that indicates the nature of the most recent failure.

Remarks

You can call GetLastStatus immediately after constructing a ImageAttributes object to determine whether the constructor succeeded.

The first time you call the GetLastStatus method of a ImageAttributes object, it returns Ok if the constructor succeeded and all methods invoked so far on the ImageAttributes object succeeded. Otherwise, it returns a value that indicates the nature of the most recent failure.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Status


ImageAttributes::Reset(type)

The Reset method clears all color- and grayscale-adjustment settings for a specified category.

Status Reset(
  ColorAdjustType type
);

Parameters

type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which color adjustment is reset. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify a gamma value for the default category, a different gamma value for the bitmap category, and still a different gamma value for the pen category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the pen category, then the default settings apply to the pen category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. You can reinstate the default settings for that category by calling Reset. For example, suppose you specify a gamma value for the default category. If you set the gamma value for the pen category by calling SetGamma, then the default gamma value will not apply to pens. If you later pass ColorAdjustTypePen to the Reset method, the pen category will revert to the default gamma value.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ClearNoOp, ColorAdjustType, Image, Metafile, SetNoOp
Tasks and Examples
Recoloring


ImageAttributes::SetBrushRemapTable(mapSize, map)

The SetBrushRemapTable method sets the color remap table for the brush category.

Status SetBrushRemapTable(
  UINT mapSize,
  ColorMap* map
);

Parameters

mapSize
[in] Integer that specifies the number of elements in the map array.
map
[in] Pointer to an array of ColorMap structures.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A color-remap table is an array of ColorMap structures. Each ColorMap structure has two Color objects: one that specifies an old color and one that specifies a corresponding new color. During rendering, any color that matches one of the old colors in the remap table is changed to the corresponding new color.

Calling the SetBrushRemapTable method has the same effect as passing ColorAdjustTypeBrush to the SetRemapTable method. The specified remap table applies to items in metafiles that are filled with a brush.

Example Code [C++]

The following example creates an ImageAttributes object and sets its brush remap table so that red is converted to green.

ImageAttributes imageAtt;
ColorMap cMap;
cMap.oldColor = Color(255, 255, 0, 0);  // red
cMap.newColor = Color(255, 0, 255, 0);  // green
imageAtt.SetBrushRemapTable(1, &cMap);

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, Color, ColorAdjustType, ColorMap, Image, Metafile
Tasks and Examples
Recoloring


ImageAttributes::SetColorKey(colorLow, colorHigh, type)

The SetColorKey method sets the color key (transparency range) for a specified category.

Status SetColorKey(
  const Color& colorLow,
  const Color& colorHigh,
  ColorAdjustType type
);

Parameters

colorLow
[in] Reference to a Color object that specifies the low color-key value.
colorHigh
[in] Reference to a Color object that specifies the high color-key value.›
type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the color key is set. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

This method sets the high and low color-key values so that arange of colors can be made transparent. Any color that has each of its three components (red, green, blue) between the corresponding components of the high and low color keys is made transparent.

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify a color key for the default category, a different color key for the bitmap category, and still a different color key for the pen category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the pen category, then the default settings apply to the pen category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a collection of adjustment settings for the default category. If you set the color key for the pen category by passing ColorAdjustTypePen to the SetColorKey method, then none of the default adjustment settings will apply to pens.

Example Code [C++]

The following example creates an Image object from a BMP file. The code also creates an ImageAttributes object. The call to SetColorKey sets the bitmap color key of the ImageAttributes object so that any color that satisfies all three of the following conditions is made transparent:

  • The red component is in the range 100 through 250.
  • The green component is in the range 95 through 245.
  • The blue component is in the range 30 through 60.
VOID Example_SetColorKey(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object based on a BMP file.
   // The image has three horizontal stripes.
   // The color of the top stripe has RGB components (90, 90, 20).
   // The color of the middle stripe has RGB components (150, 150, 150).
   // The color of the bottom stripe has RGB components (130, 130, 40).
   Image image(L"ColorKeyTest.bmp");

   // Create an ImageAttributes object, and set its color key.
   ImageAttributes imAtt;
   imAtt.SetColorKey(
      Color(100, 95, 30),
      Color(250, 245, 60),
      ColorAdjustTypeBitmap);

   // Draw the image. Apply the color key.
   // The bottom stripe of the image will be transparent because
   // 100 <= 130 <= 250 and
   // 95  <= 130 <= 245 and
   // 30  <= 40  <= 60.
   graphics.DrawImage(
      &image,
      Rect(20, 20, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),          // source rect
      UnitPixel,
      &imAtt);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ClearColorKey, ClearThreshold, Color, ColorAdjustType, Image, Metafile, SetThreshold
Tasks and Examples
Recoloring


ImageAttributes::SetColorMatrices(colorMatrix, grayMatrix, mode, type)

The SetColorMatrices method sets the color-adjustment matrix and the grayscale-adjustment matrix for a specified category.

Status SetColorMatrices(
  const ColorMatrix* colorMatrix,
  const ColorMatrix* grayMatrix,
  ColorMatrixFlags mode,
  ColorAdjustType type
);

Parameters

colorMatrix
[in] Pointer to a 5×5 color-adjustment matrix.
grayMatrix
[in] Pointer to a 5×5 grayscale-adjustment matrix.
mode
[in] Optional. Element of the ColorMatrixFlags enumeration that specifies the type of image and color that will be affected by the color-adjustment and grayscale-adjustment matrices. The default value is ColorMatrixFlagsDefault.
type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the color-adjustment and grayscale-adjustment matrices are set. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify adjustment matrices for the default category, different adjustment matrices for the bitmap category, and still different adjustment matrices for the pen category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the pen category, then the default settings apply to the pen category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a collection of adjustment settings for the default category. If you set the color-adjustment and grayscale-adjustment matrices for the pen category by passing ColorAdjustTypePen to the SetColorMatrices method, then none of the default adjustment settings will apply to pens.

Example Code [C++]

For an example of calling SetColorMatrices, see ClearColorMatrices.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ClearColorMatrices, ClearColorMatrix, Color, ColorAdjustType, ColorMatrix, Image, Metafile, SetColorMatrix, SetToIdentity
Tasks and Examples
Recoloring


ImageAttributes::SetColorMatrix(colorMatrix, mode, type)

The SetColorMatrix method sets the color-adjustment matrix for a specified category.

Status SetColorMatrix(
  const ColorMatrix* colorMatrix,
  ColorMatrixFlags mode,
  ColorAdjustType type
);

Parameters

colorMatrix
[in] Pointer to a 5×5 color-adjustment matrix.
mode
[in] Element of the ColorMatrixFlags enumeration that specifies the type of image and color that will be affected by the color-adjustment matrix.
type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the color-adjustment matrix is set. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify a color-adjustment matrix for the default category, a different color-adjustment matrix for the bitmap category, and still a different color-adjustment matrix for the pen category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the pen category, then the default settings apply to the pen category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a collection of adjustment settings for the default category. If you set the color-adjustment matrix for the pen category by passing ColorAdjustTypePen to the SetColorMatrix method, then none of the default adjustment settings will apply to pens.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ClearColorMatrices, ClearColorMatrix, Color, ColorAdjustType, ColorMatrix, Image, Metafile, SetColorMatrices, SetToIdentity
Tasks and Examples
Recoloring


ImageAttributes::SetGamma(gamma, type)

The SetGamma method sets the gamma value for a specified category.

Status SetGamma(
  REAL gamma,
  ColorAdjustType type
);

Parameters

gamma
[in] Real number that specifies the gamma value.
type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the gamma value is set. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify a gamma value for the default category, a different gamma value for the bitmap category, and still a different gamma value for the pen category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the pen category, then the default settings apply to the pen category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a collection of adjustment settings for the default category. If you set the gamma value for the pen category by passing ColorAdjustTypePen to the SetGamma method, then none of the default adjustment settings will apply to pens.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ClearGamma, ColorAdjustType, Image, Metafile
Tasks and Examples
Recoloring


ImageAttributes::SetNoOp(type)

The SetNoOp method turns off color adjustment for a specified category. You can call ClearNoOp to reinstate the color-adjustment settings that were in place before the call to SetNoOp.

Status SetNoOp(
  ColorAdjustType type
);

Parameters

type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which color correction is turned off. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates an Image object from an EMF file. The code also creates an ImageAttributes object. The SetColorMatrix call sets the brush color-adjustment matrix of that ImageAttributes object to a matrix that converts red to green.

The code calls Graphics::DrawImage three times, each time passing the address of the Image object and the address of the ImageAttributes object. When the image is drawn the first time, all the red painted by brushes is converted to green. (The red drawn by pens is not changed.) Before the image is drawn the second time, the code calls the SetNoOp method of the ImageAttributes object. So when the image is drawn the second time, no color adjustment is applied to brushes. Before the image is drawn the third time, the code calls the ClearNoOp method, which reinstates the brush color adjustment settings. So when the image is drawn the third time, all the red painted by brushes is converted to green.

VOID Example_SetClearNoOp(HDC hdc)
{
   Graphics graphics(hdc);

   Image image(L"TestMetafile4.emf");
   ImageAttributes imAtt;

    ColorMatrix brushMatrix = {     // red converted to green
      0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
      0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
      0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
      0.0f, 0.0f, 0.0f, 1.0f, 0.0f,
      0.0f, 0.0f, 0.0f, 0.0f, 1.0f};

   imAtt.SetColorMatrix(
      &brushMatrix,
      ColorMatrixFlagsDefault,
      ColorAdjustTypeBrush);

   // Draw the image (metafile) using brush color adjustment.
   // Items filled with a brush change from red to green.
   graphics.DrawImage(
      &image,
      Rect(0, 0, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),        // source rect
      UnitPixel,
      &imAtt);

   // Temporarily disable brush color adjustment.
   imAtt.SetNoOp(ColorAdjustTypeBrush);

   // Draw the image (metafile) without brush color adjustment.
   // There is no change from red to green.
   graphics.DrawImage(
      &image,
      Rect(0, 80, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),          // source rect
      UnitPixel,
      &imAtt);

   // Reinstate brush color adjustment.
   imAtt.ClearNoOp(ColorAdjustTypeBrush);

   // Draw the image (metafile) using brush color adjustment.
   // Items filled with a brush change from red to green.
   graphics.DrawImage(
      &image,
      Rect(0, 160, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),          // source rect
      UnitPixel,
      &imAtt);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ClearNoOp, ColorAdjustType, Image, Metafile, Reset, SetToIdentity
Tasks and Examples
Recoloring


ImageAttributes::SetOutputChannel(channelFlags, type)

The SetOutputChannel method sets the CMYK output channel for a specified category.

Status SetOutputChannel(
  ColorChannelFlags channelFlags,
  ColorAdjustType type
);

Parameters

channelFlags
[in] Element of the ColorChannelFlags enumeration that specifies the output channel.
type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the output channel is set. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

You can use the SetOutputChannel method to convert an image to a CMYK (cyan, magenta, yellow, black) color space and examine the intensities of one of the CMYK color channels. For example, suppose you create an ImageAttributes object and set its bitmap output channel to ColorChannelFlagsC. If you pass the address of that ImageAttributes object to the Graphics::DrawImage method, the cyan component of each pixel is calculated, and each pixel in the rendered image is a shade of gray that indicates the intensity of its cyan channel. Similarly, you can render images that indicate the intensities of the magenta, yellow, and black channels.

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify an output channel for the default category and a different output channel for the bitmap category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the bitmap category, then the default settings apply to the bitmap category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a collection of adjustment settings for the default category. If you set the output channel for the bitmap category by passing ColorAdjustTypeBitmap to the SetOutputChannel method, then none of the default adjustment settings will apply to bitmaps.

Example Code [C++]

The following example creates an Image object and calls the Graphics::DrawImage method to draw the image. Then the code creates an ImageAttributes object and sets its bitmap output channel to cyan (ColorChannelFlagsC). The code calls DrawImage a second time, passing the address of the Image object and the address of the ImageAttributes object. The cyan channel of each pixel is calculated, and the rendered image shows the intensities of the cyan channel as shades of gray. The code calls DrawImage three more times to show the intensities of the magenta, yellow, and black channels.

VOID Example_SetOutputChannel(HDC hdc)
{
   Graphics graphics(hdc);

   Image image(L"Mosaic2.bmp");

   // Draw the image unaltered.
   graphics.DrawImage(&image, 10, 10, width, height);

   UINT width = image.GetWidth();
   UINT height = image.GetHeight();

   ImageAttributes imAtt;

   // Draw the image, showing the intensity of the cyan channel.
   imAtt.SetOutputChannel(ColorChannelFlagsC, ColorAdjustTypeBitmap);
   graphics.DrawImage(
      &image,
      Rect(110, 10, width, height),  // dest rect
      0, 0, width, height,           // source rect
      UnitPixel,
      &imAtt);

   // Draw the image, showing the intensity of the magenta channel.
   imAtt.SetOutputChannel(ColorChannelFlagsM, ColorAdjustTypeBitmap);
   graphics.DrawImage(
      &image,
      Rect(210, 10, width, height),  // dest rect
      0, 0, width, height,           // source rect
      UnitPixel,
      &imAtt);

   // Draw the image, showing the intensity of the yellow channel.
   imAtt.SetOutputChannel(ColorChannelFlagsY, ColorAdjustTypeBitmap);
   graphics.DrawImage(
      &image,
      Rect(10, 110, width, height),  // dest rect
      0, 0, width, height,           // source rect
      UnitPixel,
      &imAtt);

   // Draw the image, showing the intensity of the black channel.
   imAtt.SetOutputChannel(ColorChannelFlagsK, ColorAdjustTypeBitmap);
   graphics.DrawImage(
      &image,
      Rect(110, 110, width, height),  // dest rect
      0, 0, width, height,            // source rect
      UnitPixel,
      &imAtt);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
ClearOutputChannel, ClearOutputChannelColorProfile, ColorAdjustType, ColorChannelFlags, SetOutputChannelColorProfile


ImageAttributes::SetOutputChannelColorProfile(colorProfileFilename, type)

The SetOutputChannelColorProfile method sets the output channel color-profile file for a specified category.

Status SetOutputChannelColorProfile(
  const WCHAR* colorProfileFilename,
  ColorAdjustType type
);

Parameters

colorProfileFilename
[in] Path name of a color-profile file. If the color-profile file is in the %SystemRoot%\System32\Spool\Drivers\Color directory, then this parameter can be the file name. Otherwise, this parameter must be the fully-qualified path name.
type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the output channel color-profile file is set. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

You can use the SetOutputChannel and SetOutputChannelColorProfile methods to convert an image to a CMYK (cyan, magenta, yellow, black) color space and examine the intensities of one of the CMYK color channels. For example, suppose you write code that performs the following steps:

  1. Create an Image object.
  2. Create an ImageAttributes object.
  3. Pass ColorChannelFlagsC to the SetOutputChannel method of the ImageAttributes object.
  4. Pass the path name of a color profile file to the SetOutputChannelColorProfile method of the ImageAttributes object.
  5. Pass the addresses of the Image and ImageAttributes objects to the Graphics::DrawImage method.

GDI+ will use the color-profile file to calculate the cyan component of each pixel in the image, and each pixel in the rendered image will be a shade of gray that indicates the intensity of its cyan channel.

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify an output channel color-profile file for the default category and a different output channel color-profile file for the bitmap category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the bitmap category, then the default settings apply to the bitmap category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a collection of adjustment settings for the default category. If you set the output channel color-profile file for the bitmap category by passing ColorAdjustTypeBitmap to the SetOutputChannelColorProfile method, then none of the default adjustment settings will apply to bitmaps.

Example Code [C++]

The following example creates an Image object and calls the Graphics::DrawImage method to draw the image. Then the code creates an ImageAttributes object and calls its SetOutputChannelColorProfile method to specify a profile file for the bitmap category. The call to SetOutputChannel sets the output channel (for the bitmap category) to cyan. The code calls DrawImage a second time, passing the address of the Image object and the address of the ImageAttributes object. The cyan channel of each pixel is calculated, and the rendered image shows the intensities of the cyan channel as shades of gray. The code calls DrawImage three more times to show the intensities of the magenta, yellow, and black channels.

VOID Example_SetOutputProfile(HDC hdc)
{
   Graphics graphics(hdc);

   Image image(L"Mosaic2.bmp");
   ImageAttributes imAtt;
   UINT width = image.GetWidth();
   UINT height = image.GetHeight();

   // Draw the image unaltered.
   graphics.DrawImage(&image, 10, 10, width, height);

   imAtt.SetOutputChannelColorProfile(
      L"TEKPH600.ICM", ColorAdjustTypeBitmap);

   // Draw the image, showing the intensity of the cyan channel.
   imAtt.SetOutputChannel(ColorChannelFlagsC, ColorAdjustTypeBitmap);
   graphics.DrawImage(
      &image,
      Rect(110, 10, width, height),  // dest rect
      0, 0, width, height,           // source rect
      UnitPixel,
      &imAtt);

   // Draw the image, showing the intensity of the magenta channel.
   imAtt.SetOutputChannel(ColorChannelFlagsM, ColorAdjustTypeBitmap);
   graphics.DrawImage(
      &image,
      Rect(210, 10, width, height),  // dest rect
      0, 0, width, height,           // source rect
      UnitPixel,
      &imAtt);

   // Draw the image, showing the intensity of the yellow channel.
   imAtt.SetOutputChannel(ColorChannelFlagsY, ColorAdjustTypeBitmap);
   graphics.DrawImage(
      &image,
      Rect(10, 110, width, height),  // dest rect
      0, 0, width, height,           // source rect
      UnitPixel,
      &imAtt);

   // Draw the image, showing the intensity of the black channel.
   imAtt.SetOutputChannel(ColorChannelFlagsK, ColorAdjustTypeBitmap);
   graphics.DrawImage(
      &image,
      Rect(110, 110, width, height),  // dest rect
      0, 0, width, height,            // source rect
      UnitPixel,
      &imAtt);
}

The preceding code, along with the files Mosaic2.bmp and Tekph600.icm, produced the following output.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
ClearOutputChannel, ClearOutputChannelColorProfile, ColorAdjustType, ColorChannelFlags, SetOutputChannel


ImageAttributes::SetRemapTable(mapSize, map, type)

The SetRemapTable method sets the color-remap table for a specified category.

Status SetRemapTable(
  UINT mapSize,
  const ColorMap* map,
  ColorAdjustType type
);

Parameters

mapSize
[in] Integer that specifies the number of elements in the map array.
map
[in] Pointer to an array of ColorMap structures that defines the color map.
type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the color-remap table is set. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A color-remap table is an array of ColorMap structures. Each ColorMap structure has two Color objects: one that specifies an old color and one that specifies a corresponding new color. During rendering, any color that matches one of the old colors in the remap table is changed to the corresponding new color.

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify a color remap for the default category, a color-remap table for the bitmap category, and still a different color-remap table for the pen category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the pen category, then the default settings apply to the pen category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a collection of adjustment settings for the default category. If you set the color-remap table for the pen category by passing ColorAdjustTypePen to the SetRemapTable method, then none of the default adjustment settings will apply to pens.

Example Code [C++]

The following example creates an Image object based on a BMP file and then draws the image. The code creates an ImageAttributes object and sets its default remap table so that red is converted to blue. Then the code draws the image again using the color adjustment specified by the remap table.

VOID Example_SetRemapTable(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object based on a BMP file.
   // The image has one red stripe and one green stripe.
   Image image(L"RedGreenStripes.bmp");

   // Create an ImageAttributes object and set its remap table.
   ImageAttributes imageAtt;
   ColorMap cMap;
   cMap.oldColor = Color(255, 255, 0, 0);  // red
   cMap.newColor = Color(255, 0, 0, 255);  // blue
   imageAtt.SetRemapTable(12, &cMap,
      ColorAdjustTypeDefault);

   // Draw the image with no color adjustment.
   graphics.DrawImage(&image, 10, 10, image.GetWidth(), image.GetHeight());

   // Draw the image with red converted to blue.
   graphics.DrawImage(&image,
      Rect(100, 10, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),           // source rect
      UnitPixel,
      &imageAtt);
}

The following illustration shows the output of the preceding code.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ClearRemapTable, Color, ColorAdjustType, ColorMap, Image, Metafile
Tasks and Examples
Recoloring


ImageAttributes::SetThreshold(threshold, type)

The SetThreshold method sets the threshold (transparency range) for a specified category.

Status SetThreshold(
  REAL threshold,
  ColorAdjustType type
);

Parameters

threshold
[in] Real number that specifies the threshold value.
type
[in] Optional. Element of the ColorAdjustType enumeration that specifies the category for which the color threshold is set. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The threshold is a value from 0 through 1 that specifies a cutoff point for each color component. For example, suppose the threshold is set to 0.7, and suppose you are rendering a color whose red, green, and blue components are 230, 50, and 220. The red component, 230, is greater than 0.7×255, so the red component will be changed to 255 (full intensity). The green component, 50, is less than 0.7×255, so the green component will be changed to 0. The blue component, 220, is greater than 0.7×255, so the blue component will be changed to 255.

An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. For example, you can specify a threshold for the default category, a threshold for the bitmap category, and still a different threshold for the pen category.

The default color- and grayscale-adjustment settings apply to all categories that don't have adjustment settings of their own. For example, if you never specify any adjustment settings for the pen category, then the default settings apply to the pen category.

As soon as you specify a color- or grayscale-adjustment setting for a certain category, the default adjustment settings no longer apply to that category. For example, suppose you specify a collection of adjustment settings for the default category. If you set the threshold for the pen category by passing ColorAdjustTypePen to the SetThreshold method, then none of the default adjustment settings will apply to pens.

Example Code [C++]

The following example creates an Image object based on a BMP file The code also creates an ImageAttributes object and sets its bitmap threshold value to 0.6. Then the code draws the image twice: once with no color adjustment and once with the adjustment specified by the threshold.

VOID Example_SetThreshold(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an Image object based on a BMP file.
   // The image has one stripe with RGB components (160, 0, 0)
   // and one stripe with RGB components (0, 140, 0).
   Image image(L"RedGreenThreshold.bmp");

   // Create an ImageAttributes object, and set its bitmap threshold to 0.6.
   ImageAttributes imAtt;
   imAtt.SetThreshold(0.6f, ColorAdjustTypeBitmap);

   // Draw the image with no color adjustment.
   graphics.DrawImage(&image, 10, 10, image.GetWidth(), image.GetHeight());

   // Draw the image with the threshold applied.
   // 160 > 0.6*255, so the red stripe will be changed to full intensity.
   // 140 < 0.6*255, so the green stripe will be changed to zero intensity.
   graphics.DrawImage(&image,
      Rect(100, 10, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, image.GetWidth(), image.GetHeight(),           // source rect
      UnitPixel,
      &imAtt);
}

The following illustration shows the output of the preceding code. Note that the red was converted to maximum intensity, and the green was converted to zero intensity.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ClearColorKey, ClearThreshold, Color, ColorAdjustType, Image, Metafile, SetColorKey
Tasks and Examples
Recoloring


ImageAttributes::SetToIdentity(type)

The SetToIdentity method sets the color-adjustment matrix of a specified category to identity matrix.

Status SetToIdentity(
  ColorAdjustType type
);

Parameters

type
[in] Element of the ColorAdjustType enumeration that specifies the category for which the color-adjustment matrix is set to identity. The default value is ColorAdjustTypeDefault.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, ColorAdjustType, ColorMatrix, Image, Metafile
Tasks and Examples
Recoloring


ImageAttributes::SetWrapMode(wrap, color, clamp)

The SetWrapMode method sets the wrap mode of this ImageAttributes object.

Status SetWrapMode(
  WrapMode wrap,
  const Color& color,
  BOOL clamp
);

Parameters

wrap
[in] Element of the WrapMode enumeration that specifies how repeated copies of an image are used to tile an area.
color
[in] Optional. Reference to a Color object that specifies the color of pixels outside of a rendered image. This color is visible if the wrap parameter is set to WrapModeClamp and the source rectangle passed to Graphics::DrawImage is larger than the image itself. The default value is Color(), which is a Color object initialized to black.
clamp
[in] Optional. This parameter has no effect in GDI+ version 1.0. Set this parameter to FALSE. The default value is FALSE.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example calls Graphics::DrawImage twice. In both calls, the specified source rectangle is four times as large as the image itself. In the first call to DrawImage, the ImageAttributes object has its wrap mode set to WrapModeClamp, so the portion of the source rectangle outside the image is filled with red according to the second argument passed to SetWrapMode. In the second call to DrawImage, the ImageAttributes object has its wrap mode set to WrapModeTile, so the portion of the source rectangle outside the image is filled with repeated copies of the image.

VOID Example_SetWrapMode(HDC hdc)
{
   Graphics graphics(hdc);
   Image image(L"Climber.jpg");
   ImageAttributes imAtt;

   imAtt.SetWrapMode(WrapModeClamp);
   graphics.DrawImage(&image,
      Rect(10, 10, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, 2*image.GetWidth(), 2*image.GetHeight(),      // source rect
      UnitPixel,
      &imAtt);

   imAtt.SetWrapMode(WrapModeTile);
   graphics.DrawImage(&image,
      Rect(200, 10, image.GetWidth(), image.GetHeight()),  // dest rect
      0, 0, 2*image.GetWidth(), 2*image.GetHeight(),       // source rect
      UnitPixel,
      &imAtt);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimageattributes.h; include Gdiplus.h.

See Also

Reference
Bitmap, Color, Image, Metafile, WrapMode
Tasks and Examples
Recoloring


ImageCodecInfo Class

An ImageCodecInfo object stores information about an image codec (encoder/decoder). GDI+ provides several built-in image codecs. You can obtain information about those codecs by calling the GetImageEncoders function and the GetImageDecoders function. Each of those functions returns an array of ImageCodecInfo objects, one for each available encoder or decoder.

Data Members

The following table lists the data members of the ImageCodecInfo class in the order that they are defined in the header file.

Data member | Description
Clsid | CLSID. Codec identifier.
FormatID | GUID. File format identifier. GUIDs that identify various file formats (ImageFormatBMP, ImageFormatEMF, and the like) are defined in Gdiplusimaging.h.
CodecName | WCHAR*. Pointer to a null-terminated string that contains the codec name.
DllName | WCHAR*. Pointer to a null-terminated string that contains the path name of the DLL in which the codec resides. If the codec is not in a DLL, this pointer is NULL.
FormatDescription | WCHAR*. Pointer to a null-terminated string that contains the name of the file format used by the codec.
FilenameExtension | WCHAR*. Pointer to a null-terminated string that contains all file-name extensions associated with the codec. The extensions are separated by semicolons.
MimeType | WCHAR*. Pointer to a null-terminated string that contains the mime type of the codec.
Flags | DWORD. Combination of flags from the ImageCodecFlags enumeration.
Version | DWORD. Integer that indicates the version of the codec.
SigCount | DWORD. Integer that indicates the number of signatures used by the file format associated with the codec.
SigSize | DWORD. Integer that indicates the number of bytes in each signature.
SigPattern | BYTE*. Pointer to an array of bytes that contains the pattern for each signature.
SigMask | BYTE*. Pointer to an array of bytes that contains the mask for each signature.

Example Code [C/C++]

The following console application calls the GetImageEncoders function to obtain an array of ImageCodecInfo objects, one for each available image encoder. Then the code prints all the data members of each ImageCodecInfo object in the array.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR           gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   // GetImageEncoders returns an array of ImageCodecInfo objects.
   // Determine the size of that array.
   UINT num;
   UINT size;
   GetImageEncodersSize(&num, &size);

   // Allocate a buffer large enough to hold the array
   // returned by GetImageEncoders.
   ImageCodecInfo* encoderInfo = (ImageCodecInfo*)malloc(size);
   GetImageEncoders(num, size, encoderInfo);

   WCHAR clsid[39];
   WCHAR formatID[39];
   DWORD sigCount;
   DWORD sigSize;
   UINT j, k;

   for(j = 0; j < num; ++j)
   {
      StringFromGUID2(encoderInfo[j].Clsid, clsid, 39);
      StringFromGUID2(encoderInfo[j].FormatID, formatID, 39);
      wprintf(L"Codec identifier: %s\n", clsid);
      wprintf(L"Format identifier: %s\n", formatID);

      wprintf(L"Codec name: %s\n", encoderInfo[j].CodecName);
      wprintf(L"DLL name: %s\n", encoderInfo[j].DllName);
      wprintf(L"Format description: %s\n", encoderInfo[j].FormatDescription);
      wprintf(L"Filename extension: %s\n", encoderInfo[j].FilenameExtension);
      wprintf(L"Mime type: %s\n", encoderInfo[j].MimeType);
      printf("Flags: %x\n", encoderInfo[j].Flags);
      printf("Version: %u\n", encoderInfo[j].Version);

      sigCount = encoderInfo[j].SigCount;
      sigSize = encoderInfo[j].SigSize;
      printf("Signature count: %u\n", sigCount);
      printf("Signature size: %u\n", sigSize);

      // Print each byte of each signature pattern.
      printf("Signature pattern: ");
      for(k = 0; k < sigCount * sigSize; ++k)
      {
         printf("%x ", encoderInfo[j].SigPattern[k]);
      }

      printf("\n");

      // Print each byte of each signature mask.
      printf("Signature mask: ");
      for(k = 0; k < sigCount * sigSize; ++k)
      {
         printf("%x ", encoderInfo[j].SigMask[k]);
      }

      printf("\n\n");
   }

   free(encoderInfo);
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The following program output is a portion of the output of the preceding code:

Codec identifier: {557CF400-1A04-11D3-9A73-0000F81EF32E}
Format identifier: {B96B3CAB-0728-11D3-9D7B-0000F81EF32E}
Codec name: Built-in BMP Codec
DLL name: (null)
Format description: Windows Bitmap
Filename extension: *.BMP;*.DIB;*.RLE
Mime type: image/bmp
Flags: 10007
Version: 1
Signature count: 1
Signature size: 2
Signature pattern: 42 4d
Signature mask: ff ff

Codec identifier: {557CF401-1A04-11D3-9A73-0000F81EF32E}
Format identifier: {B96B3CAE-0728-11D3-9D7B-0000F81EF32E}
Codec name: Built-in JPEG Codec
DLL name: (null)
Format description: JPEG
Filename extension: *.JPG;*.JPEG;*.JPE;*.JFIF
Mime type: image/jpeg
Flags: 10007
Version: 1
Signature count: 1
Signature size: 2
Signature pattern: ff d8
Signature mask: ff ff

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimaging.h; include Gdiplus.h.

See Also

Reference
EncoderParameter, EncoderParameters, GetEncoderParameterList, GetEncoderParameterListSize
Tasks and Examples
Listing Installed Encoders, Using Image Encoders and Decoders


InstalledFontCollection Class

The InstalledFontCollection class defines a class that represents the fonts installed on the system.

Inheritance

GdiplusBase
FontCollection
InstalledFontCollection

Constructors

Constructor | Description
InstalledFontCollection | Creates an InstalledFontCollection object.

Methods

Uninherited

Method | Description
~InstalledFontCollection | InstalledFontCollection object destructor.

Inherited from FontCollection

Method | Description
GetFamilies | Gets the font families contained in this font collection.
GetFamilyCount | Gets the number of font families contained in this font collection.
GetLastStatus | Returns a value that indicates the result of this FontCollection object's previous method call.

Remarks

GDI+ clients should not use the InstalledFontCollection class to install a font to Windows. Instead, use the GDI AddFontResource function. An InstalledFontCollection object can find only those fonts that were installed in Windows before the object was created.

See Also

Reference
FontCollection
Tasks and Examples
Using Text and Fonts


InstalledFontCollection::InstalledFontCollection()

Creates an InstalledFontCollection object.

InstalledFontCollection(void);

Parameters

This method has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
FontCollection
Tasks and Examples
Using Text and Fonts


InstalledFontCollection Methods

This topic lists the methods of the InstalledFontCollection class. For a complete class listing, see InstalledFontCollection Class.

  • GetFamilies(numSought, gpfamilies, numFound)
  • GetFamilyCount()
  • GetLastStatus()


LinearGradientBrush Class

The LinearGradientBrush class defines a brush that paints a color gradient in which the color changes evenly from the starting boundary line of the linear gradient brush to the ending boundary line of the linear gradient brush. The boundary lines of a linear gradient brush are two parallel straight lines. The color gradient is perpendicular to the boundary lines of the linear gradient brush, changing gradually across the stroke from the starting boundary line to the ending boundary line. The color gradient has one color at the starting boundary line and another color at the ending boundary line.

Inheritance

GdiplusBase
Brush
LinearGradientBrush

Constructors

Constructor | Description
LinearGradientBrush | Overloaded. Creates and initializes a new instance of the LinearGradientBrush class.

Methods

Uninherited

Method | Description
GetBlend | Gets the blend factors and their corresponding blend positions.
GetBlendCount | Gets the number of blend factors currently set.
GetGammaCorrection | Determines whether gamma correction is enabled.
GetInterpolationColorCount | Gets the number of colors that are interpolated for this linear gradient brush.
GetInterpolationColors | Gets the colors that are interpolated for this linear gradient brush and their corresponding blend positions.
GetLinearColors | Gets the starting color and ending color of this linear gradient brush.
GetRectangle | Overloaded. Gets the rectangle that defines the boundaries of the gradient.
GetTransform | Gets the transformation matrix.
GetWrapMode | Gets the wrap mode.
MultiplyTransform | Updates this brush's transformation matrix with the product of itself and another matrix.
ResetTransform | Resets the transformation matrix to the identity matrix.
RotateTransform | Updates this brush's current transformation matrix with the product of itself and a rotation matrix.
ScaleTransform | Updates this brush's current transformation matrix with the product of itself and a scaling matrix.
SetBlend | Sets the blend factors and the blend positions of this linear gradient brush to create a custom blend.
SetBlendBellShape | Sets the blend shape of this linear gradient brush to create a custom blend based on a bell-shaped curve.
SetBlendTriangularShape | Sets the blend shape of this linear gradient brush to create a custom blend based on a triangular shape.
SetGammaCorrection | Enables or disables gamma correction.
SetInterpolationColors | Sets the colors to be interpolated for this linear gradient brush and their corresponding blend positions.
SetLinearColors | Sets the starting and ending colors of the gradient.
SetTransform | Sets the transformation matrix of this linear gradient brush.
SetWrapMode | Sets the wrap mode of this linear gradient brush.
TranslateTransform | Updates this brush's current transformation matrix with the product of itself and a translation matrix.

Inherited from Brush

Method | Description
Clone | Creates a new Brush object based on this brush.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetType | Gets the type of this brush.


LinearGradientBrush Constructors

This topic lists the constructors of the LinearGradientBrush class. For a complete class listing, see LinearGradientBrush Class.

  • LinearGradientBrush(Point& point1, Point& point2, Color& color1, Color& color2)
  • LinearGradientBrush(PointF& point1, PointF& point2, Color& color1, Color& color2)
  • LinearGradientBrush(Rect& rect, Color& color1, Color& color2, REAL angle, BOOL isAngleScalable)
  • LinearGradientBrush(RectF& rect, Color& color1, Color& color2, REAL angle, BOOL isAngleScalable)
  • LinearGradientBrush(Rect& rect, Color& color1, Color& color2, LinearGradientMode mode)
  • LinearGradientBrush(RectF& rect, Color& color1, Color& color2, LinearGradientMode mode)


LinearGradientBrush::LinearGradientBrush(Point& point1, Point& point2, Color& color1, Color& color2)

Creates a LinearGradientBrush object from a set of boundary points and boundary colors.

LinearGradientBrush(
  const Point& point1,
  const Point& point2,
  const Color& color1,
  const Color& color2
);

Parameters

point1
[in] Reference to a Point object that specifies the starting point of the gradient. The starting boundary line passes through the starting point.
point2
[in] Reference to a Point object that specifies the ending point of the gradient. The ending boundary line passes through the ending point.
color1
[in] Reference to a Color object that specifies the color at the starting boundary line of this linear gradient brush.
color2
[in] Reference to a Color object that specifies the color at the ending boundary line of this linear gradient brush.

Remarks

An imaginary straight line, we'll call the directional line, is defined by the starting point, point1, and the ending point, point2. The starting boundary of the gradient is a straight line that is perpendicular to the directional line and that passes through the starting point. The ending boundary of the gradient is a straight line that is parallel to the starting boundary line and that passes through the ending point. The gradient color is constant along lines that are parallel to the boundary lines. The gradient gradually changes from the starting color to the ending color along the directional line.

Example Code [C++]

The following example creates a linear gradient brush from a set of boundary points and boundary colors. The code then uses the brush to paint the interior of a rectangle.

VOID Example_Construct01(HDC hdc)
{
   Graphics myGraphics(hdc);

   LinearGradientBrush linGrBrush(
      Point(50, 50),
      Point(200, 100),
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255));  // blue

   myGraphics.FillRectangle(&linGrBrush, 0, 0, 300, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, Rect


LinearGradientBrush::LinearGradientBrush(PointF& point1, PointF& point2, Color& color1, Color& color2)

Creates a LinearGradientBrush object from a set of boundary points and boundary colors.

LinearGradientBrush(
  const PointF& point1,
  const PointF& point2,
  const Color& color1,
  const Color& color2
);

Parameters

point1
[in] Reference to a Point object that specifies the starting point of the gradient. The starting boundary line passes through the starting point.
point2
[in] Reference to a Point object that specifies the ending point of the gradient. The ending boundary line passes through the ending point.
color1
[in] Reference to a Color object that specifies the color at the starting boundary line of this linear gradient brush.
color2
[in] Reference to a Color object that specifies the color at the ending boundary line of this linear gradient brush.

Remarks

An imaginary straight line, we'll call the directional line, is defined by the starting point, point1, and the ending point, point2. The starting boundary of the gradient is a straight line that is perpendicular to the directional line and that passes through the starting point. The ending boundary of the gradient is a straight line that is parallel to the starting boundary line and that passes through the ending point. The gradient color is constant along lines that are parallel to the boundary lines. The gradient gradually changes from the starting color to the ending color along the directional line.

Example Code [C++]

The following example creates a linear gradient brush from a set of boundary points and boundary colors. The code then uses the brush to paint the interior of a rectangle.

VOID Example_Construct02(HDC hdc)
{
   Graphics myGraphics(hdc);

   LinearGradientBrush linGrBrush(
      PointF(0.8f, 1.6f),
      PointF(3.0f, 2.4f),
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255));  // blue

   myGraphics.SetPageUnit(UnitInch);
   myGraphics.FillRectangle(&linGrBrush, 0, 0, 4, 3);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, Rect


LinearGradientBrush::LinearGradientBrush(Rect& rect, Color& color1, Color& color2, REAL angle, BOOL isAngleScalable)

Creates a LinearGradientBrush object from a rectangle and angle of direction.

LinearGradientBrush(
  const Rect& rect,
  const Color& color1,
  const Color& color2,
  REAL angle,
  BOOL isAngleScalable
);

Parameters

rect
[in] Reference to a rectangle that specifies the starting and ending points of the gradient. The upper-left corner of the rectangle is the starting point. The lower-right corner is the ending point.
color1
[in] Reference to a Color object that specifies the color at the starting boundary line of this linear gradient brush.
color2
[in] Reference to a Color object that specifies the color at the ending boundary line of this linear gradient brush.
angle
[in] Real number that, if isAngleScalable is TRUE, specifies the base angle from which the angle of the directional line is calculated, or that, if isAngleScalable is FALSE, specifies the angle of the directional line. The angle is measured from the top of the rectangle that is specified by rect and must be in degrees. The gradient follows the directional line.
isAngleScalable
[in] Boolean value that specifies whether the angle is scalable. If isAngleScalable is TRUE, the angle of the directional line is scalable; otherwise, the angle is not scalable.

Remarks

An imaginary straight line, we'll call the directional line, is defined by the starting point (upper-left corner of the rectangle rect) and the angle angle. The starting boundary of the gradient is a straight line that is perpendicular to the directional line and that passes through the starting point. The ending boundary of the gradient is a straight line that is parallel to the starting boundary line and that passes through the ending point (lower-right corner of the rectangle rect). The gradient color is constant along lines that are parallel to the boundary lines. The gradient gradually changes from the starting color to the ending color along the directional line.

If isAngleScalable is TRUE, the base angle is scaled to produce the angle of the directional line:

β = arctan( (width / height) tan(θ) )

where β is the new angle of the directional line; width and height are the dimensions of the rectangle rect; and θ is the base angle angle. This relationship is valid only if angle is less than 90 degrees.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.


LinearGradientBrush::LinearGradientBrush(RectF& rect, Color& color1, Color& color2, REAL angle, BOOL isAngleScalable)

Creates a LinearGradientBrush object from a rectangle and angle of direction.

LinearGradientBrush(
  const RectF& rect,
  const Color& color1,
  const Color& color2,
  REAL angle,
  BOOL isAngleScalable
);

Parameters

rect
[in] Reference to a rectangle that specifies the starting and ending points of the gradient. The upper-left corner of the rectangle is the starting point. The lower-right corner is the ending point.
color1
[in] Reference to a Color object that specifies the color at the starting boundary line of this linear gradient brush.
color2
[in] Reference to a Color object that specifies the color at the ending boundary line of this linear gradient brush.
angle
[in] Real number that, if isAngleScalable is TRUE, specifies the base angle from which the angle of the directional line is calculated, or that, if isAngleScalable is FALSE, specifies the angle of the directional line. The angle is measured from the top of the rectangle that is specified by rect and must be in degrees. The gradient follows the directional line.
isAngleScalable
[in] Boolean value that specifies whether the angle is scalable. If isAngleScalable is TRUE, the angle of the directional line is scalable; otherwise, the angle is not scalable.

Remarks

An imaginary straight line, we'll call the directional line, is defined by the starting point (upper-left corner of the rectangle rect) and the angle angle. The starting boundary of the gradient is a straight line that is perpendicular to the directional line and that passes through the starting point. The ending boundary of the gradient is a straight line that is parallel to the starting boundary line and that passes through the ending point (lower-right corner of the rectangle rect). The gradient color is constant along lines that are parallel to the boundary lines. The gradient gradually changes from the starting color to the ending color along the directional line.

If isAngleScalable is TRUE, the base angle is scaled to produce the angle of the directional line:

β = arctan( (width / height) tan(θ) )

where β is the new angle of the directional line; width and height are the dimensions of the rectangle rect; and θ is the base angle angle. This relationship is valid only if angle is less than 90 degrees.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.


LinearGradientBrush::LinearGradientBrush(Rect& rect, Color& color1, Color& color2, LinearGradientMode mode)

Creates a LinearGradientBrush object based on a rectangle and mode of direction.

LinearGradientBrush(
  const Rect& rect,
  const Color& color1,
  const Color& color2,
  LinearGradientMode mode
);

Parameters

rect
[in] Reference to a rectangle that specifies the starting and ending points of the gradient. The direction of the gradient, specified by mode, affects how these points are defined. The dimensions of the rectangle affect the direction of the gradient for forward diagonal mode and backward diagonal mode.
color1
[in] Reference to a Color object that specifies the color at the starting boundary line of this linear gradient brush.
color2
[in] Reference to a Color object that specifies the color at the ending boundary line of this linear gradient brush.
mode
[in] Element of the LinearGradientMode enumeration that specifies the direction of the gradient.

Remarks

The starting boundary of the gradient is a straight line that either passes through the starting point or borders the rectangle rect. The ending boundary of the gradient is a straight line that is parallel to the starting boundary line and that either passes through the ending point or borders the rectangle. An imaginary straight line, we'll call the directional line, is perpendicular to the boundary lines. The gradient color is constant along lines that are parallel to the boundary lines. The gradient gradually changes from the starting color to the ending color along the directional line.

The mode affects the boundaries of the gradient:

  • Vertical mode

    The boundary lines are parallel to the top (and bottom) of the rectangle rect. The starting and ending boundary lines are the top and bottom, respectively, of the rectangle rect.

  • Horizontal mode

    The boundary lines are parallel to the left (and right) of the rectangle rect. The starting and ending boundary lines are the left and right, respectively, of the rectangle rect.

  • Forward diagonal mode

    The boundary lines are parallel to the diagonal line that is defined by the upper-right corner and lower-left corner of the rectangle rect. The starting boundary line passes through the starting point (upper-left corner of the rectangle rect). The ending boundary line passes through the ending point (lower-right corner of the rectangle rect). Note that starting and ending points are opposites of the starting and ending points for backward diagonal mode.

  • Backward diagonal mode

    The boundary lines are parallel to the diagonal line that is defined by the upper-left corner and lower-right corner of the rectangle rect. The starting boundary line passes through the starting point (upper-right corner of the rectangle rect). The ending boundary line passes through the ending point (lower-left corner of the rectangle rect). Note that starting and ending points are opposites of the starting and ending points for forward diagonal mode.

Example Code [C++]

The following example creates a linear gradient brush using LinearGradientModeVertical for the mode setting.

VOID Example_Construct04(HDC hdc)
{
   Graphics myGraphics(hdc);

   LinearGradientBrush linGrBrush(
      Rect(20, 10, 200, 100),
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255),   // blue
      LinearGradientModeVertical);
   myGraphics.FillRectangle(&linGrBrush, 0, 0, 300, 300);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, LinearGradientMode, Rect
Tasks and Examples
Creating a Linear Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


LinearGradientBrush::LinearGradientBrush(RectF& rect, Color& color1, Color& color2, LinearGradientMode mode)

Creates a LinearGradientBrush object based on a rectangle and mode of direction.

LinearGradientBrush(
  const RectF& rect,
  const Color& color1,
  const Color& color2,
  LinearGradientMode mode
);

Parameters

rect
[in] Reference to a rectangle that specifies the starting and ending points of the gradient. The direction of the gradient, specified by mode, affects how these points are defined. The dimensions of the rectangle affect the direction of the gradient for forward diagonal mode and backward diagonal mode.
color1
[in] Reference to a Color object that specifies the color at the starting boundary line of this linear gradient brush.
color2
[in] Reference to a Color object that specifies the color at the ending boundary line of this linear gradient brush.
mode
[in] Element of the LinearGradientMode enumeration that specifies the direction of the gradient.

Remarks

The starting boundary of the gradient is a straight line that either passes through the starting point or borders the rectangle rect. The ending boundary of the gradient is a straight line that is parallel to the starting boundary line and that either passes through the ending point or borders the rectangle. An imaginary straight line, we'll call the directional line, is perpendicular to the boundary lines. The gradient color is constant along lines that are parallel to the boundary lines. The gradient gradually changes from the starting color to the ending color along the directional line.

The mode affects the boundaries of the gradient:

  • Vertical mode

    The boundary lines are parallel to the top (and bottom) of the rectangle rect. The starting and ending boundary lines are the top and bottom, respectively, of the rectangle rect.

  • Horizontal mode

    The boundary lines are parallel to the left (and right) of the rectangle rect. The starting and ending boundary lines are the left and right, respectively, of the rectangle rect.

  • Forward diagonal mode

    The boundary lines are parallel to the diagonal line that is defined by the upper-right corner and lower-left corner of the rectangle rect. The starting boundary line passes through the starting point (upper-left corner of the rectangle rect). The ending boundary line passes through the ending point (lower-right corner of the rectangle rect). Note that starting and ending points are opposites of the starting and ending points for backward diagonal mode.

  • Backward diagonal mode

    The boundary lines are parallel to the diagonal line that is defined by the upper-left corner and lower-right corner of the rectangle rect. The starting boundary line passes through the starting point (upper-right corner of the rectangle rect). The ending boundary line passes through the ending point (lower-left corner of the rectangle rect). Note that starting and ending points are opposites of the starting and ending points for forward diagonal mode.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, LinearGradientMode, RectF
Tasks and Examples
Creating a Linear Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


LinearGradientBrush Methods

This topic lists the methods of the LinearGradientBrush class. For a complete class listing, see LinearGradientBrush Class.

  • Clone()
  • GetBlend(blendFactors, blendPositions, count)
  • GetBlendCount()
  • GetGammaCorrection()
  • GetInterpolationColorCount()
  • GetInterpolationColors(presetColors, blendPositions, count)
  • GetLastStatus()
  • GetLinearColors(colors)
  • GetRectangle(Rect* rect)
  • GetRectangle(RectF* rect)
  • GetTransform(matrix)
  • GetType()
  • GetWrapMode()
  • MultiplyTransform(matrix, order)
  • ResetTransform()
  • RotateTransform(angle, order)
  • ScaleTransform(sx, sy, order)
  • SetBlend(blendFactors, blendPositions, count)
  • SetBlendBellShape(focus, scale)
  • SetBlendTriangularShape(focus, scale)
  • SetGammaCorrection(useGammaCorrection)
  • SetInterpolationColors(presetColors, blendPositions, count)
  • SetLinearColors(color1, color2)
  • SetTransform(matrix)
  • SetWrapMode(wrapMode)
  • TranslateTransform(dx, dy, order)


LinearGradientBrush::GetBlend(blendFactors, blendPositions, count)

The GetBlend method gets the blend factors and their corresponding blend positions from a LinearGradientBrush object.

Status GetBlend(
  REAL* blendFactors,
  REAL* blendPositions,
  INT count
) const;

Parameters

blendFactors
[out] Pointer to an array that receives the blend factors. Each number in the array indicates a percentage of the ending color and is in the range from 0.0 through 1.0.
blendPositions
[out] Pointer to an array that receives the blend positions. Each number in the array indicates a percentage of the distance between the starting boundary and the ending boundary and is in the range from 0.0 through 1.0, where 0.0 indicates the starting boundary of the gradient and 1.0 indicates the ending boundary. A blend position between 0.0 and 1.0 indicates a line, parallel to the boundary lines, that is a certain fraction of the distance from the starting boundary to the ending boundary. For example, a blend position of 0.7 indicates the line that is 70 percent of the distance from the starting boundary to the ending boundary. The color is constant on lines that are parallel to the boundary lines.
count
[in] Integer that specifies the number of blend factors to retrieve. Before calling the GetBlend method of a LinearGradientBrush object, call the GetBlendCount method of that same LinearGradientBrush object to determine the current number of blend factors. The number of blend positions retrieved is the same as the number of blend factors retrieved.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A LinearGradientBrush object has two parallel boundaries: a starting boundary and an ending boundary. A color is associated with each of these two boundaries. Each boundary is a straight line that passes through a specified point — the starting boundary passes through the starting point; the ending boundary passes through the ending point — and is perpendicular to the direction of the linear gradient brush. The direction of the linear gradient brush follows the line that is defined by the starting and ending points. This line, which we will call the directional line, may be horizontal, vertical, or diagonal. All points that lie on a line that is parallel to the boundaries are the same color. When you fill an area with a linear gradient brush, the color changes gradually from one line to the next as you move along the directional line from the starting boundary to the ending boundary. By default, the change in color is proportional to the change in distance; that is, a line 30 percent of the distance between the starting boundary and the ending boundary has a color that is 30 percent of the distance between the starting boundary color and the ending boundary color. The color pattern is repeated outside of the starting and ending boundaries.

You can call the SetBlend method of a LinearGradientBrush object to customize the relationship between color and distance. For example, suppose you set the blend positions to {0, 0.5, 1} and you set the blend factors to {0, 0.3, 1}. Then a line 50 percent of the distance between the starting boundary and the ending boundary will have a color that is 30 percent of the distance between the starting boundary color and the ending boundary color.

Example Code [C++]

The following example creates a linear gradient brush, sets its blend, and uses the brush to fill a rectangle. The code then gets the blend. The blend factors and positions can then be inspected or used in some way.

VOID Example_GetBlend(HDC hdc)
{
   Graphics myGraphics(hdc);

   // Create a linear gradient brush, and set its blend.
   REAL fac[] = {0.0f, 0.4f, 0.6f, 1.0f};
   REAL pos[] = {0.0f, 0.2f, 0.8f, 1.0f};

   LinearGradientBrush linGrBrush(
      Point(0, 0),
      Point(100, 0),
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255));  // blue

   linGrBrush.SetBlend(fac, pos, 4);

   // Use the linear gradient brush to fill a rectangle.
   myGraphics.FillRectangle(&linGrBrush, 0, 0, 100, 50);

   // Obtain information about the linear gradient brush.
   INT   blendCount;
   REAL* factors = NULL;
   REAL* positions = NULL;

   blendCount = linGrBrush.GetBlendCount();
   factors = new REAL[blendCount];
   positions = new REAL[blendCount];

   linGrBrush.GetBlend(factors, positions, blendCount);

   for(INT j = 0; j < blendCount; ++j)
   {
      // Inspect or use the value in factors[j].
      // Inspect or use the value in positions[j].
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetBlendCount, Point, SetBlend
Tasks and Examples
Filling a Shape with a Color Gradient, Filling Shapes with a Gradient Brush
Concepts
Brushes and Filled Shapes


LinearGradientBrush::GetBlendCount()

The GetBlendCount method gets the number of blend factors currently set for this LinearGradientBrush object.

INT GetBlendCount(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the number of blend factors currently set for this LinearGradientBrush object. If no custom blend has been set by using SetBlend, or if invalid positions were passed to SetBlend, then GetBlend returns 1.

Example Code [C++]

The following example creates a linear gradient brush, sets its blend, and uses the brush to fill a rectangle. Next, the code gets the blend count and the blend. The blend factors and positions can then be inspected or used in some way.

VOID Example_GetBlend(HDC hdc)
{
   Graphics myGraphics(hdc);

   // Create a linear gradient brush, and set its blend.
   REAL fac[] = {0.0f, 0.4f, 0.6f, 1.0f};
   REAL pos[] = {0.0f, 0.2f, 0.8f, 1.0f};

   LinearGradientBrush linGrBrush(
      Point(0, 0),
      Point(100, 0),
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255));  // blue

   linGrBrush.SetBlend(fac, pos, 4);

   // Use the linear gradient brush to fill a rectangle.
   myGraphics.FillRectangle(&linGrBrush, 0, 0, 100, 50);

   // Obtain information about the linear gradient brush.
   INT   blendCount;
   REAL* factors = NULL;
   REAL* positions = NULL;

   blendCount = linGrBrush.GetBlendCount();
   factors = (REAL*)malloc(blendCount*sizeof(REAL));
   positions = (REAL*)malloc(blendCount*sizeof(REAL));

   linGrBrush.GetBlend(factors, positions, blendCount);

   for(INT j = 0; j < blendCount; ++j)
   {
      // Inspect or use the value in factors[j].
      // Inspect or use the value in positions[j].
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetBlend, Point, SetBlend
Tasks and Examples
Filling a Shape with a Color Gradient, Filling Shapes with a Gradient Brush
Concepts
Brushes and Filled Shapes


LinearGradientBrush::GetGammaCorrection()

The GetGammaCorrection method determines whether gamma correction is enabled for this LinearGradientBrush object.

BOOL GetGammaCorrection(void) const;

Parameters

This method has no parameters.

Return Values

If gamma correction is enabled, this method returns TRUE; otherwise, it returns FALSE.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color


LinearGradientBrush::GetInterpolationColorCount()

The GetInterpolationColorCount method gets the number of colors currently set to be interpolated for this linear gradient brush.

INT GetInterpolationColorCount(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the number of colors to be interpolated for this linear gradient brush. If no colors have been set by using SetInterpolationColors, or if invalid positions were passed to SetInterpolationColors, then GetInterpolationColorCount returns 0.

Remarks

A simple linear gradient brush has two colors: a color at the starting boundary and a color at the ending boundary. When you paint with such a brush, the color changes gradually from the starting color to the ending color as you move from the starting boundary to the ending boundary. You can create a more complex gradient by using the SetInterpolationColors method to specify an array of colors and their corresponding blend positions to be interpolated for this linear gradient brush.

You can obtain the colors and blend positions currently set for a linear gradient brush by calling its GetInterpolationColors method. Before you call the GetInterpolationColors method, you must allocate two buffers: one to hold the array of colors and one to hold the array of blend positions. You can call the GetInterpolationColorCount method to determine the required size of those buffers. The size of the colors buffer is the return value of GetInterpolationColorCount multiplied by sizeof(Color). The size of the blend positions buffer is the value of GetInterpolationColorCount multiplied by sizeof(REAL).

Example Code [C++]

The following example sets the colors to be interpolated for this linear gradient brush to red, blue, and green and sets the blend positions to 0, 0.3, and 1. The code calls the GetInterpolationColorCount method of a LinearGradientBrush object to obtain the number of colors currently set to be interpolated for the brush. Next, the code gets the colors and their positions. Then, the code fills a small rectangle with each color.

VOID Example_GetInterpColors(HDC hdc)
{
   Graphics myGraphics(hdc);

   // Create a linear gradient brush, and set the colors to be interpolated.
   Color col[] = {
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255),   // blue
      Color(255, 0, 255, 0)};  // green

   REAL pos[] = {
      0.0f,   // red at the left edge
      0.3f,   // blue at 30 percent of the distance from
              // left edge to right edge
      1.0f};  // green at the right edge

   LinearGradientBrush linGrBrush(
      Point(0, 0),
      Point(100, 0),
      Color(255, 0, 0, 0),         // black
      Color(255, 255, 255, 255));  // white

   linGrBrush.SetInterpolationColors(col, pos, 3);

   // Obtain information about the linear gradient brush.
   INT    colorCount = 0;
   Color* colors = NULL;
   REAL*  positions = NULL;

   // How many colors have been specified to be interpolated
   // for this brush?
   colorCount = linGrBrush.GetInterpolationColorCount();

   // Allocate a buffer large enough to hold the set of colors.
   colors = new Color[colorCount];

   // Allocate a buffer to hold the relative positions of the colors.
   positions = REAL[colorCount];

   // Get the colors and their relative positions.
   linGrBrush.GetInterpolationColors(colors, positions, colorCount);

   // Fill a small rectangle with each of the colors.
   SolidBrush* pSolidBrush;
   for(INT j = 0; j < colorCount; j++)
   {
      pSolidBrush = new SolidBrush(colors[j]);
      myGraphics.FillRectangle(pSolidBrush, 15*j, 0, 10, 10);
      delete(pSolidBrush);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, GetInterpolationColors, PathGradientBrush, Rect, SetInterpolationColors, SolidBrush
Tasks and Examples
Creating a Linear Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


LinearGradientBrush::GetInterpolationColors(presetColors, blendPositions, count)

The GetInterpolationColors method gets the colors currently set to be interpolated for this linear gradient brush and their corresponding blend positions.

Status GetInterpolationColors(
  Color* presetColors,
  REAL* blendPositions,
  INT count
) const;

Parameters

presetColors
[out] Pointer to an array that receives the colors. A color of a given index in the presetColors array corresponds to the blend position of that same index in the blendPositions array.
blendPositions
[out] Pointer to an array that receives the blend positions. Each number in the array indicates a percentage of the distance between the starting boundary and the ending boundary and is in the range from 0.0 through 1.0, where 0.0 indicates the starting boundary of the gradient and 1.0 indicates the ending boundary. A blend position between 0.0 and 1.0 indicates a line, parallel to the boundary lines, that is a certain fraction of the distance from the starting boundary to the ending boundary. For example, a blend position of 0.7 indicates the line that is 70 percent of the distance from the starting boundary to the ending boundary. The color is constant on lines that are parallel to the boundary lines.
count
[in] Integer that specifies the number of elements in the presetColors array. This is the same as the number of elements in the blendPositions array. Before calling the GetInterpolationColors method of a LinearGradientBrush object, call the GetInterpolationColorCount method of that same LinearGradientBrush object to determine the current number of colors. The number of blend positions retrieved is the same as the number of colors retrieved.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example sets the colors that are interpolated for this linear gradient brush to red, blue, and green and sets the blend positions to 0, 0.3, and 1. The code calls the GetInterpolationColorCount method of a LinearGradientBrush object to obtain the number of colors currently set to be interpolated for the brush. Next, the code gets the colors and their positions. Then, the code fills a small rectangle with each color.

VOID Example_GetInterpColors(HDC hdc)
{
   Graphics myGraphics(hdc);

   // Create a linear gradient brush, and set the colors to be interpolated.
   Color col[] = {
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255),   // blue
      Color(255, 0, 255, 0)};  // green

   REAL pos[] = {
      0.0f,   // red at the left edge
      0.3f,   // blue at 30 percent of the distance from left edge
              // to right edge
      1.0f};  // green at the right edge

   LinearGradientBrush linGrBrush(
      Point(0, 0),
      Point(100, 0),
      Color(255, 0, 0, 0),         // black
      Color(255, 255, 255, 255));  // white

   linGrBrush.SetInterpolationColors(col, pos, 3);

   // Obtain information about the linear gradient brush.
   INT    colorCount = 0;
   Color* colors = NULL;
   REAL*  positions = NULL;

   // How many colors have been specified to be interpolated
   // for this brush?
   colorCount = linGrBrush.GetInterpolationColorCount();

   // Allocate a buffer large enough to hold the set of colors.
   colors = (Color*)malloc(colorCount*sizeof(Color));

   // Allocate a buffer to hold the relative positions of the colors.
   positions = (REAL*)malloc(colorCount*sizeof(REAL));

   // Get the colors and their relative positions.
   linGrBrush.GetInterpolationColors(colors, positions, colorCount);

   // Fill a small rectangle with each of the colors.
   SolidBrush* pSolidBrush;
   for(INT j = 0; j < colorCount; ++j)
   {
      pSolidBrush = new SolidBrush(colors[j]);
      myGraphics.FillRectangle(pSolidBrush, 15*j, 0, 10, 10);
      delete(pSolidBrush);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, GetInterpolationColorCount, PathGradientBrush, Rect, SetInterpolationColors, SolidBrush
Tasks and Examples
Creating a Linear Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


LinearGradientBrush::GetLinearColors(colors)

The GetLinearColors method gets the starting color and ending color of this linear gradient brush.

Status GetLinearColors(
  Color* colors
) const;

Parameters

colors
[out] Pointer to an array that receives the starting color and the ending color. The first color in the colors array is the color at the starting boundary line of the gradient; the second color in the colors array is the color at the ending boundary line.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a linear gradient brush and gets the boundary colors. Next, the code uses each of the two colors to create a solid brush. Then, the code fills a rectangle with each solid brush.

VOID Example_GetLinColors(HDC hdc)
{
   Graphics myGraphics(hdc);

   // Create a linear gradient brush.
   LinearGradientBrush linGrBrush(
      Rect(0, 0, 100, 50),
      Color(255, 0, 0, 0),    // black
      Color(255, 0, 0, 255),  // blue
      LinearGradientModeHorizontal);

   // Obtain information about the linear gradient brush.
   Color colors[2];
   linGrBrush.GetLinearColors(colors);

   // Fill a small rectangle with each of the two colors.
   SolidBrush solidBrush0(colors[0]);
   SolidBrush solidBrush1(colors[1]);
   myGraphics.FillRectangle(&solidBrush0, 0, 0, 20, 20);
   myGraphics.FillRectangle(&solidBrush1, 25, 0, 20, 20);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, Rect, SetLinearColors, SolidBrush
Tasks and Examples
Creating a Linear Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


LinearGradientBrush::GetRectangle Methods

This topic lists the GetRectangle methods of the LinearGradientBrush class. For a complete list of methods for the LinearGradientBrush class, see LinearGradientBrush Methods.

  • GetRectangle(Rect* rect)
  • GetRectangle(RectF* rect)


LinearGradientBrush::GetRectangle(Rect* rect)

The GetRectangle method gets the rectangle that defines the boundaries of the gradient.

Status GetRectangle(
  Rect* rect
) const;

Parameters

rect
[out] Pointer to a Rect object that receives the rectangle that defines the boundaries of the gradient. For example, if a linear gradient brush is constructed with a starting point at (20, 50) and an ending point at (60, 110), then the defining rectangle has its upper-left point at (20, 50), a width of 40, and a height of 60.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The rectangle defines the boundaries of the gradient in the following ways: The right and left sides of the rectangle form the boundaries of a horizontal gradient. The top and bottom sides form the boundaries of a vertical gradient. Two of the diagonally opposing corners lie on the boundaries of a diagonal gradient. In each of these cases, either side/corner may be on the starting boundary, depending on how the starting and ending points are passed to the constructor.

Example Code [C++]

The following example creates a linear gradient brush. Then the code gets the brush's rectangle and draws it.

VOID Example_GetRect(HDC hdc)
{
   Graphics myGraphics(hdc);

   // Create a linear gradient brush.
   LinearGradientBrush linGrBrush(
      Point(20, 10),
      Point(60, 110),
      Color(255, 0, 0, 0),     // black
      Color(255, 0, 0, 255));  // blue

   // Obtain information about the linear gradient brush.
   Rect rect;
   linGrBrush.GetRectangle(&rect);

   // Draw the retrieved rectangle.
   Pen myPen(Color(255, 0, 0, 0));
   myGraphics.DrawRectangle(&myPen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Pen, Point, Rect
Tasks and Examples
Creating a Linear Gradient, Using a Pen to Draw Lines and Rectangles
Concepts
Brushes and Filled Shapes, Pens, Lines, and Rectangles


LinearGradientBrush::GetRectangle(RectF* rect)

The GetRectangle method gets the rectangle that defines the boundaries of the gradient.

Status GetRectangle(
  RectF* rect
) const;

Parameters

rect
[out] Pointer to a RectF object that receives the rectangle that defines the boundaries of the gradient. For example, if a linear gradient brush is constructed with a starting point at (20.2, 50.8) and an ending point at (60.5, 110.0), then the defining rectangle has its upper-left point at (20.2, 50.8), a width of 40.3, and a height of 59.2.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The rectangle defines the boundaries of the gradient in the following ways: The right and left sides of the rectangle form the boundaries of a horizontal gradient. The top and bottom sides form the boundaries of a vertical gradient. Two of the diagonally opposing corners lie on the boundaries of a diagonal gradient. In each of these cases, either side/corner may be on the starting boundary, depending on how the starting and ending points are passed to the constructor.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Pen, RectF
Tasks and Examples
Creating a Linear Gradient, Using a Pen to Draw Lines and Rectangles
Concepts
Brushes and Filled Shapes, Pens, Lines, and Rectangles


LinearGradientBrush::GetTransform(matrix)

The GetTransform method gets the transformation matrix of this linear gradient brush.

Status GetTransform(
  Matrix* matrix
) const;

Parameters

matrix
[out] Pointer to a Matrix object that receives the transformation matrix.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A LinearGradientBrush object maintains a transformation matrix that can store any affine transformation. When you use a linear gradient brush to fill an area, GDI+ transforms the brush's boundary lines according to the brush's transformation matrix and then fills the area. The transformed boundaries exist only during rendering; the boundaries stored in the LinearGradientBrush object are not transformed.

Example Code [C++]

The following example creates a linear gradient brush and sets its transformation matrix. Next, the code gets the brush's transformation matrix and proceeds to inspect or use the matrix elements.

VOID Example_GetTransform(HDC hdc)
{
   Graphics myGraphics(hdc);

   // Construct a linear gradient brush, and set its transformation.
   LinearGradientBrush linGrBrush(
      Point(0, 0),
      Point(200, 0),
      Color(255, 255, 0, 0),    // red
      Color(255, 0, 0, 255));   // blue

   Matrix matrixSet(0, 1, -1, 0, 0, 0);

   linGrBrush.SetTransform(&matrixSet);

   // Obtain information about the linear gradient brush.
   Matrix matrixGet;
   REAL   elements[6];

   linGrBrush.GetTransform(&matrixGet);
   matrixGet.GetElements(elements);

   for(INT j = 0; j <= 5; ++j)
   {
       // Inspect or use the value in elements[j].
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Matrix, Point, SetTransform
Tasks and Examples
Filling a Shape with a Color Gradient, Filling Shapes with a Gradient Brush, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


LinearGradientBrush::GetWrapMode()

The GetWrapMode method gets the wrap mode for this brush. The wrap mode determines how an area is tiled when it is painted with a brush.

WrapMode GetWrapMode(void) const;

Parameters

This method has no parameters.

Return Values

This method returns one of the following elements of the WrapMode enumeration:

WrapModeTile
WrapModeTileFlipX
WrapModeTileFlipY
WrapModeTileFlipXY

Remarks

The boundary lines of a linear gradient brush form a tile. When you paint an area with a linear gradient brush, the tile repeats. A linear gradient brush can have alternate tiles flipped in a certain direction, as specified by the wrap mode. Flipping has the effect of reversing the order of the colors.

The default wrap mode for a linear gradient brush is WrapModeTile, which indicates that no flipping occurs.

Example Code [C++]

The following example creates a linear gradient brush and sets its wrap mode. Next, the code gets the brush's wrap mode and performs tasks based on the brush's current wrap mode.

VOID Example_GetWrapMode(HDC hdc)
{
   Graphics myGraphics(hdc);

   // Create a linear gradient brush, and set its wrap mode.
   LinearGradientBrush linGrBrush(
      Point(0,0),
      Point(200, 0),
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255));  // blue

   linGrBrush.SetWrapMode(WrapModeTileFlipX);

   // Obtain information about the linear gradient brush.
   WrapMode wrapMode;
   wrapMode = linGrBrush.GetWrapMode();

   if (wrapMode == WrapModeTileFlipX)
   {
       // Do some task.
   }
   else if (wrapMode == WrapModeTileFlipY)
   {
       // Do a different task.
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Point, SetWrapMode, WrapMode
Tasks and Examples
Filling Shapes with a Gradient Brush, Tiling a Shape with an Image
Concepts
Brushes and Filled Shapes


LinearGradientBrush::MultiplyTransform(matrix, order)

The MultiplyTransform method updates this brush's transformation matrix with the product of itself and another matrix.

Status MultiplyTransform(
  const Matrix* matrix,
  MatrixOrder order
);

Parameters

matrix
[in] Pointer to a matrix to be multiplied by the brush's current transformation matrix.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the passed matrix is on the left, and MatrixOrderAppend specifies that the passed matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A single 3×3 matrix can store any sequence of affine transformations. If you have several 3×3 matrices, each of which represents an affine transformation, the product of those matrices is a single 3×3 matrix that represents the entire sequence of transformations. The transformation represented by that product is called a composite transformation. For example, suppose matrix R represents a rotation, and matrix T represents a translation. If matrix M is the product RT, then matrix M represents a composite transformation: first rotate, then translate.

The order of matrix multiplication is important. In general, the matrix product RT is not the same as the matrix product TR. In the example given in the previous paragraph, the composite transformation represented by RT (first rotate, then translate) is not the same as the composite transformation represented by TR (first translate, then rotate).

Example Code [C++]

The following example creates a linear gradient brush and uses it to fill a rectangle. Next, the code sets the brush's transformation matrix, fills a rectangle with the transformed brush, modifies the brush's transformation matrix, and again fills a rectangle with the transformed brush.

VOID Example_MultTrans(HDC hdc)
{
   Graphics myGraphics(hdc);

   Matrix S(2, 0, 0, 1, 0, 0);   // horizontal doubling
   Matrix T(1, 0, 0, 1, 50, 0);  // horizontal translation of 50 units

   LinearGradientBrush linGrBrush(
      Rect(0, 0, 200, 100),
      Color(255, 255, 0, 0),     // red
      Color(255, 0, 0, 255),     // blue
      LinearGradientModeHorizontal);

   // Fill a large area with the gradient brush (no transformation).
   myGraphics.FillRectangle(&linGrBrush, 0, 0, 800, 100);

   // Apply the scaling transformation.
   linGrBrush.SetTransform(&S);

   // Fill a large area with the scaled gradient brush.
   myGraphics.FillRectangle(&linGrBrush, 0, 150, 800, 100);

   // Form a composite transformation: first scale, then translate.
   linGrBrush.MultiplyTransform(&T, MatrixOrderAppend);

   // Fill a large area with the scaled and translated gradient brush.
   myGraphics.FillRectangle(&linGrBrush, 0, 300, 800, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Matrix, MatrixOrder, Rect, RotateTransform, ScaleTransform, TranslateTransform
Tasks and Examples
Filling Shapes with a Gradient Brush, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


LinearGradientBrush::ResetTransform()

The ResetTransform method resets the transformation matrix of this linear gradient brush to the identity matrix. This means that no transformation takes place.

Status ResetTransform(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a linear gradient brush and uses it to fill a rectangle. Next, the code sets the brush's transformation matrix, fills a rectangle with the transformed brush, resets the brush's transformation matrix, and fills a rectangle with the untransformed brush.

VOID Example_ResetTrans(HDC hdc)
{
   Graphics myGraphics(hdc);

   Matrix S(2, 0, 0, 1, 0, 0);   // horizontal doubling

   LinearGradientBrush linGrBrush(
      Rect(0, 0, 200, 100),
      Color(255, 255, 0, 0),  // red
      Color(255, 0, 0, 255),  // blue
      LinearGradientModeHorizontal);

   // Fill a large area with the gradient brush (no transformation).
   myGraphics.FillRectangle(&linGrBrush, 0, 0, 800, 100);

   // Apply the scaling transformation.
   linGrBrush.SetTransform(&S);

   // Fill a large area with the scaled gradient brush.
   myGraphics.FillRectangle(&linGrBrush, 0, 150, 800, 100);

   // Reset the transformation.
   linGrBrush.ResetTransform();

   // Fill a large area with the gradient brush (no transformation).
   myGraphics.FillRectangle(&linGrBrush, 0, 300, 800, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, MultiplyTransform, RotateTransform, ScaleTransform, SetTransform, TranslateTransform
Tasks and Examples
Filling Shapes with a Gradient Brush, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


LinearGradientBrush::RotateTransform(angle, order)

The RotateTransform method updates this brush's current transformation matrix with the product of itself and a rotation matrix.

Status RotateTransform(
  REAL angle,
  MatrixOrder order
);

Parameters

angle
[in] Real number that specifies the angle of rotation in degrees.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the rotation matrix is on the left, and MatrixOrderAppend specifies that the rotation matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A single 3×3 matrix can store any sequence of affine transformations. If you have several 3×3 matrices, each of which represents an affine transformation, the product of those matrices is a single 3×3 matrix that represents the entire sequence of transformations. The transformation represented by that product is called a composite transformation. For example, suppose matrix T represents a translation, and matrix R represents a rotation. If matrix M is the product TR, then matrix M represents a composite transformation: first translate, then rotate.

The order of matrix multiplication is important. In general, the matrix product RT is not the same as the matrix product TR. In the example given in the previous paragraph, the composite transformation represented by RT (first rotate, then translate) is not the same as the composite transformation represented by TR (first translate, then rotate).

Example Code [C++]

The following example creates a linear gradient brush and uses it to fill a rectangle. Next, the code modifies the brush's transformation matrix, applying a composite transformation, and then fills a rectangle with the transformed brush.

VOID Example_RotateTrans(HDC hdc)
{
   Graphics myGraphics(hdc);

   LinearGradientBrush linGrBrush(
      Rect(0, 0, 80, 40),
      Color(255, 255, 0, 0),  // red
      Color(255, 0, 0, 255),  // blue
      LinearGradientModeHorizontal);

   // Fill a large area with the linear gradient brush (no transformation).
   myGraphics.FillRectangle(&linGrBrush, 0, 0, 800, 150);

   // Apply a composite transformation: first scale, then rotate.
   linGrBrush.ScaleTransform(2, 1);                    // horizontal doubling
   linGrBrush.RotateTransform(20, MatrixOrderAppend);  // 20-degree rotation

   // Fill a large area with the transformed linear gradient brush.
   myGraphics.FillRectangle(&linGrBrush, 0, 200, 800, 150);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Matrix, MatrixOrder, MultiplyTransform, Rect, ScaleTransform, TranslateTransform
Tasks and Examples
Filling Shapes with a Gradient Brush, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


LinearGradientBrush::ScaleTransform(sx, sy, order)

The ScaleTransform method updates this brush's current transformation matrix with the product of itself and a scaling matrix.

Status ScaleTransform(
  REAL sx,
  REAL sy,
  MatrixOrder order
);

Parameters

sx
[in] Real number that specifies the amount to scale in the x direction.
sy
[in] Real number that specifies the amount to scale in the y direction.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the scaling matrix is on the left, and MatrixOrderAppend specifies that the scaling matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A single 3×3 matrix can store any sequence of affine transformations. If you have several 3×3 matrices, each of which represents an affine transformation, the product of those matrices is a single 3×3 matrix that represents the entire sequence of transformations. The transformation represented by that product is called a composite transformation. For example, suppose matrix T represents a translation, and matrix S represents a scaling. If matrix M is the product TS, then matrix M represents a composite transformation: first translate, then scale.

The order of matrix multiplication is important. In general, the matrix product RT is not the same as the matrix product TR. In the example given in the previous paragraph, the composite transformation represented by RT (first rotate, then translate) is not the same as the composite transformation represented by TR (first translate, then rotate).

Example Code [C++]

The following example creates a linear gradient brush and uses it to fill a rectangle. Next, the code modifies the brush's transformation matrix, applying a composite transformation, and then fills a rectangle with the transformed brush.

VOID Example_ScaleTrans(HDC hdc)
{
   Graphics myGraphics(hdc);

   LinearGradientBrush linGrBrush(
      Rect(0, 0, 80, 40),
      Color(255, 255, 0, 0),  // red
      Color(255, 0, 0, 255),  // blue
      LinearGradientModeHorizontal);

   // Fill a large area with the linear gradient brush (no transformation).
   myGraphics.FillRectangle(&linGrBrush, 0, 0, 800, 150);

   // Apply a composite transformation: first translate, then scale.
   linGrBrush.TranslateTransform(60, 0);            // horizontal translation
   linGrBrush.ScaleTransform(2, MatrixOrderAppend); // horizontal doubling

   // Fill a large area with the transformed linear gradient brush.
   myGraphics.FillRectangle(&linGrBrush, 0, 200, 800, 150);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
LinearGradientMode, Matrix, MatrixOrder, MultiplyTransform, Rect, RotateTransform, TranslateTransform
Tasks and Examples
Filling Shapes with a Gradient Brush, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


LinearGradientBrush::SetBlend(blendFactors, blendPositions, count)

The SetBlend method sets the blend factors and the blend positions of this linear gradient brush to create a custom blend.

Status SetBlend(
  const REAL* blendFactors,
  const REAL* blendPositions,
  INT count
);

Parameters

blendFactors
[in] Pointer to an array of real numbers that specify blend factors. Each number in the array specifies a percentage of the ending color and should be in the range from 0.0 through 1.0.
blendPositions
[in] Pointer to an array of real numbers that specify blend positions. Each number in the array indicates a percentage of the distance between the starting boundary and the ending boundary and is in the range from 0.0 through 1.0, where 0.0 indicates the starting boundary of the gradient and 1.0 indicates the ending boundary. There must be at least two positions specified: the first position, which is always 0.0f, and the last position, which is always 1.0f. Otherwise, the behavior is undefined. A blend position between 0.0 and 1.0 indicates a line, parallel to the boundary lines, that is a certain fraction of the distance from the starting boundary to the ending boundary. For example, a blend position of 0.7 indicates the line that is 70 percent of the distance from the starting boundary to the ending boundary. The color is constant on lines that are parallel to the boundary lines.
count
[in] Integer that specifies the number of elements in the blendFactors array. This is the same as the number of elements in the blendPositions array. The blend factor at a given array index corresponds to the blend position at that same array index.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A LinearGradientBrush object has two boundaries. When you fill an area with a linear gradient brush, the color changes gradually as you move from the starting boundary to the ending boundary. By default, the color is linearly related to the distance, but you can customize the relationship between color and distance by calling the SetBlend method.

Example Code [C++]

The following example creates a linear gradient brush, sets a custom blend, and uses the brush to fill a rectangle.

VOID Example_SetBlend(HDC hdc)
{
   Graphics myGraphics(hdc);

   REAL factors[4] = {0.0f, 0.4f, 0.6f, 1.0f};
   REAL positions[4] = {0.0f, 0.2f, 0.8f, 1.0f};
   Rect rect(0, 0, 100, 50);

   LinearGradientBrush linGrBrush(
      rect,
      Color(255, 255, 0, 0),  // red
      Color(255, 0, 0, 255),  // blue
      LinearGradientModeHorizontal);

   linGrBrush.SetBlend(factors, positions, 4);
   myGraphics.FillRectangle(&linGrBrush, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, GetBlend, Rect
Tasks and Examples
Creating a Linear Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


LinearGradientBrush::SetBlendBellShape(focus, scale)

The SetBlendBellShape method sets the blend shape of this linear gradient brush to create a custom blend based on a bell-shaped curve.

Status SetBlendBellShape(
  REAL focus,
  REAL scale
);

Parameters

focus
[in] Real number that specifies the position of the ending color. This number is a percentage of the distance between the boundary lines and must be in the range from 0.0 through 1.0.
scale
[in] Optional. Real number that specifies the percentage of the gradient's ending color that gets blended, at the focus position, with the gradient's starting color. This number must be in the range from 0.0 through 1.0. The default value is 1.0, which specifies that the ending color is at full intensity.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

By default, the color changes gradually from the starting color (color at the starting boundary of the linear gradient brush) to the ending color (color at the ending boundary of the linear gradient brush) as you move from the starting boundary to the ending boundary. You can customize the positioning and blending of the starting and ending colors by using the SetBlendBellShape method.

The SetBlendBellShape method customizes the blend so that it follows a bell-shaped curve with the extremes of the bell's base at the gradient's boundaries. The starting color, which, in a default blend, is at the starting boundary of a linear gradient brush, appears at the starting and ending boundaries of the linear gradient brush when a bell-shaped blend is applied. The position of the ending color, which, in a default blend, is at the ending boundary, is somewhere between the boundaries and is determined by the value of the focus. In other words, the focus specifies the position of the peak of the bell. For example, a focus value of 0.7 places the peak at 70 percent of the distance between the starting and ending boundaries. The ending color appears at this peak.

The ending color in a bell-shaped blend is a percentage of the gamut between the gradient's default-blend starting color and default-blend ending color. For example, suppose a linear gradient brush is constructed with red as the starting color and blue as the ending color. If SetBlendBellShape is called with a scale value of 0.8, the ending color in the bell shaped blend is a hue that is 80 percent between red and blue (20 percent red, 80 percent blue). A scale value of 1.0 produces an ending color that is 100 percent blue.

Example Code [C++]

The following example creates a linear gradient brush, sets a bell-shaped blend, and uses the brush to fill a rectangle. Twice more, the code sets a bell-shaped blend with different values and, each time, uses the brush to fill a rectangle.

VOID Example_SetBlendBell(HDC hdc)
{
   Graphics myGraphics(hdc);

   LinearGradientBrush linGrBrush(
      Point(0, 0),
      Point(500, 0),
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255));  // blue

   linGrBrush.SetBlendBellShape(0.5f, 0.6f);
   myGraphics.FillRectangle(&linGrBrush, 0, 0, 500, 50);

   linGrBrush.SetBlendBellShape(0.5f, 0.8f);
   myGraphics.FillRectangle(&linGrBrush, 0, 75, 500, 50);

   linGrBrush.SetBlendBellShape(0.5f, 1.0f);
   myGraphics.FillRectangle(&linGrBrush, 0, 150, 500, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetBlend, SetBlend, SetBlendTriangularShape
Tasks and Examples
Creating a Linear Gradient, Filling a Shape with a Color Gradient, Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


LinearGradientBrush::SetBlendTriangularShape(focus, scale)

The SetBlendTriangularShape method sets the blend shape of this linear gradient brush to create a custom blend based on a triangular shape.

Status SetBlendTriangularShape(
  REAL focus,
  REAL scale
);

Parameters

focus
[in] Real number that specifies the position of the ending color. This number is a percentage of the distance between the boundary lines and must be in the range from 0.0 through 1.0.
scale
[in] Optional. Real number that specifies the percentage of the gradient's ending color that gets blended, at the focus position, with the gradient's starting color. This number must be in the range from 0.0 through 1.0. The default value is 1.0, which specifies that the ending color is at full intensity.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

By default, the color changes gradually from the starting color (color at the starting boundary of the linear gradient brush) to the ending color (color at the ending boundary of the linear gradient brush) as you move from the starting boundary to the ending boundary. You can customize the positioning and blending of the starting and ending colors by using the SetBlendTriangularShape method.

The SetBlendTriangularShape method customizes the blend so that it follows a triangular shape with the extremes of the triangle's base at the gradient's boundaries. The starting color, which, in a default blend, is at the starting boundary of a linear gradient brush, appears at the starting and ending boundaries of the linear gradient brush when a triangular-shaped blend is applied. The position of the ending color, which, in a default blend, is at the ending boundary, is somewhere between the boundaries and is determined by the value of the focus. In other words, the focus specifies the position of the peak of the triangle. For example, a focus value of 0.5 places the peak half way between the starting and ending boundaries. The ending color appears at this peak.

The ending color in a triangular-shaped blend is a percentage of the gamut between the gradient's default-blend starting color and default-blend ending color. For example, suppose a linear gradient brush is constructed with red as the starting color and blue as the ending color. If SetBlendTriangularShape is called with a scale value of 0.3, the ending color in the triangular-shaped blend is a hue that is 30 percent between red and blue (70 percent red, 30 percent blue). A scale value of 1.0 produces an ending color that is 100 percent blue.

Example Code [C++]

The following example creates a linear gradient brush, sets a triangular-shaped blend, and uses the brush to fill a rectangle. Twice more, the code sets a triangular-shaped blend with different values and, each time, uses the brush to fill a rectangle.

VOID Example_SetBlendTri(HDC hdc)
{
   Graphics myGraphics(hdc);

   LinearGradientBrush linGrBrush(
      Point(0, 0),
      Point(500, 0),
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255));  // blue

   linGrBrush.SetBlendTriangularShape(0.5f, 0.6f);
   myGraphics.FillRectangle(&linGrBrush, 0, 0, 500, 50);

   linGrBrush.SetBlendTriangularShape(0.5f, 0.8f);
   myGraphics.FillRectangle(&linGrBrush, 0, 75, 500, 50);

   linGrBrush.SetBlendTriangularShape(0.5f, 1.0f);
   myGraphics.FillRectangle(&linGrBrush, 0, 150, 500, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetBlend, Point, SetBlend, SetBlendBellShape
Tasks and Examples
Creating a Linear Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


LinearGradientBrush::SetGammaCorrection(useGammaCorrection)

The SetGammaCorrection method specifies whether gamma correction is enabled for this linear gradient brush.

Status SetGammaCorrection(
  BOOL useGammaCorrection
);

Parameters

useGammaCorrection
[in] Boolean value that specifies whether gamma correction occurs during rendering. TRUE specifies that gamma correction is enabled, and FALSE specifies that gamma correction is not enabled. By default, gamma correction is disabled during construction of a LinearGradientBrush object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Gamma correction is often done to match the intensity contrast of the gradient to the ability of the human eye to perceive intensity changes.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, GetGammaCorrection, Rect


LinearGradientBrush::SetInterpolationColors(presetColors, blendPositions, count)

The SetInterpolationColors method sets the colors to be interpolated for this linear gradient brush and their corresponding blend positions.

Status SetInterpolationColors(
  const Color* presetColors,
  const REAL* blendPositions,
  INT count
);

Parameters

presetColors
[in] Pointer to an array of Color objects that specify the colors to be interpolated for this linear gradient brush. A color of a given index in the presetColors array corresponds to the blend position of that same index in the blendPositions array.
blendPositions
[in] Pointer to an array of real numbers that specify the blend positions. Each number in the array specifies a percentage of the distance between the starting boundary and the ending boundary and is in the range from 0.0 through 1.0, where 0.0 indicates the starting boundary of the gradient and 1.0 indicates the ending boundary. There must be at least two positions specified: the first position, which is always 0.0f, and the last position, which is always 1.0f. Otherwise, the behavior is undefined. A blend position between 0.0 and 1.0 indicates the line, parallel to the boundary lines, that is a certain fraction of the distance from the starting boundary to the ending boundary. For example, a blend position of 0.7 indicates the line that is 70 percent of the distance from the starting boundary to the ending boundary. The color is constant on lines that are parallel to the boundary lines.
count
[in] Integer that specifies the number of elements in the presetColors array. This is the same as the number of elements in the blendPositions array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a linear gradient brush, sets the colors to be interpolated for the linear gradient brush, and fills a rectangle.

VOID Example_SetInterpColors(HDC hdc)
{
   Graphics myGraphics(hdc);

   Color colors[] = {
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255),   // blue
      Color(255, 0, 255, 0)};  // green

   REAL positions[] = {
      0.0f,   // red at the left edge
      0.3f,   // blue at 30 percent of the distance from left edge
              // to right edge
      1.0f};  // green at the right edge

   LinearGradientBrush linGrBrush(
      Point(0, 0),
      Point(100, 0),
      Color(255, 0, 0, 0),         // black
      Color(255, 255, 255, 255));  // white

   linGrBrush.SetInterpolationColors(colors, positions, 3);
   myGraphics.FillRectangle(&linGrBrush, 0, 0, 100, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, GetinterpolationColors
Tasks and Examples
Creating a Linear Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


LinearGradientBrush::SetLinearColors(color1, color2)

The SetLinearColors method sets the starting color and ending color of this linear gradient brush.

Status SetLinearColors(
  const Color& color1,
  const Color& color2
);

Parameters

color1
[in] Reference to a Color object that specifies the color at the starting boundary line of this linear gradient brush.
color2
[in] Reference to a Color object that specifies the color at the ending boundary line of this linear gradient brush.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a linear gradient brush and uses it to fill a rectangle. Next, the code changes the linear colors and uses the modified brush to fill another rectangle.

VOID Example_SetLinColors(HDC hdc)
{
   Graphics myGraphics(hdc);

   LinearGradientBrush linGrBrush(
      Rect(0, 0, 100, 50),
      Color(255, 255, 0, 0),  // red
      Color(255, 0, 0, 255),  // blue
      LinearGradientModeHorizontal);

   myGraphics.FillRectangle(&linGrBrush, 0, 0, 100, 50);

   linGrBrush.SetLinearColors(
      Color(255, 0, 0, 255),   // blue
      Color(255, 0, 255, 0));  // green

   myGraphics.FillRectangle(&linGrBrush, 0, 75, 100, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, GetLinearColors, Rect, SetInterpolationColors
Tasks and Examples
Creating a Linear Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


LinearGradientBrush::SetTransform(matrix)

The SetTransform method sets the transformation matrix of this linear gradient brush.

Status SetTransform(
  const Matrix* matrix
);

Parameters

matrix
[in] Pointer to a Matrix object that specifies the transformation matrix.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A LinearGradientBrush object has a rectangle that specifies the starting and ending boundaries of the gradient and a mode or angle that affects the direction. If the brush's transformation matrix is set to represent any transformation other than the identity, then the boundaries and direction are transformed according to that matrix during rendering.

The transformation applies only during rendering. The boundaries stored by the LinearGradientBrush object are not altered by the SetTransform method.

Example Code [C++]

The following example creates a linear gradient brush and uses it to fill a rectangle. Next, the code modifies the brush's transformation matrix and fills a rectangle with the transformed brush.

VOID Example_SetTransform(HDC hdc)
{
   Graphics myGraphics(hdc);

   LinearGradientBrush linGrBrush(
      Rect(0, 0, 100, 50),
      Color(255, 255, 0, 0),  // red
      Color(255, 0, 0, 255),  // blue
      LinearGradientModeHorizontal);

   Matrix matrix(2.0, 0, 0, 1, 0, 0);  // horizontal doubling

   // Fill a large area with the linear gradient brush (no transformation).
   myGraphics.FillRectangle(&linGrBrush, 0, 0, 800, 50);

   linGrBrush.SetTransform(&matrix);

   // Fill a large area with the transformed linear gradient brush.
   myGraphics.FillRectangle(&linGrBrush, 0, 75, 800, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Matrix, GetTransform, Rect, ResetTransform
Tasks and Examples
Creating a Linear Gradient, Filling Shapes with a Gradient Brush, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


LinearGradientBrush::SetWrapMode(wrapMode)

The SetWrapMode method sets the wrap mode of this linear gradient brush.

Status SetWrapMode(
  WrapMode wrapMode
);

Parameters

wrapMode
[in] Element of the WrapMode enumeration that specifies how areas painted with this linear gradient brush will be tiled. The value of this parameter must be one of the following elements:

WrapModeTile
WrapModeTileFlipX
WrapModeTileFlipY
WrapModeTileFlipXY

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The boundary lines of a linear gradient brush form a tile. When you paint an area with a linear gradient brush, the tile repeats. A linear gradient brush may have alternate tiles flipped in a certain direction, as specified by the wrap mode. Flipping has the effect of reversing the order of the colors.

The wrap mode defaults to WrapModeTile when a LinearGradientBrush object is constructed.

Example Code [C++]

The following example creates a linear gradient brush and uses it to fill a rectangle. Next, the code modifies the brush's wrap mode and uses the modified brush to fill another rectangle.

VOID Example_SetWrapMode(HDC hdc)
{
   Graphics myGraphics(hdc);

   LinearGradientBrush linGrBrush(
      Rect(0, 0, 100, 50),
      Color(255, 255, 0, 0),  // red
      Color(255, 0, 0, 255),  // blue
      LinearGradientModeHorizontal);

   // Fill a large area using the gradient brush with the default wrap mode.
   myGraphics.FillRectangle(&linGrBrush, 0, 0, 800, 50);

   linGrBrush.SetWrapMode(WrapModeTileFlipX);

   // Fill a large area using the gradient brush with the new wrap mode.
   myGraphics.FillRectangle(&linGrBrush, 0, 75, 800, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetWrapMode, Rect, WrapMode
Tasks and Examples
Creating a Linear Gradient, Tiling a Shape with an Image
Concepts
Brushes and Filled Shapes


LinearGradientBrush::TranslateTransform(dx, dy, order)

The TranslateTransform method updates this brush's current transformation matrix with the product of itself and a translation matrix.

Status TranslateTransform(
  REAL dx,
  REAL dy,
  MatrixOrder order
);

Parameters

dx
[in] Real number that specifies the horizontal component of the translation.
dy
[in] Real number that specifies the vertical component of the translation.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the translation matrix is on the left, and MatrixOrderAppend specifies that the translation matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A single 3×3 matrix can store any sequence of affine transformations. If you have several 3×3 matrices, each of which represents an affine transformation, the product of those matrices is a single 3×3 matrix that represents the entire sequence of transformations. The transformation represented by that product is called a composite transformation. For example, suppose matrix S represents a scaling, and matrix T represents a translation. If matrix M is the product ST, then matrix M represents a composite transformation: first scale, then translate.

The order of matrix multiplication is important. In general, the matrix product RT is not the same as the matrix product TR. In the example given in the previous paragraph, the composite transformation represented by RT (first rotate, then translate) is not the same as the composite transformation represented by TR (first translate, then rotate).

Example Code [C++]

The following example creates a linear gradient brush and uses it to fill a rectangle. Next, the code modifies the brush's transformation matrix, applying a composite transformation, and then fills a rectangle with the transformed brush.

VOID Example_TranslateTrans(HDC hdc)
{
   Graphics myGraphics(hdc);

   LinearGradientBrush linGrBrush(
      Rect(0, 0, 80, 40),
      Color(255, 255, 0, 0),  // red
      Color(255, 0, 0, 255),  // blue
      LinearGradientModeHorizontal);

   // Fill a large area with the linear gradient brush (no transformation).
   myGraphics.FillRectangle(&linGrBrush, 0, 0, 800, 150);

   // Apply a composite transformation: first scale, then translate.
   linGrBrush.ScaleTransform(2, 1);                     // horizontal doubling
   linGrBrush.TranslateTransform(30, MatrixOrderAppend);// translation

   // Fill a large area with the transformed linear gradient brush.
   myGraphics.FillRectangle(&linGrBrush, 0, 200, 800, 150);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Matrix, MatrixOrder, MultiplyTransform, ResetTransform, RotateTransform, ScaleTransform
Tasks and Examples
Filling Shapes with a Gradient Brush, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


Matrix Class

A Matrix object represents a 3×3 matrix that, in turn, represents an affine transformation. A Matrix object stores only six of the 9 numbers in a 3×3 matrix because all 3×3 matrices that represent affine transformations have the same third column (0, 0, 1).

Inheritance

GdiplusBase
Matrix

Constructors

Constructor | Description
Matrix | Overloaded. Creates a Matrix object and initializes the elements of the matrix.

Methods

Method | Description
Clone | Creates a new Matrix object and initializes it with the contents of this matrix.
Equals | Determines whether the elements of this matrix are the same as the elements of another matrix.
GetElements | Gets the elements of this matrix.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
Invert | Updates this matrix with its inverse.
IsIdentity | Determines whether this matrix is the identity matrix.
IsInvertible | Determines whether this matrix is invertible.
Multiply | Updates this matrix with the product of itself and another matrix.
OffsetX | Gets the horizontal translation element.
OffsetY | Gets the vertical translation element.
Reset | Updates this matrix with the elements of the identity matrix.
Rotate | Updates this matrix with the product of itself and a rotation matrix.
RotateAt | Updates this matrix with the product of itself and a matrix that represents rotation about a specified point.
Scale | Updates this matrix with the product of itself and a scaling matrix.
SetElements | Sets the element of this matrix.
Shear | Updates this matrix with the product of itself and a shearing matrix.
TransformPoints | Multiplies each point in an array by this matrix.
TransformVectors | Multiplies each vector in an array by this matrix. Ignores the translation elements of this matrix.
Translate | Updates this matrix with the product of itself and a translation matrix.
~Matrix | Matrix object destructor.


Matrix Constructors

This topic lists the constructors of the Matrix class. For a complete class listing see Matrix Class.

  • Matrix()
  • Matrix(m11, m12, m21, m22, dx, dy)
  • Matrix(Rect& rect, Point* dstplg)
  • Matrix(RectF& rect, PointF* dstplg)


Matrix::Matrix()

Creates and initializes a Matrix object that represents the identity matrix.

Matrix(void);

Parameters

This constructor has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
Matrix Constructors
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::Matrix(m11, m12, m21, m22, dx, dy)

Creates and initializes a Matrix object based on six numbers that define an affine transformation.

Matrix(
  REAL m11,
  REAL m12,
  REAL m21,
  REAL m22,
  REAL dx,
  REAL dy
);

Parameters

m11
[in] Real number that specifies the element in the first row, first column.
m12
[in] Real number that specifies the element in the first row, second column.
m21
[in] Real number that specifies the element in the second row, first column.
m22
[in] Real number that specifies the element in the second row, second column.
dx
[in] Real number that specifies the element in the third row, first column.
dy
[in] Real number that specifies the element in the third row, second column.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
Matrix Constructors
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::Matrix(Rect& rect, Point* dstplg)

Creates a Matrix object based on a rectangle and a point.

Matrix(
  const Rect& rect,
  const Point* dstplg
);

Parameters

rect
[in] Reference to a Rect object. The X data member of the rectangle specifies the matrix element in row 1, column 1. The Y data member of the rectangle specifies the matrix element in row 1, column 2. The Width data member of the rectangle specifies the matrix element in row 2, column 1. The Height data member of the rectangle specifies the matrix element in row 2, column 2.
dstplg
[in] Pointer to a Point object. The X data member of the point specifies the matrix element in row 3, column 1. The Y data member of the point specifies the matrix element in row 3, column 2.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
Matrix Constructors, Point, Rect
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::Matrix(RectF& rect, PointF* dstplg)

Creates a Matrix object based on a rectangle and a point.

Matrix(
  const RectF& rect,
  const PointF* dstplg
);

Parameters

rect
[in] Reference to a RectF object. The X data member of the rectangle specifies the matrix element in row 1, column 1. The Y data member of the rectangle specifies the matrix element in row 1, column 2. The Width data member of the rectangle specifies the matrix element in row 2, column 1. The Height data member of the rectangle specifies the matrix element in row 2, column 2.
dstplg
[in] Pointer to a PointF object. The X data member of the point specifies the matrix element in row 3, column 1. The Y data member of the point specifies the matrix element in row 3, column 2.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
Matrix Constructors, PointF, RectF
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix Methods

This topic lists the methods of the Matrix class. For a complete class listing, see Matrix Class.

  • Clone()
  • Equals(matrix)
  • GetElements()
  • GetLastStatus()
  • Invert()
  • IsIdentity()
  • IsInvertible()
  • Multiply(matrix, order)
  • OffsetX()
  • OffsetY()
  • Reset()
  • Rotate(angle, order)
  • RotateAt(angle, center, order)
  • Scale(scaleX, scaleY, order)
  • SetElements(m11, m12, m21, m22, dx, dy)
  • Shear(shearX, shearY, order)
  • TransformPoints(Point* pts, INT count)
  • TransformPoints(PointF* pts, INT count)
  • TransformVectors(Point* pts, INT count)
  • TransformVectors(PointF* pts, INT count)
  • Translate(offsetX, offsetY, order)


Matrix::Clone()

The Clone method creates a new Matrix object that is a copy of this Matrix object.

Matrix* Clone(void);

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new Matrix object.

Example Code [C++]

The following example creates a Matrix object that represents a horizontal scaling. The code creates a second matrix by calling the Clone method of the first matrix. Then the code calls the Translate method of the second matrix. At that point, the second matrix represents a composite transformation: first scale, then translate. The code passes the address of the first matrix to the SetTransform method of a Graphics object and then uses that Graphics object to draw a scaled rectangle. Then the code passes the address of the second matrix to the SetTransform method of the same Graphics object. Finally, the code calls the DrawRectangle method of the Graphics object a second time to draw a rectangle that is scaled and translated.

VOID Example_Clone(HDC hdc)
{
   Graphics myGraphics(hdc);

   Matrix matrix(3.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f);  // horizontal scaling
   Matrix* pMatrix = matrix.Clone();

   pMatrix->Translate(40.0f, 25.0f, MatrixOrderAppend);

   Pen myPen(Color(255, 0, 0, 255));
   myGraphics.SetTransform(&matrix);
   myGraphics.DrawRectangle(&myPen, 0, 0, 100, 100);  // scale
   myGraphics.SetTransform(pMatrix);
   myGraphics.DrawRectangle(&myPen, 0, 0, 100, 100);  // scale and translate

   delete pMatrix;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
Matrix Constructors
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::Equals(matrix)

The Equals method determines whether the elements of this matrix are equal to the elements of another matrix.

BOOL Equals(
  const Matrix* matrix
);

Parameters

matrix
[in] Pointer to a Matrix object that is compared with this Matrix object.

Return Values

If the elements of the two matrices are the same, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example compares two matrices to see whether they contain the same elements:

Matrix mat1(1.0f, 2.0f, 1.0f, 1.0f, 2.0f, 2.0f);
Matrix mat2(1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 2.0f);

if(mat1.Equals(&mat2))
   ;  // They are the same.
else
   ;  // They are different.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::GetElements()

The GetElements method gets the elements of this matrix. The elements are placed in an array in the order m11, m12, m21, m22, m31, m32, where mij denotes the element in row i, column j.

Status GetElements(
  REAL* m
) const;

Parameters

m
[out] Pointer to an array that receives the matrix elements. The size of the array should be 6×sizeof(REAL).

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
SetElements
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::GetLastStatus()

The GetLastStatus method returns a value that indicates the nature of this Matrix object's most recent method failure.

Status GetLastStatus(void);

Parameters

This method has no parameters.

Return Values

The GetLastSatus method returns an element of the Status enumeration.

If no methods invoked on this Matrix object have failed since the previous call to GetLastStatus, then GetLastStatus returns Ok.

If at least one method invoked on this Matrix object has failed since the previous call to GetLastStatus, then GetLastStatus returns a value that indicates the nature of the most recent failure.

Remarks

You can call GetLastStatus immediately after constructing a Matrix object to determine whether the constructor succeeded.

The first time you call the GetLastStatus method of a Matrix object, it returns Ok if the constructor succeeded and all methods invoked so far on the Matrix object succeeded. Otherwise, it returns a value that indicates the nature of the most recent failure.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
Status
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::Invert()

If this matrix is invertible, the Invert method replaces the elements of this matrix with the elements of its inverse.

Status Invert(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

If this matrix is not invertible, the method fails and returns InvalidParameter.

Example Code [C++]

The following example passes the address of a Matrix object to the SetTransform method of a Graphics object and then draws a rectangle. The rectangle is translated 30 units right and 20 units down by the world transformation of the Graphics object. The code calls the Invert method of the Matrix object and sets the world transformation of the Graphics object to the inverted matrix. The code draws a second rectangle that is translated 30 units left and 20 units up.

VOID Example_Invert(HDC hdc)
{
   Graphics myGraphics(hdc);
   Pen myPen(Color(255, 0, 0, 255));

   Matrix matrix(1.0f, 0.0f, 0.0f, 1.0f, 30.0f, 20.0f);

   myGraphics.SetTransform(&matrix);
   myGraphics.DrawRectangle(&myPen, 0, 0, 200, 100);
   matrix.Invert();
   myGraphics.SetTransform(&matrix);
   myGraphics.DrawRectangle(&myPen, 0, 0, 200, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
IsInvertible
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::IsIdentity()

The IsIdentity method determines whether this matrix is the identity matrix.

BOOL IsIdentity(void);

Parameters

This method has no parameters.

Return Values

If this matrix is the identity matrix, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a Matrix object and determines whether it is the identity matrix.

Matrix matrix(1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 2.0f);

if(matrix.IsIdentity())
   ;  // The matrix is the identity matrix.
else
   ;  // The matrix is not the identity matrix.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::IsInvertible()

The IsInvertible method determines whether this matrix is invertible.

BOOL IsInvertible(void);

Parameters

This method has no parameters.

Return Values

If this matrix is invertible, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a Matrix object and calls the IsInvertible method to determine whether the matrix is invertible. If the matrix is invertible, the code uses it to set the world transformation of a Graphics object.

VOID Example_IsInvertible(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   Matrix matrix(3.0f, 0.0f, 0.0f, 2.0f, 20.0f, 10.0f);

   if(matrix.IsInvertible())
      graphics.SetTransform(&matrix);

   graphics.DrawRectangle(&pen, 0, 0, 100, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
Invert
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::Multiply(matrix, order)

The Multiply method updates this matrix with the product of itself and another matrix.

Status Multiply(
  const Matrix* matrix,
  MatrixOrder order
);

Parameters

matrix
[in] Pointer to a matrix that will be multiplied by this matrix.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the passed matrix is on the left, and MatrixOrderAppend specifies that the passed matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates two Matrix objects: matrix1 and matrix2. The call to the Multiply method updates matrix1 with the product (matrix1)(matrix2). At that point, matrix1 represents a composite transformation: first scale, then translate. The code uses matrix1 to set the world transformation of a Graphics object and then draws a rectangle that is transformed according to that world transformation.

VOID Example_Multiply(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   Matrix matrix1(3.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f);    // horizontal scale
   Matrix matrix2(1.0f, 0.0f, 0.0f, 1.0f, 20.0f, 40.0f);  // translation

   matrix1.Multiply(&matrix2, MatrixOrderAppend);

   graphics.SetTransform(&matrix1);
   graphics.DrawRectangle(&pen, 0, 0, 100, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
MatrixOrder, Rotate, RotateAt, Scale, Shear, Translate
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::OffsetX()

The OffsetX method gets the horizontal translation value of this matrix, which is the element in row 3, column 1.

REAL OffsetX(void);

Parameters

This method has no parameters.

Return Values

This method returns the horizontal translation value of this matrix, which is the element in row 3, column 1.

Example Code [C++]

The following example creates a Matrix object with a horizontal translation value of 50 and a vertical translation value of 30. The code calls the OffsetX and OffsetY methods of the Matrix object to obtain those translation values. The code draws a line from (0, 0) to the point whose coordinates are the retrieved translation values. The code also uses the matrix to set the world transformation of a Graphics object and then draws a rectangle that is transformed according to that world transformation.

VOID Example_Offset(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   Matrix matrix(1.0f, 0.0f, 0.0f, 1.0f, 50.0f, 30.0f);
   REAL xTranslation = matrix.OffsetX();
   REAL yTranslation = matrix.OffsetY();

   graphics.DrawLine(&pen, 0.0f, 0.0f, xTranslation, yTranslation);
   graphics.SetTransform(&matrix);
   graphics.DrawRectangle(&pen, 0, 0, 20, 20);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
OffsetY, Translate
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::OffsetY()

The OffsetY method gets the vertical translation value of this matrix, which is the element in row 3, column 2.

REAL OffsetY(void);

Parameters

This method has no parameters.

Return Values

This method returns the vertical translation value of this matrix, which is the element in row 3, column 2.

Example Code [C++]

The following example creates a Matrix object with a horizontal translation value of 50 and a vertical translation value of 30. The code calls the OffsetX and OffsetY methods of the Matrix object to obtain those translation values. The code draws a line from (0, 0) to the point whose coordinates are the retrieved translation values. The code also uses the matrix to set the world transformation of a Graphics object and then draws a rectangle that is transformed according to that world transformation.

VOID Example_Offset(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   Matrix matrix(1.0f, 0.0f, 0.0f, 1.0f, 50.0f, 30.0f);
   REAL xTranslation = matrix.OffsetX();
   REAL yTranslation = matrix.OffsetY();

   graphics.DrawLine(&pen, 0.0f, 0.0f, xTranslation, yTranslation);
   graphics.SetTransform(&matrix);
   graphics.DrawRectangle(&pen, 0, 0, 20, 20);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
OffsetX, Translate
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::Reset()

The Reset method updates this matrix with the elements of the identity matrix.

Status Reset(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The elements on the main diagonal of the identity matrix are 1. All other elements of the identity matrix are 0.

Example Code [C++]

The following example creates a Matrix object that represents a horizontal scaling by a factor of 5 and a vertical scaling by a factor of 3. The code calls the Reset method to replace the elements of that matrix with the elements of the identity matrix. Then the code calls the Translate method to update the matrix with the product of itself (the identity) and a translation matrix. The result is that the matrix represents only the translation, not the scaling. The code uses the matrix to set the world transformation of a Graphics object and then draws a rectangle that is transformed according to that world transformation.

VOID Example_Reset(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   Matrix matrix(5.0f, 0.0f, 0.0f, 3.0f, 0.0f, 0.0f);
   matrix.Reset();
   matrix.Translate(50.0f, 40.0f);

   graphics.SetTransform(&matrix);
   graphics.DrawRectangle(&pen, 0, 0, 100, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
IsIdentity
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::Rotate(angle, order)

The Rotate method updates this matrix with the product of itself and a rotation matrix.

Status Rotate(
  REAL angle,
  MatrixOrder order
);

Parameters

angle
[in] Real number that specifies the angle of rotation in degrees. Positive values specify clockwise rotation.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the rotation matrix is on the left, and MatrixOrderAppend specifies that the rotation matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Matrix object and calls the Translate method to set the elements of that matrix to a translation. Then the code calls the Rotate method to update the matrix with the product of itself and a rotation matrix. At that point, the matrix represents a composite transformation: first translate, then rotate. The code uses the matrix to set the world transformation of a Graphics object and then draws an ellipse that is transformed according to the composite transformation.

VOID Example_Rotate(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   Matrix matrix;
   matrix.Translate(40.0f, 0.0f);            // first a translation
   matrix.Rotate(30.0f, MatrixOrderAppend);  // then a rotation

   graphics.SetTransform(&matrix);
   graphics.DrawEllipse(&pen, 0, 0, 100, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
MatrixOrder, Multiply, RotateAt, Scale, Shear, Translate
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::RotateAt(angle, center, order)

The RotateAt method updates this matrix with the product of itself and a matrix that represents rotation about a specified point.

Status RotateAt(
  REAL angle,
  const PointF& center,
  MatrixOrder order
);

Parameters

angle
[in] Real number that specifies the angle of rotation in degrees. Positive values specify clockwise rotation.
center
[in] Reference to a PointF object that specifies the center of the rotation. This is the point about which the rotation takes place.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the rotation matrix is on the left, and MatrixOrderAppend specifies that the rotation matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Matrix object and calls the Translate method to set the elements of that matrix to a translation (150 right, 100 down). Then the code calls the RotateAt method to update the matrix with the product of itself and a matrix that represents a 30-degree rotation about the point (150, 100). The matrix then represents a composite transformation: first translate (150 right, 100 down), then rotate about the point (150, 100). The code uses the matrix to set the world transformation of a Graphics object and then draws an ellipse that is transformed according to the composite transformation.

VOID Example_RotateAt(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   Matrix matrix;
   matrix.Translate(150.0f, 100.0f);
   matrix.RotateAt(30.0f, PointF(150.0f, 100.0f), MatrixOrderAppend);

   graphics.SetTransform(&matrix);

   // Draw a tramsformed ellipse. The composite transformation
   // is translate right 150, translate down 100, and then
   // rotate 30 degrees about the point (150, 100).
   graphics.DrawEllipse(&pen, -40, -20, 80, 40);

   // Draw rotated axes with the origin at the center of the ellipse.
   graphics.DrawLine(&pen, -50, 0, 50, 0);
   graphics.DrawLine(&pen, 0, -50, 0, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
MatrixOrder, Multiply, Rotate, Scale, Shear, Translate
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::Scale(scaleX, scaleY, order)

The Scale method updates this matrix with the product of itself and a scaling matrix.

Status Scale(
  REAL scaleX,
  REAL scaleY,
  MatrixOrder order
);

Parameters

scaleX
[in] Real number that specifies the horizontal scale factor.
scaleY
[in] Real number that specifies the vertical scale factor.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the scaling matrix is on the left, and MatrixOrderAppend specifies that the scaling matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Matrix object and calls the Rotate method to set the elements of that matrix to a rotation. Then the code calls the Scale method to update the matrix with the product of itself and a scaling matrix. At that point, the matrix represents a composite transformation: first rotate, then scale. The code uses the matrix to set the world transformation of a Graphics object and then draws an ellipse that is transformed according to the composite transformation.

VOID Example_Scale(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   Matrix matrix;
   matrix.Rotate(30.0f);
   matrix.Scale(3.0f, 2.0f, MatrixOrderAppend);

   graphics.SetTransform(&matrix);

   // Draw a tramsformed ellipse. The composite transformation
   // is rotate 30 degrees and then scale by a factor of 3
   // in the horizontal direction and 2 in the vertical direction.
   graphics.DrawEllipse(&pen, 0, 0, 80, 40);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
MatrixOrder, Multiply, Rotate, RotateAt, Shear, Translate
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::SetElements(m11, m12, m21, m22, dx, dy)

The SetElements method sets the elements of this matrix.

Status SetElements(
  REAL m11,
  REAL m12,
  REAL m21,
  REAL m22,
  REAL dx,
  REAL dy
);

Parameters

m11
[in] Real number that specifies the element in the first row, first column.
m12
[in] Real number that specifies the element in the first row, second column.
m21
[in] Real number that specifies the element in the second row, first column.
m22
[in] Real number that specifies the element in the second row, second column.
dx
[in] Real number that specifies the element in the third row, first column.
dy
[in] Real number that specifies the element in the third row, second column.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example calls the SetElements method of a Matrix object. The code uses the matrix to set the world transformation of a Graphics object and then draws a rectangle that is transformed by that world transformation.

VOID Example_SetElements(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   Matrix matrix;
   matrix.SetElements(1.0f, 0.0f, 0.0f, 1.0f, 30.0f, 50.0f);

   graphics.SetTransform(&matrix);
   graphics.DrawRectangle(&pen, 0, 0, 80, 40);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
GetElements
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::Shear(shearX, shearY, order)

The Shear method updates this matrix with the product of itself and a shearing matrix.

Status Shear(
  REAL shearX,
  REAL shearY,
  MatrixOrder order
);

Parameters

shearX
[in] Real number that specifies the horizontal shear factor.
shearY
[in] Real number that specifies the vertical shear factor.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the shearing matrix is on the left, and MatrixOrderAppend specifies that the shearing matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Matrix object and calls the Scale method to set the elements of that matrix to a scaling transformation. Then the code calls the Shear method to update the matrix with the product of itself and a shearing matrix. At that point, the matrix represents a composite transformation: first scale, then shear. The code uses the matrix to set the world transformation of a Graphics object and then draws a rectangle that is transformed according to the composite transformation.

In the call to Shear, the shearX parameter is 3 and the shearY parameter is 0. That particular shearing transformation slides the bottom edge of the rectangle to the right. The distance that the bottom edge slides is shearX multiplied by the height of the rectangle after it is stretched by the scaling transformation.

VOID Example_Shear(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   Matrix matrix;
   matrix.Scale(2.0f, 2.0f);                     // first a scaling
   matrix.Shear(3.0f, 0.0f, MatrixOrderAppend);  // then a shear

   graphics.SetTransform(&matrix);
   graphics.DrawRectangle(&pen, 0, 0, 100, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
MatrixOrder, Multiply, Rotate, RotateAt, Scale, Translate
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::TransformPoints Methods

This topic lists the TransformPoints methods of the Matrix class. For a complete list of methods for the Matrix class, see Matrix Methods.

  • TransformPoints(Point* pts, INT count)
  • TransformPoints(PointF* pts, INT count)


Matrix::TransformPoints(Point* pts, INT count)

The TransformPoints method multiplies each point in an array by this matrix. Each point is treated as a row matrix. The multiplication is performed with the row matrix on the left and this matrix on the right.

Status TransformPoints(
  Point* pts,
  INT count
);

Parameters

pts
[in, out] Pointer to an array of Point objects that, on input, contains the points to be transformed and, on output, receives the transformed points. Each point in the array is transformed (multiplied by this matrix) and updated with the result of the transformation.
count
[in] Optional. Integer that specifies the number of points to be transformed. The default value is 1.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates an array of five points and then transforms those points by calling the TransformPoints method of a Matrix object. The code passes the array of points to the Graphics::DrawCurve method before the transformation and again after the transformation.

VOID Example_TransPoints(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   Point points[5] = {
      Point(50, 100),
      Point(100, 50),
      Point(150, 125),
      Point(200, 100),
      Point(250, 150)};

   Matrix matrix(1.0f, 0.0f, 0.0f, 2.0f, 0.0f, 0.0f);

   graphics.DrawCurve(&pen, points, 5);
   matrix.TransformPoints(points, 5);
   graphics.DrawCurve(&pen, points, 5);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
Point, TransformPoints Methods, TransformVectors Methods
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::TransformPoints(PointF* pts, INT count)

The TransformPoints method multiplies each point in an array by this matrix. Each point is treated as a row matrix. The multiplication is performed with the row matrix on the left and this matrix on the right.

Status TransformPoints(
  PointF* pts,
  INT count
);

Parameters

pts
[in, out] Pointer to an array of PointF objects that, on input, contains the points to be transformed and, on output, receives the transformed points. Each point in the array is transformed (multiplied by this matrix) and updated with the result of the transformation.
count
[in] Optional. Integer that specifies the number of points to be transformed. The default value is 1.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates an array of five points and then transforms those points by calling the TransformPoints method of a Matrix object. The code passes the array of points to the Graphics::DrawCurve method before the transformation and again after the transformation.

VOID Example_TransPointsF(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   PointF points[5] = {
      PointF(50.0f, 100.0f),
      PointF(100.0f, 50.0f),
      PointF(150.0f, 125.0f),
      PointF(200.0f, 100.0f),
      PointF(250.0f, 150.0f)};

   Matrix matrix(1.0f, 0.0f, 0.0f, 2.0f, 0.0f, 0.0f);

   graphics.DrawCurve(&pen, points, 5);
   matrix.TransformPoints(points, 5);
   graphics.DrawCurve(&pen, points, 5);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
PointF, TransformPoints Methods, TransformVectors Methods
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::TransformVectors Methods

This topic lists the TransformVectors methods of the Matrix class. For a complete list of methods for the Matrix class, see Matrix Methods.

  • TransformVectors(Point* pts, INT count)
  • TransformVectors(PointF* pts, INT count)


Matrix::TransformVectors(Point* pts, INT count)

The TransformVectors method multiplies each vector in an array by this matrix. The translation elements of this matrix (third row) are ignored. Each vector is treated as a row matrix. The multiplication is performed with the row matrix on the left and this matrix on the right.

Status TransformVectors(
  Point* pts,
  INT count
);

Parameters

pts
[in, out] Pointer to an array of Point objects that, on input, contains the vectors to be transformed and, on output, receives the transformed vectors. Each vector in the array is transformed (multiplied by this matrix) and updated with the result of the transformation.
count
[in] Optional. Integer that specifies the number of vectors to be transformed. The default value is 1.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

While a point represents position, a vector represents an entity (for example, velocity or acceleration) that has a direction and a magnitude. Thus, the endpoints of a line segment are points, but their difference is a vector—the length and direction of that line segment.

Vectors are similar to points in many ways. Like points, they are represented by x- and y-coordinates, so GDI+ uses the same classes (Point and PointF) to represent vectors as it uses to represent points. The subtle difference between vectors and points is the way they are affected by transformations. In the physical world, moving the origin of the coordinate system changes the coordinates of all position points, but it will not alter any velocity vectors. Vectors can be scaled, rotated, sheared or flipped, but not translated (moved). Thus, when an affine transformation is applied to a vector, the translation component (the last row of the matrix) is ignored.

Example Code [C++]

The following example creates a vector and a point. The tip of the vector and the point are at the same location: (100, 50). The code creates a Matrix object and initializes its elements so that it represents a clockwise rotation followed by a translation 100 units to the right. The code calls the TransformPoints method of the matrix to transform the point and calls the TransformVectors method of the matrix to transform the vector. The entire transformation (rotation followed by translation) is performed on the point, but only the rotation part of the transformation is performed on the vector. The elements of the matrix that represent translation are ignored by the TransformVectors method.

VOID Example_TransVectors(HDC hdc)
{
   Graphics graphics(hdc);

   Pen pen(Color(255, 0, 0, 255), 7);
   pen.SetEndCap(LineCapArrowAnchor);
   SolidBrush brush(Color(255, 0, 0, 255));

   // A point and a vector, same representation but different behavior
   Point point(100, 50);
   Point vector(100, 50);

   // Draw the original point and vector in blue.
   graphics.FillEllipse(&brush, point.X - 5, point.Y - 5, 10, 10);

   graphics.DrawLine(&pen, Point(0, 0), vector);

   // Transform.
   Matrix matrix(0.8f, 0.6f, -0.6f, 0.8f, 100.0f, 0.0f);
   matrix.TransformPoints(&point);
   matrix.TransformVectors(&vector);

   // Draw the transformed point and vector in red.
   pen.SetColor(Color(255, 255, 0, 0));
   brush.SetColor(Color(255, 255, 0, 0));
   graphics.FillEllipse(&brush, point.X - 5, point.Y - 5, 10, 10);
   graphics.DrawLine(&pen, Point(0, 0), vector);
}

The following illustration shows the output of the preceding code. Note that the transformed point lies 100 pixels to the right of the tip of the transformed vector.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
Point, TransformPoints Methods, TransformVectors Methods
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::TransformVectors(PointF* pts, INT count)

The TransformVectors method multiplies each vector in an array by this matrix. The translation elements of this matrix (third row) are ignored. Each vector is treated as a row matrix. The multiplication is performed with the row matrix on the left and this matrix on the right.

Status TransformVectors(
  PointF* pts,
  INT count
);

Parameters

pts
[in, out] Pointer to an array of PointF objects that, on input, contains the vectors to be transformed and, on output, receives the transformed vectors. Each vector in the array is transformed (multiplied by this matrix) and updated with the result of the transformation.
count
[in] Optional. Integer that specifies the number of points to be transformed. The default value is 1.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

While a point represents position, a vector represents an entity (for example, velocity or acceleration) that has a direction and a magnitude. Thus, the endpoints of a line segment are points, but their difference is a vector—the length and direction of that line segment.

Vectors are similar to points in many ways. Like points, they are represented by x- and y-coordinates, so GDI+ uses the same classes (Point and PointF) to represent vectors as it uses to represent points. The subtle difference between vectors and points is the way they are affected by transformations. In the physical world, moving the origin of the coordinate system changes the coordinates of all position points, but it will not alter any velocity vectors. Vectors can be scaled, rotated, sheared or flipped, but not translated (moved). Thus, when an affine transformation is applied to a vector, the translation component (the last row of the matrix) is ignored.

Example Code [C++]

The following example creates a vector and a point. The tip of the vector and the point are at the same location: (100, 50). The code creates a Matrix object and initializes its elements so that it represents a clockwise rotation followed by a translation 100 units to the right. The code calls the TransformPoints method of the matrix to transform the point and calls the TransformVectors method of the matrix to transform the vector. The entire transformation (rotation followed by translation) is performed on the point, but only the rotation part of the transformation is performed on the vector. The elements of the matrix that represent translation are ignored by the TransformVectors method.

VOID Example_TransVectorsF(HDC hdc)
{
   Graphics graphics(hdc);

   Pen pen(Color(255, 0, 0, 255), 7);
   pen.SetEndCap(LineCapArrowAnchor);
   SolidBrush brush(Color(255, 0, 0, 255));

   // A point and a vector, same representation but different behavior
   PointF point(100.0f, 50.0f);
   PointF vector(100.0f, 50.0f);

   // Draw the original point and vector in blue.
   graphics.FillEllipse(&brush, point.X - 5.0f, point.Y - 5.0f, 10.0f, 10.0f);

   graphics.DrawLine(&pen, PointF(0.0f, 0.0f), vector);

   // Transform.
   Matrix matrix(0.8f, 0.6f, -0.6f, 0.8f, 100.0f, 0.0f);
   matrix.TransformPoints(&point);
   matrix.TransformVectors(&vector);

   // Draw the transformed point and vector in red.
   pen.SetColor(Color(255, 255, 0, 0));
   brush.SetColor(Color(255, 255, 0, 0));
   graphics.FillEllipse(&brush, point.X - 5.0f, point.Y - 5.0f, 10.0f, 10.0f);
   graphics.DrawLine(&pen, PointF(0.0f, 0.0f), vector);
}

The following illustration shows the output of the preceding code. Note that the transformed point lies 100 pixels to the right of the tip of the transformed vector.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
PointF, TransformPoints Methods, TransformVectors Methods
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Matrix::Translate(offsetX, offsetY, order)

The Translate method updates this matrix with the product of itself and a translation matrix.

Status Translate(
  REAL offsetX,
  REAL offsetY,
  MatrixOrder order
);

Parameters

offsetX
[in] Real number that specifies the horizontal component of the translation.
offsetY
[in] Real number that specifies the vertical component of the translation.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the translation matrix is on the left, and MatrixOrderAppend specifies that the translation matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Matrix object and calls the Rotate method to set the elements of that matrix to a rotation. Then the code calls the Translate method to update the matrix with the product of itself and a translation matrix. At that point, the matrix represents a composite transformation: first rotate, then translate. The code uses the matrix to set the world transformation of a Graphics object and then draws an ellipse that is transformed according to the composite transformation.

VOID Example_Translate(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 255));

   Matrix matrix;
   matrix.Rotate(30.0f);                                 // first a rotation
   matrix.Translate(150.0f, 100.0f, MatrixOrderAppend);  // then a translation

   graphics.SetTransform(&matrix);

   // Draw a tramsformed ellipse. The composite transformation
   // is rotate 30 degrees, then translate 150 right and 100 down.
   graphics.DrawEllipse(&pen, -40, -20, 80, 40);

   // Draw rotated axes with the origin at the center of the ellipse.
   graphics.DrawLine(&pen, -50, 0, 50, 0);
   graphics.DrawLine(&pen, 0, -50, 0, 50);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmatrix.h; include Gdiplus.h.

See Also

Reference
MatrixOrder, Multiply, Rotate, RotateAt, Scale, Shear
Tasks and Examples
Transformations
Concepts
Global and Local Transformations, Matrix Representation of Transformations


Metafile Class

The Metafile class defines a graphic metafile. A metafile contains records that describe a sequence of graphics API calls. Metafiles can be recorded (constructed) and played back (displayed).

Inheritance

GdiplusBase
Image
Metafile

Constructors

Constructor | Description
Metafile | Overloaded. Initializes a new instance of the Metafile class.

Methods

Uninherited

Method | Description
GetHENHMETAFILE | Gets a Windows handle to an EMF file.
GetMetafileHeader | Overloaded. Gets the header file.
PlayRecord | Plays a metafile record.

Inherited from Image

Method | Description
Clone | Creates a new Image object and initializes it with the contents of this Image object.
FromFile | Creates an Image object based on a file.
FromStream | Creates an Image object based on a stream.
GetAllPropertyItems | Gets all the property items (pieces of metadata) stored in this Image object.
GetBounds | Gets a rectangle that indicates the size of the image.
GetEncoderParameterList | Gets the list of parameters supported by a specified codec.
GetEncoderParameterListSize | Gets the size (in bytes) of the list of parameters supported by a specified codec.
GetFlags | Gets a set of flags that indicate certain attributes of this Image object.
GetFrameCount | Gets the number of frames in a specified dimension of this Image object.
GetFrameDimensionsCount | Gets the number of frame dimensions in this Image object.
GetFrameDimensionsList | Gets the frame dimension IDs of this Image object.
GetHeight | Gets the height, in pixels, of this image.
GetHorizontalResolution | Gets the horizontal resolution, in dots per inch, of this image.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetPalette | Gets the color palette of this Image object.
GetPaletteSize | Gets the size, in bytes, of the color palette of this Image object.
GetPhysicalDimension | Gets the width and height of this image.
GetPixelFormat | Gets the pixel format of this image.
GetPropertyCount | Gets the number of property items (pieces of metadata) stored in this Image object.
GetPropertyIdList | Gets a list of the property IDs stored in this Image object.
GetPropertyItem | Gets a specified property item (piece of metadata) from this Image object.
GetPropertyItemSize | Gets the size (in bytes) of a specified property item (piece of metadata) stored in this Image object.
GetPropertySize | Gets the total size, in bytes, of the property items stored in this Image object. Also gets the number of property items.
GetRawFormat | Gets a GUID that identifies the format of this Image object.
GetThumbnailImage | Gets a thumbnail image from this Image object.
GetType | Gets the image type (bitmap or metafile).
GetVerticalResolution | Gets the vertical resolution, in dots per inch, of this image.
GetWidth | Gets the width, in pixels, of this image.
RemovePropertyItem | Removes a property item (piece of metadata) from this Image object.
RotateFlip | Rotates this image.
Save | Overloaded. Saves this image to a file or to a stream.
SaveAdd | Overloaded. Adds a frame to this Image object.
SelectActiveFrame | Selects a specified frame of this Image object.
SetPalette | Sets the color palette of this Image object.
SetPropertyItem | Sets a specified property item (piece of metadata) of this Image object.

Remarks

Some Metafile constructors (those that receive a device context handle) create Metafile objects that are used to record metafiles. Other Metafile constructors (those that do not receive a device context handle) create Metafile objects that are used to display (play back) metafiles.


Metafile Constructors

This topic lists the constructors of the Metafile class. For a complete class listing, see Metafile Class.

  • Metafile(filename)
  • Metafile(WCHAR* fileName, HDC referenceHdc, Rect& frameRect, MetafileFrameUnit frameUnit, EmfType type, WCHAR* description)
  • Metafile(WCHAR* fileName, HDC referenceHdc, RectF& frameRect, MetafileFrameUnit frameUnit, EmfType type, WCHAR* description)
  • Metafile(fileName, referenceHdc, type, description)
  • Metafile(hEmf, deleteEmf)
  • Metafile(HDC referenceHdc, Rect& frameRect, MetafileFrameUnit frameUnit, EmfType type, WCHAR* description)
  • Metafile(HDC referenceHdc, RectF& frameRect, MetafileFrameUnit frameUnit, EmfType type, WCHAR* description)
  • Metafile(hWmf, wmfPlaceableFileHeader, deleteWmf)
  • Metafile(referenceHdc, type, description)
  • Metafile(stream)
  • Metafile(IStream* stream, HDC referenceHdc, Rect& frameRect, MetafileFrameUnit frameUnit, EmfType type, WCHAR* description)
  • Metafile(IStream* stream, HDC referenceHdc, RectF& frameRect, MetafileFrameUnit frameUnit, EmfType type, WCHAR* description)
  • Metafile(stream, referenceHdc, type, description)


Metafile::Metafile(filename)

Creates a Metafile object for playback.

Metafile(
  const WCHAR* filename
);

Parameters

filename
[in] Pointer to a wide-character string that specifies the name of an existing disk file used to create the Metafile object for playback.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
Metafile Constructors
Tasks and Examples
Loading and Displaying Metafiles, Recording Metafiles
Concepts
Metafiles


Metafile::Metafile(WCHAR* fileName, HDC referenceHdc, Rect& frameRect, MetafileFrameUnit frameUnit, EmfType type, WCHAR* description)

Creates a Metafile object for recording.

Metafile(
  const WCHAR* fileName,
  HDC referenceHdc,
  const Rect& frameRect,
  MetafileFrameUnit frameUnit,
  EmfType type,
  const WCHAR* description
);

Parameters

fileName
[in] Pointer to a wide-character string that specifies the name of the file in which the metafile will be saved.
referenceHdc
[in] Handle to a device context that contains attributes of a display device.
frameRect
[in] Reference to a rectangle that bounds the metafile display.
frameUnit
[in] Optional. Element of the MetafileFrameUnit enumeration that specifies the unit of measure for frameRect. The default value is MetafileFrameUnitGdi.
type
[in] Optional. Element of the EmfType enumeration that specifies the type of metafile that will be recorded. The default value is EmfTypeEmfPlusDual.
description
[in] Optional. Pointer to a wide-character string that specifies the descriptive name of the metafile. The default value is NULL.

Remarks

When recording to a file, the file must be writable, and GDI+ must be able to obtain an exclusive lock on the file.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
EmfType, MetafileFrameUnit, Rect
Tasks and Examples
Loading and Displaying Metafiles, Recording Metafiles
Concepts
Metafiles


Metafile::Metafile(WCHAR* fileName, HDC referenceHdc, RectF& frameRect, MetafileFrameUnit frameUnit, EmfType type, WCHAR* description)

Creates a Metafile object for recording.

Metafile(
  const WCHAR* fileName,
  HDC referenceHdc,
  const RectF& frameRect,
  MetafileFrameUnit frameUnit,
  EmfType type,
  const WCHAR* description
);

Parameters

fileName
[in] Pointer to a wide-character string that specifies the name of the file in which the metafile will be saved.
referenceHdc
[in] Windows handle to a device context that contains attributes of a display device.
frameRect
[in] Reference to a rectangle that bounds the metafile display.
frameUnit
[in] Optional. Element of the MetafileFrameUnit enumeration that specifies the unit of measure for frameRect. The default value is MetafileFrameUnitGdi.
type
[in] Optional. Element of the EmfType enumeration that specifies the type of metafile that will be recorded. The default value is EmfTypeEmfPlusDual.
description
[in] Optional. Pointer to a wide-character string that specifies the descriptive name of the metafile. The default value is NULL.

Remarks

When recording to a file, the file must be writable, and GDI+ must be able to obtain an exclusive lock on the file.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
EmfType, MetafileFrameUnit, RectF
Tasks and Examples
Loading and Displaying Metafiles, Recording Metafiles
Concepts
Metafiles


Metafile::Metafile(fileName, referenceHdc, type, description)

Creates a Metafile object for recording.

Metafile(
  const WCHAR* fileName,
  HDC referenceHdc,
  EmfType type,
  const WCHAR* description
);

Parameters

fileName
[in] Pointer to a wide-character string that specifies the name of the file in which the metafile will be saved.
referenceHdc
[in] Windows handle to a device context that contains attributes of a display device.
type
[in] Optional. Element of the EmfType enumeration that specifies the type of metafile that will be recorded. The default value is EmfTypeEmfPlusDual.
description
[in] Optional. Pointer to a wide-character string that specifies the descriptive name of the metafile. The default value is NULL.

Remarks

When recording to a file, the file must be writable, and GDI+ must be able to obtain an exclusive lock on the file.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
EmfType, MetafileFrameUnit
Tasks and Examples
Loading and Displaying Metafiles, Recording Metafiles
Concepts
Metafiles


Metafile::Metafile(hEmf, deleteEmf)

Creates a GDI+ Metafile object for playback based on a GDI Enhanced Metafile (EMF) file.

Metafile(
  HENHMETAFILE hEmf,
  BOOL deleteEmf
);

Parameters

hEmf
[in] Windows handle to a metafile.
deleteEmf
[in] Optional. Boolean value that specifies whether the Windows handle to a metafile is deleted when the Metafile object is deleted. TRUE specifies that the hEmf Windows handle is deleted, and FALSE specifies that the hEmf Windows handle is not deleted. The default value is FALSE.

Remarks

This constructor allows GDI+ to own the windows handle to the metafile, which should not be used by other portions of your code until the Metafile object is deleted or goes out of scope.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
GetHENHMETAFILE
Tasks and Examples
Loading and Displaying Metafiles, Recording Metafiles
Concepts
Metafiles


Metafile::Metafile(HDC referenceHdc, Rect& frameRect, MetafileFrameUnit frameUnit, EmfType type, WCHAR* description)

Creates a Metafile object for recording.

Metafile(
  HDC referenceHdc,
  const Rect& frameRect,
  MetafileFrameUnit frameUnit,
  EmfType type,
  const WCHAR* description
);

Parameters

referenceHdc
[in] Windows handle to a device context that contains attributes of the display device that is used to record the metafile.
frameRect
[in] Reference to a rectangle that bounds the metafile display.
frameUnit
[in] Optional. Element of the MetafileFrameUnit enumeration that specifies the unit of measure for frameRect. The default value is MetafileFrameUnitGdi.
type
[in] Optional. Element of the EmfType enumeration that specifies the type of metafile that will be recorded. The default value is EmfTypeEmfPlusDual.
description
[in] Optional. Pointer to a wide-character string that specifies the descriptive name of the metafile. The default value is NULL.

Remarks

When recording to a file, the file must be writable, and GDI+ must be able to obtain an exclusive lock on the file.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
EmfType, MetafileFrameUnit, Rect
Tasks and Examples
Loading and Displaying Metafiles, Recording Metafiles
Concepts
Metafiles


Metafile::Metafile(HDC referenceHdc, RectF& frameRect, MetafileFrameUnit frameUnit, EmfType type, WCHAR* description)

Creates a Metafile object for recording.

Metafile(
  HDC referenceHdc,
  const RectF& frameRect,
  MetafileFrameUnit frameUnit,
  EmfType type,
  const WCHAR* description
);

Parameters

referenceHdc
[in] Windows handle to a device context that contains attributes of the display device that is used to record the metafile.
frameRect
[in] Reference to a rectangle that bounds the metafile display.
frameUnit
[in] Optional. Element of the MetafileFrameUnit enumeration that specifies the unit of measure for frameRect. The default value is MetafileFrameUnitGdi.
type
[in] Optional. Element of the EmfType enumeration that specifies the type of metafile that will be recorded. The default value is EmfTypeEmfPlusDual.
description
[in] Optional. Pointer to a wide-character string that specifies the descriptive name of the metafile. The default value is NULL.

Remarks

When recording to a file, the file must be writable, and GDI+ must be able to obtain an exclusive lock on the file.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
EmfType, MetafileFrameUnit, RectF
Tasks and Examples
Loading and Displaying Metafiles, Recording Metafiles
Concepts
Metafiles


Metafile::Metafile(hWmf, wmfPlaceableFileHeader, deleteWmf)

Creates a GDI+ Metafile object for recording. The format will be placeable metafile.

Metafile(
  HMETAFILE hWmf,
  const WmfPlaceableFileHeader* wmfPlaceableFileHeader,
  BOOL deleteWmf
);

Parameters

hWmf
[in] Windows handle to a metafile.
wmfPlaceableFileHeader
[in] Pointer to a WmfPlaceableFileHeader structure that specifies a preheader preceding the metafile header.
deleteWmf
[in] Optional. Boolean value that specifies whether the Windows handle to a metafile is deleted when the metafile is deleted. TRUE specifies that the hWmf Windows handle is deleted, and FALSE specifies that the hWmf Windows handle is not deleted. The default value is FALSE.

Remarks

Placeable metafiles are WMF files that contain a preheader preceding the metafile header. The preheader contains additional information for the metafile header of the metafile.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
WmfPlaceableFileHeader, PWMFRect16


Metafile::Metafile(referenceHdc, type, description)

Creates a Metafile object for recording.

Metafile(
  HDC referenceHdc,
  EmfType type,
  const WCHAR* description
);

Parameters

referenceHdc
[in] Windows handle to a device context that contains attributes of the display device that is used to record the metafile.
type
[in] Optional. Element of the EmfType enumeration that specifies the type of metafile that will be recorded. The default value is EmfTypeEmfPlusDual.
description
[in] Optional. Pointer to a wide-character string that specifies the descriptive name of the metafile. The default value is NULL.

Remarks

When recording to a file, the file must be writable, and GDI+ must be able to obtain an exclusive lock on the file.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
EmfType
Tasks and Examples
Loading and Displaying Metafiles, Recording Metafiles
Concepts
Metafiles


Metafile::Metafile(stream)

Creates a Metafile object from an IStream interface for playback.

Metafile(
  IStream* stream
);

Parameters

stream
[in] Pointer to a COM IStream interface that points to a data stream in a file.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
IStream
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


Metafile::Metafile(IStream* stream, HDC referenceHdc, Rect& frameRect, MetafileFrameUnit frameUnit, EmfType type, WCHAR* description)

Creates a Metafile object for recording to an IStream interface.

Metafile(
  IStream* stream,
  HDC referenceHdc,
  const Rect& frameRect,
  MetafileFrameUnit frameUnit,
  EmfType type,
  const WCHAR* description
);

Parameters

stream
[in] Pointer to a COM IStream interface that points to a stream of data in a file. When the commands are recorded, they will be saved to this stream.
referenceHdc
[in] Windows handle to a device context that contains attributes of the display device that is used to record the metafile.
frameRect
[in] Reference to a rectangle that bounds the metafile display.
frameUnit
[in] Optional. Element of the MetafileFrameUnit enumeration that specifies the unit of measure for frameRect. The default value is MetafileFrameUnitGdi.
type
[in] Optional. Element of the EmfType enumeration that specifies the type of metafile that will be recorded. The default value is EmfTypeEmfPlusDual.
description
[in] Optional. Pointer to a wide-character string that specifies the descriptive name of the metafile. The default value is NULL.

Remarks

When recording to a file, the file must be writable, and GDI+ must be able to obtain an exclusive lock on the file.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
EmfType, IStream, MetafileFrameUnit, Rect
Tasks and Examples
Loading and Displaying Metafiles, Recording Metafiles
Concepts
Metafiles


Metafile::Metafile(IStream* stream, HDC referenceHdc, RectF& frameRect, MetafileFrameUnit frameUnit, EmfType type, WCHAR* description)

Creates a Metafile object for recording to an IStream interface.

Metafile(
  IStream* stream,
  HDC referenceHdc,
  const RectF& frameRect,
  MetafileFrameUnit frameUnit,
  EmfType type,
  const WCHAR* description
);

Parameters

stream
[in] Pointer to a COM IStream interface that points to a stream of data in a file. When the commands are recorded, they will be saved to this stream.
referenceHdc
[in] Windows handle to a device context that contains attributes of the display device that is used to record the metafile.
frameRect
[in] Reference to a rectangle that bounds the metafile display.
frameUnit
[in] Optional. Element of the MetafileFrameUnit enumeration that specifies the unit of measure for frameRect. The default value is MetafileFrameUnitGdi.
type
[in] Optional. Element of the EmfType enumeration that specifies the type of metafile that will be recorded. The default value is EmfTypeEmfPlusDual.
description
[in] Optional. Pointer to a wide-character string that specifies the descriptive name of the metafile. The default value is NULL.

Remarks

When recording to a file, the file must be writable, and GDI+ must be able to obtain an exclusive lock on the file.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
EmfType, IStream, MetafileFrameUnit, RectF
Tasks and Examples
Loading and Displaying Metafiles, Recording Metafiles
Concepts
Metafiles


Metafile::Metafile(stream, referenceHdc, type, description)

Creates a Metafile object for recording to an IStream interface.

Metafile(
  IStream* stream,
  HDC referenceHdc,
  EmfType type,
  const WCHAR* description
);

Parameters

stream
[in] Pointer to a COM IStream interface that points to a stream of data in a file. When the commands are recorded, they will be saved to this stream.
referenceHdc
[in] Windows handle to a device context that contains attributes of the display device that is used to record the meatfile.
type
[in] Optional. Element of the EmfType enumeration that specifies the type of metafile that will be recorded. The default value is EmfTypeEmfPlusDual.
description
[in] Optional. Pointer to a wide-character string that specifies the descriptive name of the metafile. The default value is NULL.

Remarks

When recording to a file, the file must be writable, and GDI+ must be able to obtain an exclusive lock on the file.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
EmfType, IStream
Tasks and Examples
Loading and Displaying Metafiles, Recording Metafiles
Concepts
Metafiles


Metafile Methods

This topic lists the methods of the Metafile class. For a complete class listing, see Metafile Class.

  • Clone()
  • FromFile(filename, useEmbeddedColorManagement)
  • FromStream(stream, useEmbeddedColorManagement)
  • GetAllPropertyItems(totalBufferSize, numProperties, allItems)
  • GetBounds(srcRect, srcUnit)
  • GetEncoderParameterList(clsidEncoder, size, buffer)
  • GetEncoderParameterListSize(clsidEncoder)
  • GetFlags()
  • GetFrameCount(dimensionID)
  • GetFrameDimensionsCount()
  • GetFrameDimensionsList(dimensionIDs, count)
  • GetHeight()
  • GetHENHMETAFILE()
  • GetHorizontalResolution()
  • GetLastStatus()
  • GetMetafileHeader(filename, header)
  • GetMetafileHeader(header)
  • GetMetafileHeader(hEmf, header)
  • GetMetafileHeader(hWmf, wmfPlaceableFileHeader, header)
  • GetMetafileHeader(stream, header)
  • GetPalette(palette, size)
  • GetPaletteSize()
  • GetPhysicalDimension(size)
  • GetPixelFormat()
  • GetPropertyCount()
  • GetPropertyIdList(numOfProperty, list)
  • GetPropertyItem(propId, propSize, buffer)
  • GetPropertyItemSize(propId)
  • GetPropertySize(totalBufferSize, numProperties)
  • GetRawFormat(format)
  • GetThumbnailImage(thumbWidth, thumbHeight, callback, callbackData)
  • GetType()
  • GetVerticalResolution()
  • GetWidth()
  • PlayRecord(recordType, flags, dataSize, data)
  • RemovePropertyItem(propId)
  • RotateFlip(rotateFlipType)
  • SelectActiveFrame(dimensionID, frameIndex)
  • SetPalette(palette)
  • SetPropertyItem(item)


Metafile::GetHENHMETAFILE()

The GetHENHMETAFILE method gets a Windows handle to an Enhanced Metafile (EMF) file.

HENHMETAFILE GetHENHMETAFILE(void);

Parameters

This method has no parameters.

Return Values

This method returns a HENHMETAFILE.

Remarks

This method sets the Metafile object to an invalid state. The user is responsible for calling DeleteEnhMetafile, to delete the Windows handle.

Example Code [C++]

The following example creates a Metafile object from an EMF+ file and gets a Windows handle to the metafile.

VOID Example_GetHENHMETAFILE(HDC hdc)
{

   // Create a GDI+ Metafile object from an existing disk file.
   Metafile metafile(L"SampleMetafile.emf+");

   // Get a Windows handle to the metafile.
   HENHMETAFILE hEmf = metafile.GetHENHMETAFILE();

}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
ENHMETAHEADER3, Marshaling OLE Data Types


Metafile::GetMetafileHeader Methods

This topic lists the GetMetafileHeader methods of the Metafile class. For a complete list of methods for the Metafile class, see Metafile Methods.

  • GetMetafileHeader(filename, header)
  • GetMetafileHeader(header)
  • GetMetafileHeader(hEmf, header)
  • GetMetafileHeader(hWmf, wmfPlaceableFileHeader, header)
  • GetMetafileHeader(stream, header)


Metafile::GetMetafileHeader(filename, header)

The GetMetafileHeader method gets the header.

static Status GetMetafileHeader(
  const WCHAR* filename,
  MetafileHeader* header
);

Parameters

filename
[in] Pointer to a wide-character string that specifies the name of an existing Metafile object that contains the header.
header
[out] Pointer to a MetafileHeader object that receives the header, which contains the attributes of the metafile.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object from an EMF+ file and gets the metafile header. The code then gets the bounding rectangle of the metafile from the metafile header. Finally, the code creates a Pen object and draws the bounding rectangle.

VOID Example_GetMetafileHeader1(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Metafile object from an EMF+ file.
   Metafile *metafile = new Metafile(L"file1.emf+");

   // Create a MetafileHeader object.
   MetafileHeader metaHeader;

   // Get the MetafileHeader.
   metafile->GetMetafileHeader(L"file1.emf+", &metaHeader);

   // Get the bounding rectangle of the metafile.
   Rect rect;
   metaHeader.GetBounds(&rect);

   // Create a Pen object, and draw the bounding rectangle.
   Pen pen(Color(255, 0, 0, 0));
   graphics.DrawRectangle(&pen, rect);

   // Delete the metafile.
   delete metafile;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
MetafileHeader
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


Metafile::GetMetafileHeader(header)

The GetMetafileHeader method gets the header.

Status GetMetafileHeader(
  MetafileHeader* header
) const;

Parameters

header
[out] Pointer to a MetafileHeader object that receives the header, which contains the attributes of the metafile.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object from an EMF+ file and gets the metafile header. The code then gets the bounding rectangle of the metafile from the metafile header. Finally, the code creates a Pen object and draws the bounding rectangle.

VOID Example_GetMetafileHeader1(HDC hdc)
{
   Graphics graphics(hdc);

   //Create a Metafile object from an EMF+ file.
   Metafile *metafile = new Metafile(L"file1.emf+");

   // Create a MetafileHeader object.
   MetafileHeader metaHeader;

   // Get the MetafileHeader.
   metafile->GetMetafileHeader(&metaHeader);

   // Get the bounding rectangle of the metafile.
   Rect rect;
   metaHeader.GetBounds(&rect);

   // Create a Pen object, and draw the bounding rectangle.
   Pen pen(Color(255, 0, 0, 0));
   graphics.DrawRectangle(&pen, rect);

   // Delete the metafile.
   delete metafile;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
MetafileHeader
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


Metafile::GetMetafileHeader(hEmf, header)

The GetMetafileHeader method gets the header.

static Status GetMetafileHeader(
  HENHMETAFILE hEmf,
  MetafileHeader* header
);

Parameters

hEmf
[in] Windows handle to a metafile.
header
[out] Pointer to a MetafileHeader object that receives the header, which contains the attributes of the metafile.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object from an EMF+ file, gets a Windows handle to the metafile, and gets the metafile header. The code then gets the bounding rectangle of the metafile from the metafile header. Finally, the code creates a Pen object and draws the bounding rectangle.

VOID Example_GetMetafileHeader3(HWND hWnd)
{
   Graphics graphics(hdc);

   //Create a Metafile object from an EMF+ file.
   Metafile *metafile = new Metafile(L"file1.emf+");

   // Create a MetafileHeader object.
   MetafileHeader metaHeader;

   // Get a Windows handle to the metafile.
   HENHMETAFILE hEmf;
   hEmf = metafile->GetHENHMETAFILE();

   // Get the MetafileHeader.
   metafile->GetMetafileHeader(hEmf, &metaHeader);

   // Get the bounding rectangle of the metafile.
   Rect rect;
   metaHeader.GetBounds(&rect);

   // Create a Pen object, and draw the bounding rectangle.
   Pen pen(Color(255, 0, 0, 0));
   graphics.DrawRectangle(&pen, rect);

   // Delete the metafile.
   delete metafile;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
HENHMETAFILE, MetafileHeader
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


Metafile::GetMetafileHeader(hWmf, wmfPlaceableFileHeader, header)

The GetMetafileHeader method gets the metafile header of this metafile.

static Status GetMetafileHeader(
  HMETAFILE hWmf,
  const WmfPlaceableFileHeader* wmfPlaceableFileHeader,
  MetafileHeader* header
);

Parameters

hWmf
[in] Windows handle to a metafile.
wmfPlaceableFileHeader
[in] Pointer to a placeable metafile header.
header
[out] Pointer to a MetafileHeader object that receives the copy of the metafile header.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
WmfPlaceableFileHeader, MetafileHeader
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


Metafile::GetMetafileHeader(stream, header)

The GetMetafileHeader method gets the header.

static Status GetMetafileHeader(
  IStream* stream,
  MetafileHeader* header
);

Parameters

stream
[in] Pointer to a COM IStream interface that points to a stream of data in a file.
header
[out] Pointer to a MetafileHeader object that receives the header, which contains the attributes of the metafile.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Metafile object from an EMF+ file and gets the metafile header. The code then creates a pointer to a COM IStream interface and gets the metafile header.

{
   Graphics graphics(hdc);

   //Create a Metafile object from an EMF+ file.
   Metafile *metafile = new Metafile(L"file1.emf+");

   // Create a MetafileHeader object.
   MetafileHeader metaHeader;

   // Create a pointer to a COM IStream interface.
   IStream* pStream = NULL;

   // Get the MetafileHeader.
   metafile->GetMetafileHeader(pStream, &metaHeader);

   // Delete the metafile.
   delete metafile;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
MetafileHeader
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


Metafile::PlayRecord(recordType, flags, dataSize, data)

The PlayRecord method plays a metafile record.

PlayRecord(
  EmfPlusRecordType recordType,
  UINT flags,
  UINT dataSize,
  const BYTE* data
);

Parameters

recordType
[in] Element of the EmfPlusRecordType enumeration that specifies the type of metafile record to be played.
flags
[in] Set of flags that specify attributes of the record to be played.
dataSize
[in] Integer that specifies the number of bytes contained in the record data.
data
[in] Pointer to an array of bytes that contains the record data.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

This method is used in conjunction with the EnumerateMetafile method of the Graphics class. The EnumerateMetafile method calls an application-defined callback function for each record in a specified metafile. The callback function can display each record (or selected records) by calling the PlayRecord method.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetafile.h; include Gdiplus.h.

See Also

Reference
EmfPlusRecordType, EnumerateMetafile
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader Class

A MetafileHeader object stores properties of an associated metafile.

Data Members

Data member | Description
DpiX | REAL. Horizontal resolution, in dots per inch, of the image stored in the associated metafile.
DpiY | REAL. Vertical resolution, in dots per inch, of the image stored in the associated metafile.
EmfPlusFlags | UINT. Value that specifies the EMF+ flags associated with the metafile.
EmfPlusHeaderSize | INT. Size, in bytes, of the EMF+ header.
Height | INT. Height, in pixels, of the image stored in the associated metafile.
LogicalDpiX | INT. Logical horizontal resolution, in dots per inch, of the image stored in the associated metafile.
LogicalDpiY | INT. Logical vertical resolution, in dots per inch, of the image stored in the associated metafile.
Size | UINT. Size, in bytes, of the associated metafile.
Type | MetafileType. Element of the MetafileType enumeration that specifies the type of the associated metafile.
Version | UINT. Version of the associated metafile.
Width | INT. Width, in pixels, of the image stored in the associated metafile.
X | INT. Leftmost coordinate of the image stored in the associated metafile.
Y | INT. Topmost coordinate of the image stored in the associated metafile.
{WmfHeader, EmfHeader} | union. Types are METAHEADER and ENHMETAHEADER3 respectively.

Methods

Method | Description
GetBounds | Gets a rectangle that bounds the Metafile.
GetDpiX | Gets the horizontal dpi of the metafile.
GetDpiY | Gets the vertical dpi of the metafile.
GetEmfHeader | Gets the ENHMETAHEADER3 structure from an EMF or EMF+ metafile.
GetEmfPlusFlags | Gets the EMF+ flags associated with the metafile.
GetMetafileSize | Gets the size of the metafile in bytes.
GetType | Gets the metafile type.
GetVersion | Gets the version of the metafile.
GetWmfHeader | Gets the METAHEADER structure of a WMF metafile.
IsDisplay | Determines whether a metafile was recorded against a display handle to a device context.
IsEmf | Determines whether the metafile contains only GDI records.
IsEmfOrEmfPlus | Determines whether the metafile contains GDI or GDI+ records.
IsEmfPlus | Determines whether the metafile contains GDI+ records.
IsEmfPlusDual | Determines whether the metafile contains both, GDI and GDI+ records.
IsEmfPlusOnly | Determines whether the metafile contains only GDI+ records.
IsWmf | Determines whether the metafile is an EMF file.
IsWmfPlaceable | Determines whether the metafile is a placeable metafile.

Remarks

Metafiles provide a device-independent and application-independent way to share pictures. They contain records that describe a sequence of graphics APIs to invoke in a particular order with their associated graphics data. Metafiles can be recorded by an application and later played back by that application or by another one to reproduce a particular picture. They can also be used to send content to a print spooler. Enhanced metafiles support the ability to provide both GDI+ and GDI descriptions of the same picture so that both GDI+ and down-level GDI applications can render it.


MetafileHeader Methods

This topic lists the methods of the MetafileHeader class. For a complete class listing, see MetafileHeader Class.

  • GetBounds(rect)
  • GetDpiX()
  • GetDpiY()
  • GetEmfHeader()
  • GetEmfPlusFlags()
  • GetMetafileSize()
  • GetType()
  • GetVersion()
  • GetWmfHeader()
  • IsDisplay()
  • IsEmf()
  • IsEmfOrEmfPlus()
  • IsEmfPlus()
  • IsEmfPlusDual()
  • IsEmfPlusOnly()
  • IsWmf()
  • IsWmfPlaceable()


MetafileHeader::GetBounds(rect)

The GetBounds method gets the bounding rectangle for the associated metafile.

VOID GetBounds(
  Rect* rect
);

Parameters

rect
[out] Pointer to a Rect object that receives the bounding rectangle.

Return Values

This method does not return a value.

Example Code [C++]

The following example calls the Metafile::CreateMetafileHeader method to create a MetafileHeader object based on header information in an EMF file. The code calls the GetBounds method to obtain the bounding rectangle for the metafile stored in the EMF file. Then the code draws the bounding rectangle.

VOID Example_GetBounds(HDC hdc)
{
   Graphics graphics(hdc);

   MetafileHeader metaHeader;
   Metafile::GetMetafileHeader(L"SampleMetafile.emf", &metaHeader);

   Rect rect;
   metaHeader.GetBounds(&rect);

   Pen pen(Color(255, 0, 0, 0));
   graphics.DrawRectangle(&pen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
GetMetafileHeader, Metafile, Rect
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::GetDpiX()

The GetDpiX method gets the horizontal dots per inch of the associated metafile.

REAL GetDpiX(void);

Parameters

This method has no parameters.

Return Values

This method returns a real number that indicates the horizontal dots per inch of the associated metafile.

Example Code [C++]

The following example creates a MetafileHeader object and then gets the horizontal dots per inch.

MetafileHeader metaHeader;
Metafile::GetMetafileHeader(L"SampleMetafile.emf", &metaHeader);

// Get the horizontal dots per inch of the associated metafile.
REAL dpiX = metaHeader.GetDpiX();

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
GetDpiY, GetMetafileHeader, Metafile
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::GetDpiY()

The GetDpiY method gets the vertical dots per inch of the associated metafile.

REAL GetDpiY(void);

Parameters

This method has no parameters.

Return Values

This method returns a real number that specifies the vertical dots per inch of the associated metafile.

Example Code [C++]

The following example creates a MetafileHeader object and then gets the vertical dots per inch of the associated metafile.

MetafileHeader metaHeader;
Metafile::GetMetafileHeader(L"SampleMetafile.emf", &metaHeader);

// Get the vertical dots per inch of the associated metafile.
REAL dpiY = metaHeader.GetDpiY();

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
GetDpiX, GetMetafileHeader, Metafile
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::GetEmfHeader()

The GetEmfHeader method gets an ENHMETAHEADER3 structure that contains properties of the associated metafile.

const ENHMETAHEADER3* GetEmfHeader(void) const

Parameters

This method has no parameters.

Return Values

If the associated metafile is in the EMF or EMF+ format, this method returns a pointer to an ENHMETAHEADER3 structure that contains properties of the associated metafile. If the associated metafile is in the WMF format, this method returns NULL.

Example Code [C++]

The following console application creates a MetafileHeader object from an EMF file. The code calls the GetEmfHeader method of the MetafileHeader object and then prints two of the data members of the ENHMETAHEADER3 structure.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   MetafileHeader* metafileHeader = new MetafileHeader;
   const ENHMETAHEADER3* emh = NULL;

   Metafile::GetMetafileHeader(L"SampleMetafile.emf", metafileHeader);
   emh = metafileHeader->GetEmfHeader();

   printf("szlDevice.cx: %d\n", emh->szlDevice.cx);
   printf("szlMillimeters.cx: %d\n", emh->szlMillimeters.cx);

   delete metafileHeader;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
ENHMETAHEADER3, GetMetafileHeader, Metafile
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::GetEmfPlusFlags()

The GetEmfPlusFlags method gets a flag that indicates whether the associated metafile was recorded against a video display device context.

UINT GetEmfPlusFlags(void);

Parameters

This method has no parameters.

Return Values

If the associated metafile is in the EMF+ format and was recorded against a video display device context, then this method returns GDIP_EMFPLUSFLAGS_DISPLAY; otherwise, it returns 0. GDIP_EMFPLUSFLAGS_DISPLAY is defined in Gdiplusmetaheader.h.

Example Code [C++]

The following example calls GetEmfPlusFlags to determine whether a particular metafile was recorded against a video display device context.

MetafileHeader metaHeader;
Metafile::GetMetafileHeader(L"SampleMetafile.emf", &metaHeader);

if ( metaHeader.GetEmfPlusFlags() == GDIP_EMFPLUSFLAGS_DISPLAY )
{
   // The metafile was recorded against a video display device context.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
GetMetafileHeader, Metafile
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::GetMetafileSize()

The GetMetafileSize method gets the size, in bytes, of the metafile.

UINT GetMetafileSize(void);

Parameters

This method has no parameters.

Return Values

This method returns an integer that specifies the size, in bytes, of the metafile.

Example Code [C++]

The following example calls GetMetafileSize to get the size of a particular metafile.

MetafileHeader metaHeader;
Metafile::GetMetafileHeader(L"sampleMetafile.emf", &metaHeader);

UINT size = metaHeader.GetMetafileSize();

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
GetMetafileHeader, Metafile
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::GetType()

The GetType method gets the type of the associated metafile.

MetafileType GetType(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the MetafileType enumeration that indicates the type of the associated metafile.

Example Code [C++]

The following example calls GetType to determine whether the type of a particular metafile is MetafileTypeEmfPlusDual.

MetafileHeader metaHeader;
Metafile::GetMetafileHeader(L"sampleMetafile.emf", &metaHeader);

// Get the type of the metafile.
MetafileType type = metaHeader.GetType();

if(type == MetafileTypeEmfPlusDual)
{
   // The metafile can be played by GDI and GDI+.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
GetMetafileHeader, Metafile, MetafileType
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::GetVersion()

The GetVersion method gets the version of the metafile.

UINT GetVersion(void);

Parameters

This method has no parameters.

Return Values

This method returns the version of the metafile. The metafile version indicates whether the metafile is an EMF, EMF+, or WMF metafile. EMF files always have 0x0010000 as the version. EMF+ files currently have 0xdbc01001 as the version. WMF files usually have 0x0300 as the version; however, earlier versions may be 0x0100.

Example Code [C++]

The following example gets the version of a metafile.

MetafileHeader metaHeader;
Metafile::GetMetafileHeader(L"SampleMetafile.emf", &metaHeader);

UINT version = metaHeader.GetVersion();

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
GetMetafileHeader, Metafile
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::GetWmfHeader()

The GetWmfHeader method gets a METAHEADER structure that contains properties of the associated metafile.

const METAHEADER* GetWmfHeader(void) const;

Parameters

This method has no parameters.

Return Values

If the associated metafile is in the WMF format, this method returns a pointer to a structure that contains properties of the associated metafile. If the associated metafile is in the EMF or EMF+ format, this method returns NULL. The METAHEADER structure is defined in Wingdi.h.

Example Code [C++]

The following console application creates a MetafileHeader object based on a WMF file. The code calls GetWmfHeader and then prints one of the data members of the METAHEADER structure.

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   MetafileHeader* metafileHeader = new MetafileHeader;
   const METAHEADER* mh = NULL;

   Metafile::GetMetafileHeader(L"SampleMetafile2.wmf", metafileHeader);
   mh = metafileHeader->GetWmfHeader();

   printf("mtSize: %d\n", mh->mtSize);

   delete metafileHeader;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
GetMetafileHeader, Metafile, METAHEADER
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::IsDisplay()

The IsDisplay method determines whether the associated metafile was recorded against a video display device context.

BOOL IsDisplay(void) const;

Parameters

This method has no parameters.

Return Values

If the associated metafile is in the EMF+ format and was recorded against a video display device context, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example calls IsDisplay to determine whether a particular metafile was recorded against a video display device context.

MetafileHeader metaHeader;
Metafile::GetMetafileHeader(L"SampleMetafile.emf", &metaHeader);

if ( metaHeader.IsDisplay() == TRUE )
{
   // The metafile was recorded against a video display device context.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::IsEmf()

The IsEmf method determines whether the associated metafile is in the EMF format.

BOOL IsEmf(void) const;

Parameters

This method has no parameters.

Return Values

If the associated metafile is in the EMF format, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a Metafile object from an EMF file and gets the metafile header of the metafile. The code then determines whether the metafile contains GDI records.

MetafileHeader metaHeader;
Metafile::GetMetafileHeader(L"sampleMetafile.emf", &metaHeader);

if( metaHeader.IsEmf() == TRUE )
{
   // The associated metafile is in the EMF format.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
EmfType
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::IsEmfOrEmfPlus()

The IsEmfOrEmfPlus method determines whether the associated metafile is in either the EMF or EMF+ format.

BOOL IsEmfOrEmfPlus(void) const;

Parameters

This method has no parameters.

Return Values

If the associated metafile is in the EMF or EMF+ format, this method returns TRUE; otherwise, it returns FALSE. In particular, this method returns FALSE if the associated metafile is in the WMF format.

Example Code [C++]

The following example calls IsEmfOrEmfPlus to determine whether the format of a particular metafile is either EMF or EMF+.

MetafileHeader metaHeader;
Metafile::GetMetafileHeader(L"SampleMetafile.emf", &metaHeader);

if( metaHeader.IsEmfOrEmfPlus() == TRUE )
{
   // The format of the associated metafile is either EMF or EMF+.
   // The format of the associated metafile is not WMF.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
EmfType
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::IsEmfPlus()

The IsEmfPlus method determines whether the associated metafile is in the EMF+ format.

BOOL IsEmfPlus(void) const;

Parameters

This method has no parameters.

Return Values

If the associated metafile is in the EMF+ format, this method returns TRUE; otherwise, it returns FALSE. In particular, this method returns FALSE if the associated metafile is in the EMF or WMF format.

Example Code [C++]

The following example calls IsEmfPlus to determine whether a particular metafile is in the EMF+ format.

MetafileHeader metaHeader;
Metafile::GetMetafileHeader(L"sampleMetafile.emf", &metaHeader);

if( metaHeader.IsEmfPlus() == TRUE )
{
   // The associated metafile is in the EMF+ format.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
EmfType
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::IsEmfPlusDual()

The IsEmfPlusDual method determines whether the associated metafile is in the EMF+ Dual format.

BOOL IsEmfPlusDual(void) const;

Parameters

This method has no parameters.

Return Values

If the associated metafile is in the EMF+ Dual format, this method returns TRUE; otherwise, it returns FALSE. In particular, this method returns FALSE if the associated metafile is in the WMF, EMF, or EMF+ Only format.

Example Code [C++]

The following example calls IsEmfPlusDual to determine whether a particular metafile is in the EMF+ Dual format.

MetafileHeader metaHeader;
Metafile::GetMetafileHeader(L"sampleMetafile.emf", &metaHeader);

if( metaHeader.IsEmfPlusDual() == TRUE )
{
   // The associated metafile is in the EMF+ Dual format.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
EmfType
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::IsEmfPlusOnly()

The IsEmfPlusOnly method determines whether the associated metafile is in the EMF+ Only format.

BOOL IsEmfPlusOnly(void) const;

Parameters

This method has no parameters.

Return Values

If the associated metafile is in the EMF+ Only format, this method returns TRUE; otherwise, it returns FALSE. In particular, this method returns FALSE if the associated metafile is in the WMF, EMF, or EMF+ Dual format.

Example Code [C++]

The following example creates a Metafile object from an EMF+ file and gets the metafile header of the metafile. The code then determines whether the metafile contains only GDI+ records.

MetafileHeader metaHeader;
Metafile::GetMetafileHeader(L"SampleMetafile.emf", &metaHeader);

if( metaHeader.IsEmfPlusOnly() == TRUE )
{
   // The associated metafile is in the EMF+ Only format.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
EmfType
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


MetafileHeader::IsWmf()

The IsWmf method determines whether the associated metafile is in the WMF format.

BOOL IsWmf(void);

Parameters

This method has no parameters.

Return Values

If the associated metafile is in the WMF format, this method returns TRUE; otherwise, it returns FALSE. In particular, this method returns FALSE if the associated metafile is in the EMF or EMF+ format.

Example Code [C++]

The following example calls IsWmf to determine whether a particular metafile is in the WMF format.

MetafileHeader metaHeader;
Metafile::GetMetafileHeader(L"sampleMetafile.wmf", &metaHeader);

if( metaHeader.IsWmf() == TRUE )
{
   // The associated metafile is in the WMF format.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.


MetafileHeader::IsWmfPlaceable()

The IsWfmPlaceable method determines whether the associated metafile is a placeable metafile.

BOOL IsWmfPlaceable(void) const;

Parameters

This method has no parameters.

Return Values

If the associated metafile is a placeable metafile, this method returns TRUE; otherwise, it returns FALSE.

Remarks

Placeable metafiles are WMF files that contain a preheader preceding the metafile header. The preheader contains additional information for the metafile header of the metafile.

Example Code [C++]

The following example creates a Metafile object from a WMF file and gets the metafile header of the metafile. The code then determines whether the metafile is a placeable metafile.

MetafileHeader metaHeader;
Metafile::GetMetafileHeader(L"sampleMetafile.wmf", &metaHeader);

if( metaHeader.IsWmfPlaceable() == TRUE )
{
   // The associated metafile is a placeable metafile.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
EmfType
Tasks and Examples
Loading and Displaying Metafiles
Concepts
Metafiles


PathData Class

The PathData class is a helper class for the GraphicsPath and GraphicsPathIterator classes. A GraphicsPath object has an array of points and an array of types. Each element in the array of types is a byte that specifies the point type and a set of flags for the corresponding element in the array of points. You can use a PathData object to get or set the data points (and their types) of a path.

Data Members

Data member | Description
Count | INT. Number of PointF objects in the Points array. This is the same as the number of bytes in the Types array..
Points | PointF*. Pointer to an array of path data points.
Types | BYTE*. Pointer to an array of bytes. Each byte holds the point type and a set of flags for the corresponding point in the Points array. Possible point types and flags are listed in the PathPointType enumeration.

Constructors

Constructor | Description
PathData | Default constructor. Creates a new PathData object.

Methods

Method | Description
~PathData | PathData object destructor.

See Also

Reference
GetPathData, GetPathPoints, GetPathTypes, GetPointCount, PathPointType, PointF
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


PathData::PathData()

Creates a PathData object. The Count data member is initialized to 0. The Points and Types data members are initialized to NULL.

PathData(void);

Parameters

This method has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetPathPoints, GetPathTypes, GetPointCount, PathPointType, PointF
Tasks and Examples
Constructing and Drawing Paths
Concepts
Paths


PathGradientBrush Class

A PathGradientBrush object stores the attributes of a color gradient that you can use to fill the interior of a path with a gradually changing color. A path gradient brush has a boundary path, a boundary color, a center point, and a center color. When you paint an area with a path gradient brush, the color changes gradually from the boundary color to the center color as you move from the boundary path to the center point.

Inheritance

GdiplusBase
Brush
PathGradientBrush

Constructors

Constructor | Description
PathGradientBrush | Overloaded. Creates a PathGradientBrush object.

Methods

Uninherited

Method | Description
GetBlend | Gets the blend factors and the corresponding blend positions.
GetBlendCount | Returns the number of blend factors.
GetCenterColor | Gets the color of the center point.
GetCenterPoint | Overloaded. Gets the center point.
GetFocusScales | Gets the focus scales.
GetGammaCorrection | Returns a value that indicates whether gamma correction is enabled.
GetGraphicsPath | Not implemented in GDI+ version 1.0.
GetInterpolationColorCount | Gets the number of colors in the array of preset colors.
GetInterpolationColors | Gets the preset colors and the blend positions.
GetPointCount | Gets the number of points in the array of points that defines the boundary path.
GetRectangle | Overloaded. Gets the rectangle that encloses the boundary path.
GetSurroundColorCount | Gets the number of colors specified for the boundary.
GetSurroundColors | Gets the colors specified for the boundary.
GetTransform | Gets the transformation matrix.
GetWrapMode | Gets the wrap mode.
MultiplyTransform | Multiplies the current transformation matrix by another matrix.
ResetTransform | Resets the transformation matrix to the identity matrix.
RotateTransform | Multiplies the transformation matrix by a rotation matrix.
ScaleTransform | Multiplies the transformation matrix by a scaling matrix.
SetBlend | Sets a custom blend by setting blend positions and blend factors.
SetBlendBellShape | Sets the location of the center color as a fraction of the distance from the boundary to the center point.
SetBlendTriangularShape | Sets the location of the center color as a fraction of the distance from the boundary to the center point.
SetCenterColor | Sets the center color.
SetCenterPoint | Overloaded. Sets the center point.
SetFocusScales | Sets the focus scales.
SetGammaCorrection | Enables/disables gamma correction.
SetGraphicsPath | Not implemented in GDI+ version 1.0.
SetInterpolationColors | Sets the preset colors and the blend positions.
SetSurroundColors | Sets the colors for the boundary..
SetTransform | Sets the transformation matrix.
SetWrapMode | Sets the wrap mode, which influences tiling.
TranslateTransform | Multiplies the transformation matrix by a translation matrix.

Inherited from Brush

Method | Description
Clone | Creates a new Brush object based on this brush.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetType | Gets the type of this brush.

Remarks

By default, the center point of a path gradient brush is the centroid of the boundary path, but you can set the center point to any location, inside or outside the path, by calling PathGradientBrush::SetCenterPoint.

The boundary path can be a polygon specified by an array of points, and each of those points along the boundary can have a different color.

By default, the color is linearly related to the distance as you move from a point on the boundary to the center point. You can customize the relationship between color and distance by calling PathGradientBrush::SetBlend.


PathGradientBrush Constructors

This topic lists the constructors of the PathGradientBrush class. For a complete class listing, see PathGradientBrush Class.

  • PathGradientBrush(path)
  • PathGradientBrush(Point* points, INT count, WrapMode wrapMode)
  • PathGradientBrush(PointF* points, INT count, WrapMode wrapMode)


PathGradientBrush::PathGradientBrush(path)

Creates a PathGradientBrush object based on a GraphicsPath object.

PathGradientBrush(
  const GraphicsPath* path
);

Parameters

path
[in] Pointer to a GraphicsPath object that specifies the boundary path of the path gradient brush.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, LinearGradientBrush
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::PathGradientBrush(Point* points, INT count, WrapMode wrapMode)

Creates a PathGradientBrush object based on an array of points. Initializes the wrap mode of the path gradient brush.

PathGradientBrush(
  const Point* points,
  INT count,
  WrapMode wrapMode
);

Parameters

points
[in] Pointer to an array of points that specifies the boundary path of the path gradient brush.
count
[in] Integer that specifies the number of elements in the points array.
wrapMode
[in] Optional. Element of the WrapMode enumeration that specifies how areas painted with the path gradient brush will be tiled. The default value is WrapModeClamp.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, LinearGradientBrush, Point
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::PathGradientBrush(PointF* points, INT count, WrapMode wrapMode)

Creates a PathGradientBrush object based on an array of points. Initializes the wrap mode of the path gradient brush.

PathGradientBrush(
  const PointF* points,
  INT count,
  WrapMode wrapMode
);

Parameters

points
[in] Pointer to an array of points that specifies the boundary path of the path gradient brush.
count
[in] Integer that specifies the number of elements in the points array.
wrapMode
[in] Optional. Element of the WrapMode enumeration that specifies how areas painted with the path gradient brush will be tiled. The default value is WrapModeClamp.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, LinearGradientBrush, PointF
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush Methods

This topic lists the methods of the PathGradientBrush class. For a complete class listing, see PathGradientBrush Class.

  • Clone()
  • GetBlend(blendFactors, blendPositions, count)
  • GetBlendCount()
  • GetCenterColor(color)
  • GetCenterPoint(Point* point)
  • GetCenterPoint(PointF* point)
  • GetFocusScales(xScale, yScale)
  • GetGammaCorrection()
  • GetGraphicsPath(path)
  • GetInterpolationColorCount()
  • GetInterpolationColors(presetColors, blendPositions, count)
  • GetLastStatus()
  • GetPointCount()
  • GetRectangle(Rect* rect)
  • GetRectangle(RectF* rect)
  • GetSurroundColorCount()
  • GetSurroundColors(colors, count)
  • GetTransform(matrix)
  • GetType()
  • GetWrapMode()
  • MultiplyTransform(matrix, order)
  • ResetTransform()
  • RotateTransform(angle, order)
  • ScaleTransform(sx, sy, order)
  • SetBlend(blendFactors, blendPositions, count)
  • SetBlendBellShape(focus, scale)
  • SetBlendTriangularShape(focus, scale)
  • SetCenterColor(color)
  • SetCenterPoint(Point& point)
  • SetCenterPoint(PointF& point)
  • SetFocusScales(xScale, yScale)
  • SetGammaCorrection(useGammaCorrection)
  • SetGraphicsPath(path)
  • SetInterpolationColors(presetColors, blendPositions, count)
  • SetSurroundColors(colors, count)
  • SetTransform(matrix)
  • SetWrapMode(wrapMode)
  • TranslateTransform(dx, dy, order)


PathGradientBrush::GetBlend(blendFactors, blendPositions, count)

The GetBlend method gets the blend factors and the corresponding blend positions currently set for this path gradient brush.

Status GetBlend(
  REAL* blendFactors,
  REAL* blendPositions,
  INT count
);

Parameters

blendFactors
[out] Pointer to an array that receives the blend factors.
blendPositions
[out] Pointer to an array that receives the blend positions.
count
[in] Integer that specifies the number of blend factors to retrieve. Before calling the GetBlend method of a PathGradientBrush object, call the GetBlendCount method of that same PathGradientBrush object to determine the current number of blend factors. The number of blend positions retrieved is the same as the number of blend factors retrieved.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A PathGradientBrush object has a boundary path and a center point. When you fill an area with a path gradient brush, the color changes gradually as you move from the boundary path to the center point. By default, the color is linearly related to the distance, but you can customize the relationship between color and distance by calling the SetBlend method.

Example Code [C++]

The following example demonstrates several methods of the PathGradientBrush class including SetBlend, GetBlendCount, and GetBlend. The code creates a PathGradientBrush object and calls the SetBlend method to establish a set of blend factors and blend positions for the brush. Then the code calls the GetBlendCount method to retrieve the number of blend factors. After the number of blend factors is retrieved, the code allocates two buffers: one to receive the array of blend factors and one to receive the array of blend positions. Then the code calls the GetBlend method to retrieve the blend factors and the blend positions.

VOID Example_GetBlend(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that consists of a single ellipse.
   GraphicsPath path;
   path.AddEllipse(0, 0, 200, 100);

   // Use the path to construct a brush.
   PathGradientBrush pthGrBrush(&path);

   // Set the color at the center of the path to blue.
   pthGrBrush.SetCenterColor(Color(255, 0, 0, 255));

   // Set the color along the entire boundary of the path to aqua.
   Color colors[] = {Color(255, 0, 255, 255)};
   INT count = 1;
   pthGrBrush.SetSurroundColors(colors, &count);

   // Set blend factors and positions for the path gradient brush.
   REAL fac[] = {
      0.0f,
      0.4f,     // 40 percent of the way from aqua to blue
      0.8f,     // 80 percent of the way from aqua to blue
      1.0f};

   REAL pos[] = {
      0.0f,
      0.3f,   // 30 percent of the way from the boundary to the center
      0.7f,   // 70 percent of the way from the boundary to the center
      1.0f};

   pthGrBrush.SetBlend(fac, pos, 4);

   // Fill the ellipse with the path gradient brush.
   graphics.FillEllipse(&pthGrBrush, 0, 0, 200, 100);

   // Obtain information about the path gradient brush.
   INT blendCount = pthGrBrush.GetBlendCount();
   REAL* factors = new REAL[blendCount];
   REAL* positions = new REAL[blendCount];

   pthGrBrush.GetBlend(factors, positions, blendCount);

   for(INT j = 0; j < blendCount; ++j)
   {
      // Inspect or use the value in factors[j].
      // Inspect or use the value in positions[j].
   }

   delete [] factors;
   delete [] positions;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetBlendCount, GraphicsPath, LinearGradientBrush, SetBlend, SetCenterColor, SetCenterPoint Methods, SetSurroundColors
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes, Paths


PathGradientBrush::GetBlendCount()

The GetBlendCount method gets the number of blend factors currently set for this path gradient brush.

INT GetBlendCount(void);

Parameters

This method has no parameters.

Return Values

This method returns the number of blend factors currently set for this path gradient brush.

Remarks

Before you call the GetBlend method of a PathGradientBrush object, you must allocate two buffers: one to receive an array of blend factors and one to receive an array of blend positions. To determine the size of the required buffers, call the GetBlendCount method of the PathGradientBrush object. The size (in bytes) of each buffer should be the return value of GetBlendCount multiplied by sizeof(REAL).

Example Code [C++]

The following example demonstrates several methods of the PathGradientBrush class, including SetBlend, GetBlendCount, and GetBlend. The code creates a PathGradientBrush object and calls the SetBlend method to establish a set of blend factors and blend positions for the brush. Then the code calls the GetBlendCount method to retrieve the number of blend factors. Once the number of blend factors is retrieved, the code allocates two buffers: one to receive the array of blend factors and one to receive the array of blend positions. Then the code calls the GetBlend method to retrieve the blend factors and the blend positions.

VOID Example_GetBlend(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that consists of a single ellipse.
   GraphicsPath path;
   path.AddEllipse(0, 0, 200, 100);

   // Use the path to construct a brush.
   PathGradientBrush pthGrBrush(&path);

   // Set the color at the center of the path to blue.
   pthGrBrush.SetCenterColor(Color(255, 0, 0, 255));

   // Set the color along the entire boundary of the path to aqua.
   Color colors[] = {Color(255, 0, 255, 255)};
   INT count = 1;
   pthGrBrush.SetSurroundColors(colors, &count);

   // Set blend factors and positions for the path gradient brush.
   REAL fac[] = {
      0.0f,
      0.4f,     // 40 percent of the way from aqua to blue
      0.8f,     // 80 percent of the way from aqua to blue
      1.0f};

   REAL pos[] = {
      0.0f,
      0.3f,   // 30 percent of the way from the boundary to the center
      0.7f,   // 70 percent of the way from the boundary to the center
      1.0f};

   pthGrBrush.SetBlend(fac, pos, 4);

   // Fill the ellipse with the path gradient brush.
   graphics.FillEllipse(&pthGrBrush, 0, 0, 200, 100);

   // Obtain information about the path gradient brush.
   INT blendCount = pthGrBrush.GetBlendCount();
   REAL* factors = new REAL[blendCount];
   REAL* positions = new REAL[blendCount];

   pthGrBrush.GetBlend(factors, positions, blendCount);

   for(INT j = 0; j < blendCount; ++j)
   {
      // Inspect or use the value in factors[j].
      // Inspect or use the value in positions[j].
   }

   delete [] factors;
   delete [] positions;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetBlend, SetBlend
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::GetCenterColor(color)

The GetCenterColor method gets the color of the center point of this path gradient brush.

Status GetCenterColor(
  Color* color
);

Parameters

color
[out] Pointer to a Color object that receives the color of the center point.

Remarks

By default, the center point of a PathGradientBrush object is the centroid of the brush's boundary path, but you can set the center point to any location, inside or outside the path, by calling the SetCenterPoint method of the PathGradientBrush object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a PathGradientBrush object and uses it to fill an ellipse. Then the code calls the GetCenterColor method of the PathGradientBrush object to obtain the center color.

VOID Example_GetCenterColor(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that consists of a single ellipse.
   GraphicsPath path;
   path.AddEllipse(0, 0, 200, 100);

   // Use the path to construct a brush.
   PathGradientBrush pthGrBrush(&path);

   // Set the color at the center of the path to blue.
   pthGrBrush.SetCenterColor(Color(255, 0, 0, 255));

   // Set the color along the entire boundary of the path to aqua.
   Color colors[] = {Color(255, 0, 255, 255)};
   int count = 1;
   pthGrBrush.SetSurroundColors(colors, &count);

   // Fill the ellipse with the path gradient brush.
   graphics.FillEllipse(&pthGrBrush, 0, 0, 200, 100);

   // Obtain information about the path gradient brush.
   Color color;
   pthGrBrush.GetCenterColor(&color);

   // Fill a rectangle with the retrieved color.
   SolidBrush solidBrush(color);
   graphics.FillRectangle(&solidBrush, 0, 120, 200, 30);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Color, GetCenterPoint Methods, SetCenterColor, SetCenterPoint Methods
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::GetCenterPoint Methods

This topic lists the GetCenterPoint methods of the PathGradientBrush class. For a complete list of methods for the PathGradientBrush class, see PathGradientBrush Methods.

  • GetCenterPoint(Point* point)
  • GetCenterPoint(PointF* point)


PathGradientBrush::GetCenterPoint(Point* point)

The GetCenterPoint method gets the center point of this path gradient brush.

Status GetCenterPoint(
  Point* point
);

Parameters

point
[out] Pointer to a Point object that receives the center point.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

By default, the center point of a PathGradientBrush object is at the centroid of the brush's boundary path, but you can set the center point to any location, inside or outside the path, by calling the SetCenterPoint method of the PathGradientBrush object.

Example Code [C++]

The following example demonstrates several methods of the PathGradientBrush class including GetCenterPoint and SetCenterColor. The code creates a PathGradientBrush object and then sets the brush's center color and boundary color. The code calls the GetCenterPoint method to determine the center point of the path gradient brush and then draws a line from the origin to that center point.

VOID Example_GetCenterPoint(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that consists of a single ellipse.
   GraphicsPath path;
   path.AddEllipse(0, 0, 200, 100);

   // Use the path to construct a brush.
   PathGradientBrush pthGrBrush(&path);

   // Set the color at the center of the path to blue.
   pthGrBrush.SetCenterColor(Color(255, 0, 0, 255));

   // Set the color along the entire boundary of the path to aqua.
   Color colors[] = {Color(255, 0, 255, 255)};
   INT count = 1;
   pthGrBrush.SetSurroundColors(colors, &count);

   // Fill the ellipse with the path gradient brush.
   graphics.FillEllipse(&pthGrBrush, 0, 0, 200, 100);

   // Obtain information about the path gradient brush.
   Point  centerPoint;
   pthGrBrush.GetCenterPoint(&centerPoint);

   // Draw a line from the origin to the center of the ellipse.
   Pen pen(Color(255, 0, 255, 0));
   graphics.DrawLine(&pen, Point(0, 0), centerPoint);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Color, GetCenterColor, SetCenterColor, SetCenterPoint Methods
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::GetCenterPoint(PointF* point)

The GetCenterPoint method gets the center point of this path gradient brush.

Status GetCenterPoint(
  PointF* point
);

Parameters

point
[out] Pointer to a PointF object that receives the center point.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

By default, the center point of a PathGradientBrush object is at the centroid of the brush's boundary path, but you can set the center point to any location, inside or outside the path, by calling the SetCenterPoint method of the PathGradientBrush object.

Example Code [C++]

The following example demonstrates several methods of the PathGradientBrush class including GetCenterPoint and SetCenterColor. The code creates a PathGradientBrush object and then sets the brush's center color and boundary color. The code calls the GetCenterPoint method to determine the center point of the gradient and then draws a line from the origin to that center point.

VOID Example_GetCenterPoint(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that consists of a single ellipse.
   GraphicsPath path;
   path.AddEllipse(0, 0, 200, 100);

   // Use the path to construct a brush.
   PathGradientBrush pthGrBrush(&path);

   // Set the color at the center of the path to blue.
   pthGrBrush.SetCenterColor(Color(255, 0, 0, 255));

   // Set the color along the entire boundary of the path to aqua.
   Color colors[] = {Color(255, 0, 255, 255)};
   INT count = 1;
   pthGrBrush.SetSurroundColors(colors, &count);

   // Fill the ellipse with the path gradient brush.
   graphics.FillEllipse(&pthGrBrush, 0, 0, 200, 100);

   // Obtain information about the path gradient brush.
   PointF centerPoint;
   pthGrBrush.GetCenterPoint(&centerPoint);

   // Draw a line from the origin to the center of the ellipse.
   Pen pen(Color(255, 0, 255, 0));
   graphics.DrawLine(&pen, PointF(0, 0), centerPoint);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Color, GetCenterColor, SetCenterColor, SetCenterPoint Methods
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::GetFocusScales(xScale, yScale)

The GetFocusScales method gets the focus scales of this path gradient brush.

Status GetFocusScales(
  REAL* xScale,
  REAL* yScale
);

Parameters

xScale
[out] Pointer to a REAL that receives the x focus scale value.
yScale
[out] Pointer to a REAL that receives the y focus scale value.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

By default, the center color of a path gradient is at the center point. By calling SetFocusScales, you can specify that the center color should appear along a path that surrounds the center point. For example, suppose the boundary path is a triangle and the center point is at the centroid of that triangle. Also assume that the boundary color is red and the center color is blue. If you set the focus scales to (0.2, 0.2), the color is blue along the boundary of a small triangle that surrounds the center point. That small triangle is the main boundary path scaled by a factor of 0.2 in the x direction and 0.2 in the y direction. When you paint with the path gradient brush, the color will change gradually from red to blue as you move from the boundary of the large triangle to the boundary of the small triangle. The area inside the small triangle will be filled with blue.

Example Code [C++]

The following example creates a PathGradientBrush object based on a triangular path. The code sets the focus scales of the path gradient brush to (0.2, 0.2) and then uses the path gradient brush to fill an area that contains the triangular path. Finally, the code calls the GetFocusScales method of the PathGradientBrush object to obtain the values of the x focus scale and the y focus scale.

VOID Example_GetFocusScales(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {Point(100, 0), Point(200, 200), Point(0, 200)};

   // No GraphicsPath object is created. The PathGradientBrush
   // object is constructed directly from the array of points.
   PathGradientBrush pthGrBrush(points, 3);

   Color colors[] = {
      Color(255, 255, 0, 0),    // red
      Color(255, 0, 0, 255)};   // blue

   REAL relativePositions[] = {
      0.0f,    // red at the boundary of the outer triangle
      1.0f};   // blue at the boundary of the inner triangle

   pthGrBrush.SetInterpolationColors(colors, relativePositions, 2);

   // The inner triangle is formed by scaling the outer triangle
   // about its centroid. The scaling factor is 0.2 in both
   // the x and y directions.
   pthGrBrush.SetFocusScales(0.2f, 0.2f);

   // Fill a rectangle that is larger than the triangle
   // specified in the Point array. The portion of the
   // rectangle outside the triangle will not be painted.
   graphics.FillRectangle(&pthGrBrush, 0, 0, 200, 200);

   // Obtain information about the path gradient brush.
   REAL xScale = 0.0f;
   REAL yScale = 0.0f;
   pthGrBrush.GetFocusScales(&xScale, &yScale);

   // The value of xScale is now 0.2.
   // The value of yScale is now 0.2.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, SetFocusScales
Tasks and Examples
Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::GetGammaCorrection()

The GetGammaCorrection method determines whether gamma correction is enabled for this path gradient brush.

BOOL GetGammaCorrection(void);

Parameters

This method has no parameters.

Return Values

If gamma correction is enabled, this method returns TRUE; otherwise, it returns FALSE.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
SetGammaCorrection
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::GetGraphicsPath(path)

The GetGraphicsPath method is not implemented in GDI+ version 1.0.

Status GetGraphicsPath(
  GraphicsPath* path
);

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.


PathGradientBrush::GetInterpolationColorCount()

The GetInterpolationColorCount method gets the number of preset colors currently specified for this path gradient brush.

INT GetInterpolationColorCount(void);

Parameters

This method has no parameters.

Return Values

This method returns the number of preset colors currently specified for this path gradient brush.

Remarks

A simple path gradient brush has two colors: a boundary color and a center color. When you paint with such a brush, the color changes gradually from the boundary color to the center color as you move from the boundary path to the center point. You can create a more complex gradient by specifying an array of preset colors and an array of blend positions.

You can obtain the interpolation colors and interpolation positions currently set for a PathGradientBrush object by calling the GetInterpolationColors method of that PathGradientBrush object. Before you call the GetInterpolationColors method, you must allocate two buffers: one to hold the array of interpolation colors and one to hold the array of interpolation positions. You can call the GetInterpolationColorCount method of the PathGradientBrush object to determine the required size of those buffers. The size of the color buffer is the return value of GetInterpolationColorCount multiplied by sizeof(Color). The size of the position buffer is the value of GetInterpolationColorCount multiplied by sizeof(REAL).

Example Code [C++]

The following example creates a PathGradientBrush object from a triangular path. The code sets the preset colors to red, blue, and aqua and sets the blend positions to 0, 0.6, and 1. The code calls the GetInterpolationColorCount method of the PathGradientBrush object to obtain the number of preset colors currently set for the brush. Next, the code allocates two buffers: one to hold the array of preset colors, and one to hold the array of blend positions. The call to the GetInterpolationColors method of the PathGradientBrush object fills the buffers with the preset colors and the blend positions. Finally the code fills a small square with each of the preset colors.

VOID Example_GetInterpColors(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path gradient brush from an array of points, and
   // set the interpolation colors for that brush.

   Point points[] = {Point(100, 0), Point(200, 200), Point(0, 200)};
   PathGradientBrush pthGrBrush(points, 3);

   Color col[] = {
      Color(255, 255, 0, 0),     // red
      Color(255, 0, 0, 255),     // blue
      Color(255, 0, 255, 255)};  // aqua

   REAL pos[] = {
      0.0f,    // red at the boundary
      0.6f,    // blue 60 percent of the way from the boundary to the center
      1.0f};   // aqua at the center

   pthGrBrush.SetInterpolationColors(col, pos, 3);

   // Obtain information about the path gradient brush.
   INT colorCount = pthGrBrush.GetInterpolationColorCount();
   Color* colors = new Color[colorCount];
   REAL* positions = new REAL[colorCount];
   pthGrBrush.GetInterpolationColors(colors, positions, colorCount);

   // Fill a small square with each of the interpolation colors.
   SolidBrush solidBrush(Color(255, 255, 255, 255));

   for(INT j = 0; j < colorCount; ++j)
   {
      solidBrush.SetColor(colors[j]);
      graphics.FillRectangle(&solidBrush, 15*j, 0, 10, 10);
   }

   delete [] colors;
   delete [] positions;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Color, GetInterpolationColors, SetInterpolationColors
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::GetInterpolationColors(presetColors, blendPositions, count)

The GetInterpolationColors method gets the preset colors and blend positions currently specified for this path gradient brush.

Status GetInterpolationColors(
  Color* presetColors,
  REAL* blendPositions,
  INT count
);

Parameters

presetColors
[out] Pointer to an array that receives the preset colors. A color of a given index in the presetColors array corresponds to the blend position of that same index in the blendPositions array.
blendPositions
[out] Pointer to an array that receives the blend positions. Each blend position is a number from 0 through 1, where 0 indicates the boundary of the gradient and 1 indicates the center point. A blend position between 0 and 1 indicates the set of all points that are a certain fraction of the distance from the boundary to the center point. For example, a blend position of 0.7 indicates the set of all points that are 70 percent of the way from the boundary to the center point.
count
[in] Integer that specifies the number of elements in the presetColors array. This is the same as the number of elements in the blendPositions array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other methods of the Status enumeration.

Remarks

A simple path gradient brush has two colors: a boundary color and a center color. When you paint with such a brush, the color changes gradually from the boundary color to the center color as you move from the boundary path to the center point. You can create a more complex gradient by specifying an array of preset colors and an array of blend positions.

Before you call the GetInterpolationColors method, you must allocate two buffers: one to hold the array of preset colors and one to hold the array of blend positions. You can call the GetInterpolationColorCount method of the PathGradientBrush object to determine the required size of those buffers. The size of the color buffer is the return value of GetInterpolationColorCount multiplied by sizeof(Color). The size of the position buffer is the value of GetInterpolationColorCount multiplied by sizeof(REAL).

Example Code [C++]

The following example creates a PathGradientBrush object from a triangular path. The code sets the preset colors to red, blue, and aqua and sets the blend positions to 0, 0.6, and 1. The code calls the GetInterpolationColorCount method of the PathGradientBrush object to obtain the number of preset colors currently set for the brush. Next, the code allocates two buffers: one to hold the array of preset colors, and one to hold the array of blend positions. The call to the GetInterpolationColors method of the PathGradientBrush object fills the buffers with the preset colors and the blend positions. Finally the code fills a small square with each of the preset colors.

VOID Example_GetInterpColors(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path gradient brush from an array of points, and
   // set the interpolation colors for that brush.

   Point points[] = {Point(100, 0), Point(200, 200), Point(0, 200)};
   PathGradientBrush pthGrBrush(points, 3);

   Color col[] = {
      Color(255, 255, 0, 0),     // red
      Color(255, 0, 0, 255),     // blue
      Color(255, 0, 255, 255)};  // aqua

   REAL pos[] = {
      0.0f,    // red at the boundary
      0.6f,    // blue 60 percent of the way from the boundary to the center
      1.0f};   // aqua at the center

   pthGrBrush.SetInterpolationColors(col, pos, 3);

   // Obtain information about the path gradient brush.
   INT colorCount = pthGrBrush.GetInterpolationColorCount();
   Color* colors = new Color[colorCount];
   REAL* positions = new REAL[colorCount];
   pthGrBrush.GetInterpolationColors(colors, positions, colorCount);

   // Fill a small square with each of the interpolation colors.
   SolidBrush solidBrush(Color(255, 255, 255, 255));

   for(INT j = 0; j < colorCount; ++j)
   {
      solidBrush.SetColor(colors[j]);
      graphics.FillRectangle(&solidBrush, 15*j, 0, 10, 10);
   }

   delete [] colors;
   delete [] positions;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Color, GetInterpolationColorCount, SetInterpolationColors
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::GetPointCount()

The GetPointCount method gets the number of points in the array of points that defines this brush's boundary path.

INT GetPointCount(void);

Parameters

This method has no parameters.

Return Values

This method returns the number of points in the array of points that defines this brush's boundary path.

Example Code [C++]

The following example creates a PathGradientBrush object based on an array of three points. Then the code calls the GetPointCount method of the PathGradientBrush object to obtain the number of points in the array that defines the brush's boundary path.

// Create a path gradient brush based on an array of points.
Point pts[] = {Point(20, 20), Point(100, 20), Point(100, 100)};
PathGradientBrush pthGrBrush(pts, 3);

// Obtain information about the path gradient brush.
INT pointCount = 0;
pointCount = pthGrBrush.GetPointCount();

// Now pointCount is equal to 3.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, Point
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::GetRectangle Methods

This topic lists the GetRectangle methods of the PathGradientBrush class. For a complete list of methods for the PathGradientBrush class listing, see PathGradientBrush Methods.

  • GetRectangle(Rect* rect)
  • GetRectangle(RectF* rect)


PathGradientBrush::GetRectangle(Rect* rect)

The GetRectangle method gets the smallest rectangle that encloses the boundary path of this path gradient brush.

Status GetRectangle(
  Rect* rect
);

Parameters

rect
[out] Pointer to a Rect object that receives the bounding rectangle.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a PathGradientBrush object based on a polygon that is defined by four points. The code calls the GetRectangle method of the PathGradientBrush object to obtain the smallest rectangle that encloses the brush's boundary path. The code calls the FillRectangle method of a Graphics object, passing the address of the PathGradientBrush object and a reference to the brush's bounding rectangle. That call fills only the portion of the bounding rectangle that is inside the brush's boundary path. Finally the code draws the outline of the bounding rectangle.

VOID Example_GetRect(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0));

   // Create a path gradient brush based on an array of points.
   Point points[] = {
      Point(30, 20),
      Point(150, 40),
      Point(100, 100),
      Point(60, 200) };

   PathGradientBrush pthGrBrush(points, 4);

   // Obtain information about the path gradient brush.
   Rect rect;
   pthGrBrush.GetRectangle(&rect);

   graphics.FillRectangle(&pthGrBrush, rect);
   graphics.DrawRectangle(&pen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, Rect
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
About GDI+:
Brushes and Filled Shapes


PathGradientBrush::GetRectangle(RectF* rect)

The GetRectangle method gets the smallest rectangle that encloses the boundary path of this path gradient brush.

Status GetRectangle(
  RectF* rect
);

Parameters

rect
[out] Pointer to a RectF object that receives the bounding rectangle.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a PathGradientBrush object based on a polygon that is defined by four points. The code calls the GetRectangle method of the PathGradientBrush object to obtain the smallest rectangle that encloses the brush's boundary path. The code calls the FillRectangle method of a Graphics object, passing the address of the PathGradientBrush object and a reference to the brush's bounding rectangle That call fills only the portion of the bounding rectangle that is inside the brush's boundary path. Finally the code draws the outline of the bounding rectangle.

VOID Example_GetRect(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0));

   // Create a path gradient brush based on an array of points.
   Point points[] = {
      Point(30, 20),
      Point(150, 40),
      Point(100, 100),
      Point(60, 200) };

   PathGradientBrush pthGrBrush(points, 4);

   // Obtain information about the path gradient brush.
   RectF rect;
   pthGrBrush.GetRectangle(&rect);

   graphics.FillRectangle(&pthGrBrush, rect);
   graphics.DrawRectangle(&pen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, RectF
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::GetSurroundColorCount()

The GetSurroundColorCount method gets the number of colors that have been specified for the boundary path of this path gradient brush.

INT GetSurroundColorCount(void);

Parameters

This method has no parameters.

Return Values

This method returns the number of colors that have been specified for the boundary path of this path gradient brush.

Example Code [C++]

The following example creates a PathGradientBrush object based on a triangular path that is defined by an array of three points. The code calls the SetSurroundColors method of the PathGradientBrush object to specify a color for each of the points that define the triangle. The GetSurroundColorCount method determines the current number of surround colors (the colors specified for the brush's boundary path). Next, the code allocates a buffer large enough to receive the array of surround colors and calls GetSurroundColors to fill that buffer. Finally the code fills a small square with each of the brush's surround colors.

VOID Example_GetSurColors(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path gradient brush and set its surround colors.
   Point pts[] = {
      Point(20, 20),
      Point(100, 20),
      Point(100, 100)};

   Color cols[] = {
      Color(255, 255, 0, 0),  // red
      Color(255, 0, 255, 0),  // green
      Color(255, 0, 0, 0)};   // black

   INT count = 3;
   PathGradientBrush pthGrBrush(pts, 3);
   pthGrBrush.SetSurroundColors(cols, &count);

   // Obtain information about the path gradient brush.
   INT colorCount = pthGrBrush.GetSurroundColorCount();
   Color* colors = new Color[colorCount];
   pthGrBrush.GetSurroundColors(colors, &colorCount);

   // Fill a small square with each of the surround colors.
   SolidBrush solidBrush(Color(255, 255, 255, 255));

   for(INT j = 0; j < colorCount; ++j)
   {
      solidBrush.SetColor(colors[j]);
      graphics.FillRectangle(&solidBrush, 15*j, 0, 10, 10);
   }

   delete [] colors;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetSurroundColorCount, GraphicsPath, SetSurroundColors
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::GetSurroundColors(colors, count)

The GetSurroundColors method gets the surround colors currently specified for this path gradient brush.

Status GetSurroundColors(
  Color* colors,
  INT* count
);

Parameters

colors
[in] Pointer to an array that receives the surround colors.
count
[in, out] Pointer to an integer that, on input, specifies the number of colors requested. If the method succeeds, this parameter, on output, receives the number of colors retrieved. If the method fails, this parameter does not receive a value.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A path gradient brush has a boundary path and a center point. The center point is set to a single color, but you can specify different colors for several points on the boundary. For example, suppose you specify red for the center color, and you specify blue, green, and yellow for distinct points on the boundary. Then as you move along the boundary, the color will change gradually from blue to green to yellow and back to blue. As you move along a straight line from any point on the boundary to the center point, the color will change from that boundary point's color to red.

Example Code [C++]

The following example creates a PathGradientBrush object based on a triangular path that is defined by an array of three points. The code calls the SetSurroundColors method of the PathGradientBrush object to specify a color for each of the points that define the triangle. The GetSurroundColorCount method determines the current number of surround colors (the colors specified for the brush's boundary path). Next, the code allocates a buffer large enough to receive the array of surround colors and calls GetSurroundColors to fill that buffer. Finally the code fills a small square with each of the brush's surround colors.

VOID Example_GetSurColors(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path gradient brush and set its surround colors.
   Point pts[] = {
      Point(20, 20),
      Point(100, 20),
      Point(100, 100)};

   Color cols[] = {
      Color(255, 255, 0, 0),  // red
      Color(255, 0, 255, 0),  // green
      Color(255, 0, 0, 0)};   // black

   INT count = 3;
   PathGradientBrush pthGrBrush(pts, 3);
   pthGrBrush.SetSurroundColors(cols, &count);

   // Obtain information about the path gradient brush.
   INT colorCount = pthGrBrush.GetSurroundColorCount();
   Color* colors = new Color[colorCount];
   pthGrBrush.GetSurroundColors(colors, &colorCount);

   // Fill a small square with each of the surround colors.
   SolidBrush solidBrush(Color(255, 255, 255, 255));

   for(INT j = 0; j < colorCount; ++j)
   {
      solidBrush.SetColor(colors[j]);
      graphics.FillRectangle(&solidBrush, 15*j, 0, 10, 10);
   }

   delete [] colors;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Color, GetSurroundColorCount, SetSurroundColors
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::GetTransform(matrix)

The GetTransform method gets transformation matrix of this path gradient brush.

Status GetTransform(
  Matrix* matrix
);

Parameters

matrix
[out] Pointer to a Matrix object that receives the transformation matrix.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A PathGradientBrush object maintains a transformation matrix that can store any affine transformation. When you use a path gradient brush to fill an area, GDI+ transforms the brush's boundary path according to the brush's transformation matrix and then fills the interior of the transformed path. The transformed path exists only during rendering; the boundary path stored in PathGradientBrush object is not transformed.

Example Code [C++]

The following example creates a PathGradientBrush object based on an array of three points. The ScaleTransform and TranslateTransform methods set the elements of the brush's transformation matrix so that the matrix represents a composite transformation (first scale, then translate). That composite transformation applies to the brush's boundary path, so the call to FillRectangle fills the interior of a triangle that is the result of scaling and translating the boundary path. The code calls the GetTransform method of the PathGradientBrush object to obtain the brush's transformation matrix and then calls the GetElements method of the retrieved Matrix object to fill an array with the matrix elements.

VOID Example_GetTransform(HDC hdc)
{
  Graphics graphics(hdc);

   // Create a path gradient brush and set its transformation.
   Point pts[] = {Point(0, 0), Point(50, 0), Point(50, 50)};
   PathGradientBrush pthGrBrush(pts, 3);
   pthGrBrush.ScaleTransform(3.0f, 1.0f);
   pthGrBrush.TranslateTransform(10.0f, 30.0f, MatrixOrderAppend);

   graphics.FillRectangle(&pthGrBrush, 0, 0, 200, 200);

   // Obtain information about the path gradient brush.
   Matrix matrix;
   REAL elements[6];

   pthGrBrush.GetTransform(&matrix);
   matrix.GetElements(elements);

   for(INT j = 0; j <= 5; ++j)
   {
      // Inspect or use the value in elements[j].
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Matrix, SetTransform
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


PathGradientBrush::GetWrapMode()

The GetWrapMode method gets the wrap mode currently set for this path gradient brush.

WrapMode GetWrapMode(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the WrapMode enumeration that indicates the wrap mode currently set for this path gradient brush.

Remarks

The bounding rectangle of a path gradient brush is the smallest rectangle that encloses the brush's boundary path. When you paint the bounding rectangle with the path gradient brush, only the area inside the boundary path gets filled. The area inside the bounding rectangle but outside the boundary path does not get filled.

The default wrap mode for a path gradient brush is WrapModeClamp, which indicates that no painting occurs outside of the brush's bounding rectangle. All of the other wrap modes indicate that areas outside the brush's bounding rectangle will be tiled. Each tile is a copy (possibly flipped) of the filled path inside its bounding rectangle.

Example Code [C++]

The following example creates a PathGradientBrush object based on a triangular path. The code calls the SetWrapMode method of the PathGradientBrush object to set the wrap mode to WrapModeTileFlipX. Next, the code calls the GetWrapMode method of the PathGradientBrush object to obtain the brush's wrap mode. If the obtained wrap mode is WrapModeTileFlipX, the code calls Graphics::FillRectangle to tile a large area with the path gradient brush.

VOID Example_GetWrapMode(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path gradient brush based on an array of points,
   // and set its wrap mode.
   Point points[] = {
      Point(0, 0),
      Point(100, 0),
      Point(100, 100)};

   Color colors[] = {
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255),   // blue
      Color(255, 0, 255, 0)};  // green

   INT count = 3;

   PathGradientBrush pthGrBrush(points, 3);
   pthGrBrush.SetSurroundColors(colors, &count);
   pthGrBrush.SetWrapMode(WrapModeTileFlipX);

   // Obtain information about the path gradient brush.
   WrapMode wrapMode;
   wrapMode = pthGrBrush.GetWrapMode();

   if(wrapMode == WrapModeTileFlipX)
         graphics.FillRectangle(&pthGrBrush, 0, 0, 800, 800);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
SetWrapMode
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient, Tiling a Shape with an Image
Concepts
Brushes and Filled Shapes


PathGradientBrush::MultiplyTransform(matrix, order)

TheMultiplyTransform method updates the brush's transformation matrix with the product of itself and another matrix.

Status MultiplyTransform(
  Matrix* matrix,
  MatrixOrder order
);

Parameters

matrix
[in] Pointer to the matrix that will be multiplied by the brush's current transformation matrix.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the passed matrix is on the left, and MatrixOrderAppend specifies that the passed matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A single 3×3 matrix can store any sequence of affine transformations. If you have several 3×3 matrices, each of which represents an affine transformation, the product of those matrices is a single 3×3 matrix that represents the entire sequence of transformations. The transformation represented by that product is called a composite transformation. For example, suppose matrix R represents a rotation and matrix T represents a translation. If matrix M is the product RT, then matrix M represents a composite transformation: first rotate, then translate.

The order of matrix multiplication is important. In general, the matrix product RT is not the same as the matrix product TR. In the example given in the previous paragraph, the composite transformation represented by RT (first rotate, then translate) is not the same as the composite transformation represented by TR (first translate, then rotate).

Example Code [C++]

The following example creates a PathGradientBrush object based on a triangular path. The code calls the ScaleTransform method of the PathGradientBrush object to fill the brush's transformation matrix with the elements that represent a horizontal scaling by a factor of 3. Then the code calls the MultiplyTransform method of that same PathGradientBrush object to multiply the brush's existing transformation matrix by a matrix that represents a translation (10 right, 30 down). The MatrixOrderAppend argument indicates that the multiplication is performed with the translation matrix on the right.

After the multiplication, the brush's transformation matrix represents a composite transformation: first scale, then translate. That composite transformation is applied to the brush's boundary path during the call to FillRectangle, so it is the area inside the transformed path that gets painted.

VOID Example_MultiplyTransform(HDC hdc)
{
   Graphics graphics(hdc);
   Point pts[] = {Point(0, 0), Point(50, 0), Point(50, 50)};

   // Translate 10 right, 30 down.
   Matrix matrix(1.0f, 0.0f, 0.0f, 1.0f, 10.0f, 30.0f);

   PathGradientBrush pthGrBrush(pts, 3);
   pthGrBrush.ScaleTransform(3.0f, 1.0f);
   pthGrBrush.MultiplyTransform(&matrix, MatrixOrderAppend);

   graphics.FillRectangle(&pthGrBrush, 0, 0, 200, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference:
GetTransform, Matrix, MatrixOrder, ResetTransform, RotateTransform, ScaleTransform, SetTransform, TranslateTransform
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


PathGradientBrush::ResetTransform()

The ResetTransform method resets the transformation matrix of this path gradient brush to the identity matrix. This means that no transformation will take place.

Status ResetTransform(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a PathGradientBrush object based on a triangular path. The ScaleTransform and TranslateTransform methods set the elements of the brush's transformation matrix so that the matrix represents a composite transformation: first scale, then translate. The code calls the FillRectangle method of a Graphics object to paint a rectangle with the transformed path gradient brush. Then the code calls the ResetTransform method of the PathGradientBrush object to set the brush's transformation matrix to the identity matrix. The code calls FillRectangle a second time to paint the same rectangle with the reset (no transformation) path gradient brush.

VOID Example_ResetTransform(HDC hdc)
{
   Graphics graphics(hdc);

   Point pts[] = {Point(0, 0), Point(50, 0), Point(50, 50)};

   PathGradientBrush pthGrBrush(pts, 3);
   pthGrBrush.ScaleTransform(3.0f, 1.0f);
   pthGrBrush.TranslateTransform(100.0f, 50.0f, MatrixOrderAppend);

   // Fill an area with the transformed path gradient brush.
   graphics.FillRectangle(&pthGrBrush, 0, 0, 500, 500);

   pthGrBrush.ResetTransform();

   // Fill the same area with the path gradient brush (no transformation).
   graphics.FillRectangle(&pthGrBrush, 0, 0, 500, 500);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, MultiplyTransform, RotateTransform, ScaleTransform, SetTransform, TranslateTransform
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


PathGradientBrush::RotateTransform(angle, order)

TheRotateTransform method updates this brush's current transformation matrix with the product of itself and a rotation matrix.

Status RotateTransform(
  REAL angle,
  MatrixOrder order
);

Parameters

angle
[in] Real number that specifies the angle of rotation in degrees.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the rotation matrix is on the left, and MatrixOrderAppend specifies that the rotation matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A single 3×3 matrix can store any sequence of affine transformations. If you have several 3×3 matrices, each of which represents an affine transformation, the product of those matrices is a single 3×3 matrix that represents the entire sequence of transformations. The transformation represented by that product is called a composite transformation. For example, suppose matrix T represents a translation and matrix R represents a rotation. If matrix M is the product TR, then matrix M represents a composite transformation: first translate, then rotate.

Example Code [C++]

The following example creates a PathGradientBrush object based on a triangular path. The calls to the ScaleTransform and RotateTransform methods of the PathGradientBrush object set the elements of the brush's transformation matrix so that it represents a composite transformation: first scale, then rotate. The code uses the path gradient brush twice to paint a rectangle: once before the transformation is set and once after the transformation is set.

VOID Example_RotateTransform(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path gradient brush based on an array of points.
   Point pts[] = {Point(0, 0), Point(50, 0), Point(50, 50)};
   PathGradientBrush pthGrBrush(pts, 3);

   // Fill an area with the path gradient brush (no transformation).
   graphics.FillRectangle(&pthGrBrush, 0, 0, 500, 500);

   pthGrBrush.ScaleTransform(3.0f, 1.0f);                 // first scale
   pthGrBrush.RotateTransform(60.0f, MatrixOrderAppend);  // then rotate

   // Fill the same area with the transformed path gradient brush.
   graphics.FillRectangle(&pthGrBrush, 0, 0, 500, 500);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, MultiplyTransform, ResetTransform, ScaleTransform, SetTransform, TranslateTransform
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


PathGradientBrush::ScaleTransform(sx, sy, order)

The ScaleTransform method updates this brush's current transformation matrix with the product of itself and a scaling matrix.

Status ScaleTransform(
  REAL sx,
  REAL sy,
  MatrixOrder order
);

Parameters

sx
[in] Real number that specifies the horizontal scale factor.
sy
[in] Real number that specifies the vertical scale factor.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the scaling matrix is on the left, and MatrixOrderAppend specifies that the scaling matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A single 3×3 matrix can store any sequence of affine transformations. If you have several 3×3 matrices, each of which represents an affine transformation, the product of those matrices is a single 3×3 matrix that represents the entire sequence of transformations. The transformation represented by that product is called a composite transformation. For example, suppose matrix T represents a translation and matrix S represents a scaling. If matrix M is the product TS, then matrix M represents a composite transformation: first translate, then scale.

Example Code [C++]

The following example creates a PathGradientBrush object based on a triangular path. The calls to the TranslateTransform and ScaleTransform methods of the PathGradientBrush object set the elements of the brush's transformation matrix so that it represents a composite transformation: first translate, then scale. The code uses the path gradient brush twice to paint a rectangle: once before the transformation is set and once after the transformation is set.

VOID Example_ScaleTransform(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path gradient brush based on an array of points.
   Point pts[] = {Point(0, 0), Point(50, 0), Point(50, 50)};
   PathGradientBrush pthGrBrush(pts, 3);

   // Fill an area with the path gradient brush (no transformation).
   graphics.FillRectangle(&pthGrBrush, 0, 0, 500, 500);

   pthGrBrush.TranslateTransform(50.0f, 40.0f);               // translate
   pthGrBrush.ScaleTransform(3.0f, 2.0f, MatrixOrderAppend);  // then scale

   // Fill the same area with the transformed path gradient brush.
   graphics.FillRectangle(&pthGrBrush, 0, 0, 500, 500);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, MultiplyTransform, ResetTransform, RotateTransform, SetTransform, TranslateTransform
Task and Examples:
Creating a Path Gradient, Filling a Shape with a Color Gradient, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


PathGradientBrush::SetBlend(blendFactors, blendPositions, count)

The SetBlend method sets the blend factors and the blend positions of this path gradient brush.

Status SetBlend(
  REAL* blendFactors,
  REAL* blendPositions,
  INT count
);

Parameters

blendFactors
[in] Pointer to an array of blend factors. Each number in the array should be in the range 0 through 1.
blendPositions
[in] Pointer to an array of blend positions. Each number in the array should be in the range 0 through 1.
count
[in] Integer that specifies the number of elements in the blendFactors array. This is the same as the number of elements in the blendPositions array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A PathGradientBrush object has a boundary path and a center point. When you fill an area with a path gradient brush, the color changes gradually as you move from the boundary path to the center point. By default, the color is linearly related to the distance, but you can customize the relationship between color and distance by calling the SetBlend method.

Example Code [C++]

The following example creates a PathGradientBrush object based on an ellipse. The code calls the SetBlend method of the PathGradientBrush object to establish a set of blend factors and blend positions for the brush. Then the code uses the path gradient brush to fill the ellipse.

VOID Example_SetBlend(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that consists of a single ellipse.
   GraphicsPath path;
   path.AddEllipse(0, 0, 200, 100);

   // Use the path to construct a brush.
   PathGradientBrush pthGrBrush(&path);

   // Set the color at the center of the path to blue.
   pthGrBrush.SetCenterColor(Color(255, 0, 0, 255));

   // Set the color along the entire boundary of the path to aqua.
   Color colors[] = {Color(255, 0, 255, 255)};
   INT count = 1;
   pthGrBrush.SetSurroundColors(colors, &count);

   // Set blend factors and positions for the path gradient brush.
   REAL fac[] = {
      0.0f,
      0.4f,     // 40 percent of the way from aqua to blue
      0.8f,     // 80 percent of the way from aqua to blue
      1.0f};

   REAL pos[] = {
      0.0f,
      0.3f,   // 30 percent of the way from the boundary to the center
      0.7f,   // 70 percent of the way from the boundary to the center
      1.0f};

   pthGrBrush.SetBlend(fac, pos, 4);

   // Fill the ellipse with the path gradient brush.
   graphics.FillEllipse(&pthGrBrush, 0, 0, 200, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Color, GetBlend, GetBlendCount, GraphicsPath
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::SetBlendBellShape(focus, scale)

The SetBlendBellShape method sets the blend shape of this path gradient brush.

Status SetBlendBellShape(
  REAL focus,
  REAL scale
);

Parameters

focus
[in] Real number that specifies where the center color will be at its highest intensity. This number must be in the range 0 through 1.
scale
[in] Optional. Real number that specifies the maximum intensity of center color that gets blended with the boundary color. This number must be in the range 0 through 1. The default value is 1.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

By default, as you move from the boundary of a path gradient to the center point, the color changes gradually from the boundary color to the center color. You can customize the positioning and blending of the boundary and center colors by calling the SetBlendBellShape method.

Example Code [C++]

The following example creates a PathGradientBrush object based on an ellipse. The code calls the SetBlendBellShape method of the PathGradientBrush object, passing a focus of 0.2 and a scale of 0.7. Then the code uses the path gradient brush to paint a rectangle that contains the ellipse.

VOID Example_SetBlendShape(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that consists of a single ellipse.
   GraphicsPath path;
   path.AddEllipse(0, 0, 200, 100);

   // Use the path to construct a brush.
   PathGradientBrush pthGrBrush(&path);

   // Set the color at the center of the path to red.
   pthGrBrush.SetCenterColor(Color(255, 255, 0, 0));

   // Set the color along the entire boundary of the path to blue.
   Color colors[] = {Color(255, 0, 0, 255)};
   INT count = 1;
   pthGrBrush.SetSurroundColors(colors, &count);

   pthGrBrush.SetBlendBellShape(0.2f, 0.7f);

   // The color is blue on the boundary and at the center.
   // At points that are 20 percent of the way from the boundary to the
   // center, the color is 70 percent red and 30 percent blue.

   graphics.FillRectangle(&pthGrBrush, 0, 0, 300, 300);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Color, GetBlend, GetBlendCount, GraphicsPath SetBlend, SetBlendTriangularShape
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::SetBlendTriangularShape(focus, scale)

The SetBlendTriangularShape method sets the blend shape of this path gradient brush.

Status SetBlendTriangularShape(
  REAL focus,
  REAL scale
);

Parameters

focus
[in] Real number that specifies where the center color will be at its highest intensity. This number must be in the range 0 through 1.
scale
[in] Optional. Real number that specifies the maximum intensity of center color that gets blended with the boundary color. This number must be in the range 0 through 1. The default value is 1.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

By default, as you move from the boundary of a path gradient to the center point, the color changes gradually from the boundary color to the center color. You can customize the positioning and blending of the boundary and center colors by calling the SetBlendTriangularShape method.

Example Code [C++]

The following example creates a PathGradientBrush object based on an ellipse. The code calls the SetBlendTriangularShape method of the PathGradientBrush object, passing a focus of 0.2 and a scale of 0.7. Then the code uses the path gradient brush to paint a rectangle that contains the ellipse.

VOID Example_SetBlendShape(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that consists of a single ellipse.
   GraphicsPath path;
   path.AddEllipse(0, 0, 200, 100);

   // Use the path to construct a brush.
   PathGradientBrush pthGrBrush(&path);

   // Set the color at the center of the path to red.
   pthGrBrush.SetCenterColor(Color(255, 255, 0, 0));

   // Set the color along the entire boundary of the path to blue.
   Color colors[] = {Color(255, 0, 0, 255)};
   INT count = 1;
   pthGrBrush.SetSurroundColors(colors, &count);

   pthGrBrush.SetBlendTriangularShape(0.2f, 0.7f);

   // The color is blue on the boundary and at the center.
   // At points that are 20 percent of the way from the boundary to the
   // center, the color is 70 percent red and 30 percent blue.

   graphics.FillRectangle(&pthGrBrush, 0, 0, 300, 300);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Color, GetBlend, GetBlendCount, GraphicsPath, SetBlend, SetBlendBellShape
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::SetCenterColor(color)

The SetCenterColor method sets the center color of this path gradient brush. The center color is the color that appears at the brush's center point.

Status SetCenterColor(
  const Color& color
);

Parameters

color
[in] Reference to a Color object that specifies the center color.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

By default the center point is the centroid of the brush's boundary path, but you can set the center point to any location inside or outside the path.

Example Code [C++]

The following example creates a PathGradientBrush object based on an ellipse. The code calls the SetCenterColor method of the PathGradientBrush object to set the center color to blue. The SetSurroundColors method sets the color along the entire boundary to aqua. The Graphics::FillRectangle method uses the path gradient brush to paint a rectangle that contains the ellipse.

VOID Example_SetCenter(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that consists of a single ellipse.
   GraphicsPath path;
   path.AddEllipse(0, 0, 200, 100);

   // Use the path to construct a brush.
   PathGradientBrush pthGrBrush(&path);

   // Set the color at the center of the path to blue.
   pthGrBrush.SetCenterColor(Color(255, 0, 0, 255));

   // Set the color along the entire boundary of the path to aqua.
   Color colors[] = {Color(255, 0, 255, 255)};
   INT count = 1;
   pthGrBrush.SetSurroundColors(colors, &count);

   graphics.FillRectangle(&pthGrBrush, 0, 0, 300, 300);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Color, GetCenterColor, GetCenterPoint Methods, GraphicsPath, SetCenterPoint Methods
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::SetCenterPoint Methods

This topic lists the SetCenterPoint methods of the PathGradientBrush class. For a complete list of methods for the PathGradientBrush class, see PathGradientBrush Methods.

  • SetCenterPoint(Point& point)
  • SetCenterPoint(PointF& point)


PathGradientBrush::SetCenterPoint(Point& point)

The SetCenterPoint method sets the center point of this path gradient brush. By default, the center point is at the centroid of the brush's boundary path, but you can set the center point to any location inside or outside the path.

Status SetCenterPoint(
  const Point& point
);

Parameters

point
[in] Reference to a Point object that specifies the center point.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a PathGradientBrush object based on an ellipse. The code sets the center color to blue and sets the color along the boundary to aqua. By default, the center point would be at the center of the ellipse (100, 50), but the call to the SetCenterPoint method sets the center point to (180, 50).

VOID Example_SetCenter(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that consists of a single ellipse.
   GraphicsPath path;
   path.AddEllipse(0, 0, 200, 100);

   // Use the path to construct a brush.
   PathGradientBrush pthGrBrush(&path);

   // Set the color at the center of the path to blue.
   pthGrBrush.SetCenterColor(Color(255, 0, 0, 255));

   // Set the center point.
   pthGrBrush.SetCenterPoint(Point(180, 50));

   // Set the color along the entire boundary of the path to aqua.
   Color colors[] = {Color(255, 0, 255, 255)};
   INT count = 1;
   pthGrBrush.SetSurroundColors(colors, &count);

   graphics.FillRectangle(&pthGrBrush, 0, 0, 300, 300);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetCenterColor, GetCenterPoint Methods, GraphicsPath, SetCenterColor
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::SetCenterPoint(PointF& point)

The SetCenterPoint method sets the center point of this path gradient brush. By default, the center point is at the centroid of the brush's boundary path, but you can set the center point to any location inside or outside the path.

Status SetCenterPoint(
  const PointF& point
);

Parameters

point
[in] Reference to a PointF object that specifies the center point.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a PathGradientBrush object based on an ellipse. The code sets the center color to blue and sets the color along the boundary to aqua. By default, the center point would be at the center of the ellipse (100, 50), but the call to the SetCenterPoint method sets the center point to (180.5, 50.0).

VOID Example_SetCenter(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a path that consists of a single ellipse.
   GraphicsPath path;
   path.AddEllipse(0, 0, 200, 100);

   // Use the path to construct a brush.
   PathGradientBrush pthGrBrush(&path);

   // Set the color at the center of the path to blue.
   pthGrBrush.SetCenterColor(Color(255, 0, 0, 255));

   // Set the center point.
   pthGrBrush.SetCenterPoint(PointF(180.5f, 50.0f));

   // Set the color along the entire boundary of the path to aqua.
   Color colors[] = {Color(255, 0, 255, 255)};
   INT count = 1;
   pthGrBrush.SetSurroundColors(colors, &count);

   graphics.FillRectangle(&pthGrBrush, 0, 0, 300, 300);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetCenterColor, GetCenterPoint Methods, GraphicsPath, SetCenterColor
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::SetFocusScales(xScale, yScale)

The SetFocusScales method sets the focus scales of this path gradient brush.

Status SetFocusScales(
  REAL xScale,
  REAL yScale
);

Parameters

xScale
[in] Real number that specifies the x focus scale.
yScale
[in] Real number that specifies the y focus scale.

Remarks

By default, the center color of a path gradient is at the center point. By calling SetFocusScales, you can specify that the center color should appear along a path that surrounds the center point. That path is the boundary path scaled by a factor of xScale in the x direction and by a factor of yScale in the y direction. The area inside the scaled path is filled with the center color.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a PathGradientBrush object based on a triangular path. The code calls the SetFocusScales method of the PathGradientBrush object to set the brush's focus scales to (0.2, 0.2). Then the code uses the path gradient brush to paint a rectangle that includes the triangular path.

VOID Example_SetFocusScales(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {Point(100, 0), Point(200, 200), Point(0, 200)};

   // No GraphicsPath object is created. The PathGradientBrush
   // object is constructed directly from the array of points.
   PathGradientBrush pthGrBrush(points, 3);

   Color colors[] = {
      Color(255, 255, 0, 0),    // red
      Color(255, 0, 0, 255)};   // blue

   REAL relativePositions[] = {
      0.0f,    // red at the boundary of the outer triangle
      1.0f};   // blue at the boundary of the inner triangle

   pthGrBrush.SetInterpolationColors(colors, relativePositions, 2);

   // The inner triangle is formed by scaling the outer triangle
   // about its centroid. The scaling factor is 0.2 in both
   // the x and y directions.
   pthGrBrush.SetFocusScales(0.2f, 0.2f);

   // Fill a rectangle that is larger than the triangle
   // specified in the Point array. The portion of the
   // rectangle outside the triangle will not be painted.
   graphics.FillRectangle(&pthGrBrush, 0, 0, 200, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetFocusScales, SetInterpolationColors
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::SetGammaCorrection(useGammaCorrection)

The SetGammaCorrection method specifies whether gamma correction is enabled for this path gradient brush.

Status SetGammaCorrection(
  BOOL useGammaCorrection
);

Parameters

useGammaCorrection
[in] Boolean value that specifies whether gamma correction is enabled. TRUE specifies that gamma correction is enabled, and FALSE specifies that gamma correction is not enabled.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetGammaCorrection
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::SetGraphicsPath(path)

The SetGraphicsPath method is not implemented in GDI+ version 1.0.

Status SetGraphicsPath(
  const GraphicsPath* path
);

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.


PathGradientBrush::SetInterpolationColors(presetColors, blendPositions, count)

The SetInterpolationColors method sets the preset colors and the blend positions of this path gradient brush.

Status SetInterpolationColors(
  const Color* presetColors,
  REAL* blendPositions,
  INT count
);

Parameters

presetColors
[in] Pointer to an array of Color objects that specifies the interpolation colors for the gradient. A color of a given index in the presetColors array corresponds to the blend position of that same index in the blendPositions array.
blendPositions
[in] Pointer to an array that specifies the blend positions. Each blend position is a number from 0 through 1, where 0 indicates the boundary of the gradient and 1 indicates the center point. A blend position between 0 and 1 specifies the set of all points that are a certain fraction of the distance from the boundary to the center point. For example, a blend position of 0.7 specifies the set of all points that are 70 percent of the way from the boundary to the center point.
count
[in] Integer that specifies the number of Color objects in the presetColors array. This is the same as the number of elements in the blendPositions array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other members of the Status enumeration.

Remarks

A simple path gradient brush has two colors: a boundary color and a center color. When you paint with such a brush, the color changes gradually from the boundary color to the center color as you move from the boundary path to the center point. You can create a more complex gradient by specifying an array of preset colors and an array of blend positions.

Example Code [C++]

The following example creates a PathGradientBrush object based on a triangular path. The SetInterpolation method sets the brush's preset colors to red, blue, and aqua and sets the blend positions to 0, 0, 4, and 1. The Graphics::FillRectangle method uses the path gradient brush to paint a rectangle that contains the triangular path.

VOID Example_SetInterpColors(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {Point(100, 0), Point(200, 200), Point(0, 200)};
   PathGradientBrush pthGrBrush(points, 3);

   Color col[] = {
      Color(255, 255, 0, 0),     // red
      Color(255, 0, 0, 255),     // blue
      Color(255, 0, 255, 255)};  // aqua

   REAL pos[] = {
      0.0f,    // red at the boundary
      0.4f,    // blue 40 percent of the way from the boundary to the center
      1.0f};   // aqua at the center

   pthGrBrush.SetInterpolationColors(col, pos, 3);
   graphics.FillRectangle(&pthGrBrush, 0, 0, 300, 300);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Color, GetInterpolationColors
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::SetSurroundColors(colors, count)

The SetSurroundColors method sets the surround colors of this path gradient brush. The surround colors are colors specified for discrete points on the brush's boundary path.

Status SetSurroundColors(
  const Color* colors,
  INT* count
);

Parameters

colors
[in] Pointer to an array of Color objects that specify the surround colors.
count
[in, out] Pointer to an integer that, on input, specifies the number of Color objects in the colors array. If the method succeeds, this parameter, on output, receives the number of surround colors set. If the method fails, this parameter does not receive a value.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A path gradient brush has a boundary path and a center point. The center point is set to a single color, but you can specify different colors for several points on the boundary. For example, suppose you specify red for the center color, and you specify blue, green, and yellow for distinct points on the boundary. Then as you move along the boundary, the color will change gradually from blue to green to yellow and back to blue. As you move along a straight line from any point on the boundary to the center point, the color will change from that boundary point's color to red.

Example Code [C++]

The following example creates a PathGradientBrush object based on an array of three points that defines a triangular path. The code also initializes an array of three Color objects. The call to the SetSurroundColors method associates each color in the color array with the corresponding (same index) point in the point array. After the surround colors of the path gradient brush have been set, the Graphics::FillRectangle method uses the path gradient brush to paint a rectangle that includes the triangular path.

One edge of the rendered triangle changes gradually from red to green. The next edge changes gradually from green to black, and the third edge changes gradually from black to red. The code does not set the center color, so the center color has the default value of black. As you move along a straight line from any point on the boundary path (triangle) to the center point, the color changes gradually from that boundary point's color to black.

VOID Example_SetSurColor(HDC hdc)
{
   Graphics graphics(hdc);

   Point pts[] = {
      Point(20, 20),
      Point(100, 20),
      Point(100, 100)};

   Color cols[] = {
      Color(255, 255, 0, 0),  // red
      Color(255, 0, 255, 0),  // green
      Color(255, 0, 0, 0)};   // black

   INT count = 3;
   PathGradientBrush pthGrBrush(pts, 3);
   pthGrBrush.SetSurroundColors(cols, &count);

   graphics.FillRectangle(&pthGrBrush, 0, 0, 200, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
Color, GetSurroundColorCount, GetSurroundColors
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::SetTransform(matrix)

The SetTransform method sets the transformation matrix of this path gradient brush.

Status SetTransform(
  const Matrix* matrix
);

Parameters

matrix
[in] Pointer to a Matrix object that specifies the transformation matrix.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A PathGradientBrush object has a GraphicsPath object that serves as the boundary path for the brush. When you paint with a path gradient brush, only the area inside the boundary path is filled. If the brush's transformation matrix is set to represent any transformation other than the identity, then the boundary path is transformed according to that matrix during rendering, and only the area inside the transformed path is filled.

The transformation applies only during rendering. The boundary path stored by the PathGradientBrush object is not altered by the SetTransform method.

Example Code [C++]

The following example creates a PathGradientBrush object based on a triangular path. The Graphics::FillRectangle method uses the path gradient brush to paint a rectangle that contains the triangular path. Next, the code creates a Matrix object that represents a composite transformation (rotate, then translate) and passes the address of that Matrix object to the SetTransform method of the PathGradientBrush object. The code calls FillRectangle a second time to paint the same rectangle using the transformed path gradient brush.

VOID Example_SetTransform(HDC hdc)
{
   Graphics graphics(hdc);

   Point pts[] = {
      Point(0, 0),
      Point(100, 0),
      Point(100, 100)};

   Color cols[] = {
      Color(255, 255, 0, 0),  // red
      Color(255, 0, 255, 0),  // green
      Color(255, 0, 0, 0)};   // black

   INT count = 3;
   PathGradientBrush pthGrBrush(pts, 3);
   pthGrBrush.SetSurroundColors(cols, &count);

   // Fill an area with the path gradient brush (no transformation).
   graphics.FillRectangle(&pthGrBrush, 0, 0, 200, 200);

   // Set the transformation for the brush (rotate, then translate).
   Matrix matrix(0.0f, 1.0f, -1.0f, 0.0f, 150.0f, 60.0f);
   pthGrBrush.SetTransform(&matrix);

   // Fill the same area with the transformed path gradient brush.
   graphics.FillRectangle(&pthGrBrush, 0, 0, 200, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetTransform, GraphicsPath, MultiplyTransform, ResetTransform, RotateTransform, ScaleTransform, TranslateTransform
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::SetWrapMode(wrapMode)

The SetWrapMode method sets the wrap mode of this path gradient brush.

Status SetWrapMode(
  WrapMode wrapMode
);

Parameters

wrapMode
[in] Element of the WrapMode enumeration that specifies how areas painted with the path gradient brush will be tiled. The default value is WrapModeClamp.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The bounding rectangle of a path gradient brush is the smallest rectangle that encloses the brush's boundary path. When you paint the bounding rectangle with the path gradient brush, only the area inside the boundary path gets filled. The area inside the bounding rectangle but outside the boundary path does not get filled.

WrapModeClamp (the default wrap mode) indicates that no painting occurs outside of the brush's bounding rectangle. All of the other wrap modes indicate that areas outside the brush's bounding rectangle will be tiled. Each tile is a copy (possibly flipped) of the filled path inside its bounding rectangle.

Example Code [C++]

The following example creates a PathGradientBrush object based on a triangular path. The code calls the SetWrapMode method of the PathGradientBrush object to set the brush's wrap mode to WrapModeTileFlipX. The Graphics::FillRectangle method uses the path gradient brush to tile a large area.

The output of the code is a grid of tiles. As you move from one tile to the next in a given row, the image (filled boundary path inside the bounding rectangle) is flipped horizontally.

VOID Example_SetWrapMode(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(0, 0),
      Point(100, 0),
      Point(100, 100)};

   Color colors[] = {
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255),   // blue
      Color(255, 0, 255, 0)};  // green

   INT count = 3;

   PathGradientBrush pthGrBrush(points, 3);
   pthGrBrush.SetSurroundColors(colors, &count);
   pthGrBrush.SetWrapMode(WrapModeTileFlipX);

   graphics.FillRectangle(&pthGrBrush, 0, 0, 800, 800);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetWrapMode, SetWrapMode
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient
Concepts
Brushes and Filled Shapes


PathGradientBrush::TranslateTransform(dx, dy, order)

The TranslateTransform method updates this brush's current transformation matrix with the product of itself and a translation matrix.

Status TranslateTransform(
  REAL dx,
  REAL dy,
  MatrixOrder order
);

Parameters

dx
[in] Real number that specifies the horizontal component of the translation.
dy
[in] Real number that specifies the vertical component of the translation.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the translation matrix is on the left, and MatrixOrderAppend specifies that the translation matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A single 3×3 matrix can store any sequence of affine transformations. If you have several 3×3 matrices, each of which represents an affine transformation, the product of those matrices is a single 3×3 matrix that represents the entire sequence of transformations. The transformation represented by that product is called a composite transformation. For example, suppose matrix S represents a scaling and matrix T represents a translation. If matrix M is the product ST, then matrix M represents a composite transformation: first scale, then translate.

Example Code [C++]

The following example creates a PathGradientBrush object based on a triangular path. The calls to the ScaleTransform and TranslateTransform methods of the PathGradientBrush object set the elements of the brush's transformation matrix so that it represents a composite transformation: first scale, then translate. The code uses the path gradient brush twice to paint a rectangle: once before the transformation is set and once after the transformation is set.

VOID Example_TranslateTrans(HDC hdc)
{
   Graphics graphics(hdc);

   Point pts[] = {Point(0, 0), Point(50, 0), Point(50, 50)};
   PathGradientBrush pthGrBrush(pts, 3);

   // Fill an area with the path gradient brush (no transformation).
   graphics.FillRectangle(&pthGrBrush, 0, 0, 500, 500);

   pthGrBrush.ScaleTransform(3.0f, 1.0f);
   pthGrBrush.TranslateTransform(100.0f, 50.0f, MatrixOrderAppend);

   // Fill the same area with the transformed path gradient brush.
   graphics.FillRectangle(&pthGrBrush, 0, 0, 500, 500);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspath.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, MultiplyTransform, ResetTransform, RotateTransform, ScaleTransform, SetTransform
Tasks and Examples
Creating a Path Gradient, Filling a Shape with a Color Gradient, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


Pen Class

A Pen object is a GDI+ object used to draw lines and curves.

Inheritance

GdiplusBase
Pen

Constructors

Constructor | Description
Pen | Overloaded. Creates and initializes a new Pen object.

Methods

Method | Description
Clone | Copies a Pen object.
GetAlignment | Gets the current alignment setting for a pen.
GetBrush | Gets the brush used to fill a line.
GetColor | Gets the color of the pen.
GetCompoundArray | Gets an array of custom dashes and spaces.
GetCompoundArrayCount | Gets the number of elements in the compound array.
GetCustomEndCap | Gets the custom end cap of a line.
GetCustomStartCap | Gets the custom start cap of a line.
GetDashCap | Gets the dash cap of the dashes in a dashed line.
GetDashOffset | Gets the distance from the start of the line to the start of the first space in a dashed line.
GetDashPattern | Gets an array of custom dashes and spaces.
GetDashPatternCount | Gets the number of elements in a dash pattern array.
GetDashStyle | Gets the dash style of a pen.
GetEndCap | Gets the end cap of a line.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetLineJoin | Gets the join style of two lines that meet.
GetMiterLimit | Gets the miter limit of a Pen object.
GetPenType | Gets the pen type.
GetStartCap | Gets the start cap of a line.
GetTransform | Gets the transformation matrix of a Pen object.
GetWidth | Gets the width of a pen.
MultiplyTransform | Multiplies two matrices of a Pen object.
ResetTransform | Resets the pen transformation to the identity matrix.
RotateTransform | Applies a rotation matrix to a Pen object.
ScaleTransform | Applies a scaling matrix to a Pen object.
SetAlignment | Sets the alignment of a Pen object relative to the stoke that is drawn.
SetBrush | Sets the brush used to fill a stroke.
SetColor | Sets the color of a Pen object.
SetCompoundArray | Sets an array of custom dashes and spaces.
SetCustomEndCap | Sets the cap style at the end of a line.
SetCustomStartCap | Sets a custom start cap of a line.
SetDashCap | Sets the dash cap of the dashes in a dashed line.
SetDashOffset | Sets the distance from the start of the line to the start of the dashes in a dashed line.
SetDashPattern | Sets an array of custom dashes and spaces.
SetDashStyle | Sets the style of the dashes in a dashed line.
SetEndCap | Sets the end cap of a line.
SetLineCap | Sets the end cap of a line.
SetLineJoin | Sets the join style of two lines that join.
SetMiterLimit | Sets the miter limit of a Pen object.
SetStartCap | Sets the start cap of a line.
SetTransform | Sets the transformation matrix of a Pen object.
SetWidth | Sets the width of a Pen object.
~Pen | Pen object destructor.

Remarks

A Pen object has attributes that can be set to adjust the width, color, and style used to draw lines and curves.


Pen Constructors

This topic lists the constructors of the Pen class. For a complete class listing, see Pen Class.

  • Pen(brush, width)
  • Pen(color, width)


Pen::Pen(brush, width)

Creates a Pen object that uses the attributes of a brush and a real number to set the width of this Pen object.

Pen(
  const Brush* brush,
  REAL width
);

Parameters

brush
[in] Pointer to a brush to base this pen on.
width
[in] Optional. Real number that specifies the width of this pen's stroke. The default value is 1.0.

Remarks

If you pass the address of a pen to one of the draw methods of a Graphics object, the width of the pen's stroke is dependent on the unit of measure specified in the Graphics object. The default unit of measure is UnitPixel, which is an element of the Unit enumeration.

Example Code [C++]

The following example creates a Brush object and then creates a Pen object based on the Brush object.

SolidBrush sBrush(Color(255,255,0,0));
Pen pen(&sBrush, 4.0f);

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
Pen Constructors, Brush
Tasks and Examples
Setting Pen Width and Alignment
Concepts
Pens, Lines, and Rectangles


Pen::Pen(color, width)

Creates a Pen object that uses a specified color and width.

Pen(
  const Color& color,
  REAL width
);

Parameters

color
[in] Reference to a Color object that specifies the color for this Pen object.
width
[in] Optional. Real number that specifies the width of this pen's stroke. The default value is 1.0.

Remarks

If you pass the address of a pen to one of the draw methods of a Graphics object, the width of the pen's stroke is dependent on the unit of measure specified in the Graphics object. The default unit of measure is UnitPixel, which is an element of the Unit enumeration.

Example Code [C++]

The following example creates a Pen object with the color red and a width of 4.0.

Pen pen(Color(255,255,0,0), 4.0f);

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
Pen Constructors, Color, SetWidth
Tasks and Examples
Setting Pen Width and Alignment
Concepts
Pens, Lines, and Rectangles


Pen Methods

This topic lists the methods of the Pen class. For a complete class listing, see Pen Class.

  • Clone()
  • GetAlignment()
  • GetBrush()
  • GetColor(color)
  • GetCompoundArray(compoundArray, count)
  • GetCompoundArrayCount()
  • GetCustomEndCap(customCap)
  • GetCustomStartCap(customCap)
  • GetDashCap()
  • GetDashOffset()
  • GetDashPattern(dashArray, count)
  • GetDashPatternCount()
  • GetDashStyle()
  • GetEndCap()
  • GetLastStatus()
  • GetLineJoin()
  • GetMiterLimit()
  • GetPenType()
  • GetStartCap()
  • GetTransform(matrix)
  • GetWidth()
  • MultiplyTransform(matrix, order)
  • ResetTransform()
  • RotateTransform(angle, order)
  • ScaleTransform(sx, sy, order)
  • SetAlignment(penAlignment)
  • SetBrush(brush)
  • SetColor(color)
  • SetCompoundArray(compoundArray, count)
  • SetCustomEndCap(customCap)
  • SetCustomStartCap(customCap)
  • SetDashCap(dashCap)
  • SetDashOffset(dashOffset)
  • SetDashPattern(dashArray, count)
  • SetDashStyle(dashStyle)
  • SetEndCap(endCap)
  • SetLineCap(startCap, endCap, dashCap)
  • SetLineJoin(lineJoin)
  • SetMiterLimit(miterLimit)
  • SetStartCap(startCap)
  • SetTransform(matrix)
  • SetWidth(width)


Pen::Clone()

The Clone method copies a Pen object.

Pen* Clone(void);

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new Pen object.

Example Code [C++]

The following example creates a Pen object, creates a copy of the Pen object, and then draws an ellipse using the copied Pen object.

VOID Example_Clone(HDC hdc)
{
   Graphics graphics(hdc);

   // Create and clone a Pen object.
   Pen pen(Color(255, 0, 0, 255), 4);
   Pen* pPen = pen.Clone();

   // Draw a rectangle using the cloned Pen object.

   graphics.DrawRectangle(pPen, 10, 10, 100, 50);

   delete pPen;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
Pen Methods
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Pen::GetAlignment()

The GetAlignment method gets the alignment currently set for this Pen object.

PenAlignment GetAlignment(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the PenAlignment enumeration that indicates the current alignment setting for this Pen object.

Remarks

The default value of PenAlignment is PenAlignmentCenter.

Example Code [C++]

The following example creates a Pen object, sets the alignment, draws a line, and then gets the pen alignment settings.

VOID Example_GetAlignment(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object and set its alignment.
   Pen pen(Color(255, 0, 255, 0), 15);
   pen.SetAlignment(PenAlignmentCenter);

   // Draw a line.
   graphics.DrawLine(&pen, 0, 0, 100, 50);

   // Obtain information about the Pen object.
   PenAlignment penAlignment;
   penAlignment = pen.GetAlignment();

   if(penAlignment == PenAlignmentCenter)
      ;  // The pixels will be centered on the theoretical line.
   else if(penAlignment == PenAlignmentInset)
      ;  // The pixels will lie inside the filled area  of the theoretical line.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
PenAlignment, SetAlignment
Tasks and Examples
Setting Pen Width and Alignment
Concepts
Pens, Lines, and Rectangles


Pen::GetBrush()

The GetBrush method gets the Brush object that is currently set for this Pen object.

Brush* GetBrush(void);

Parameters

This method has no parameters.

Return Values

This method returns a pointer to a Brush object that is currently used to fill a line.

Example Code [C++]

The following example creates a Brush object, creates a Pen object based on the Brush object, draws a line with the pen, gets the Brush from the pen, and then uses the Brush to fill a rectangle.

VOID Example_GetBrush(HDC hdc)
{
   Graphics graphics(hdc);

    HatchBrush hatchBrush(
      HatchStyleVertical,
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255));  // blue

   // Create a pen based on a hatch brush, and use that pen
   // to draw a line.
   Pen pen(&hatchBrush, 15);
   graphics.DrawLine(&pen, 0, 0, 200, 100);

   // Get the pen's brush, and use that brush to fill a rectangle.
   Brush* pBrush = pen.GetBrush();
   graphics.FillRectangle(pBrush, 0, 100, 200, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
Brush, SetBrush
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


Pen::GetColor(color)

The GetColor method gets the color currently set for this Pen object.

Status GetColor(
  Color* color
);

Parameters

color
[out] Pointer to a Color object that receives the color of this Pen object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Pen object and draws a line. The code then gets the color of the pen and creates a Brush object based on that color. Finally, the code uses the Brush object to fill a rectangle.

VOID Example_GetColor(HDC hdc
{
   Graphics graphics(hdc);

   // Create a pen, and use it to draw a line.
   Pen pen(Color(255, 200, 150, 100), 5);
   graphics.DrawLine(&pen, 0, 0, 200, 100);

   // Get the pen's color, and use that color to create a brush.
   Color color;
   pen.GetColor(&color);
   SolidBrush solidBrush(color);

   // Use the brush to fill a rectangle.
   graphics.FillRectangle(&solidBrush, 0, 100, 200, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
Color, SetColor
Tasks and Examples
Filling a Shape with a Solid Color


Pen::GetCompoundArray(compoundArray, count)

The GetCompoundArray method gets the compound array currently set for this Pen object.

Status GetCompoundArray(
  REAL* compoundArray,
  INT count
);

Parameters

compoundArray
[out] Pointer to an array that receives the compound array.
count
[in] Integer that specifies the number of elements in the compoundArray array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Suppose that a compound array contains the values 0.0, 0.2, 0.7, and 1.0 and that the pen has a width of 100. When you use the pen to draw, you get two parallel lines. The first line has a width of 20, the space between the two lines has a width of 50, and the second line has a width of 30.

For a more complex example, suppose that a compound array contains the values 0.0, 0.2, 0.3, 0.6, 0.85, and 1.0 and that the pen has a width of 100. When you use the pen to draw, you get three parallel lines. The widths of the three lines are 20, 30, and 15 respectively. The widths of the two spaces between the lines are 10 and 15 respectively.

Example Code [C++]

The following example gets the compound array for a Pen object. Assuming that a compound array has been set for this Pen object, the code then gets the entries that have been set for this pen.

INT count = pen.GetCompoundCount();
REAL * distances = new REAL[count];
Status stat = pen.GetCompoundArray(distances, count);

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
SetCompoundArray
Concepts
Pens, Lines, and Rectangles


Pen::GetCompoundArrayCount()

The GetCompoundArrayCount method gets the number of elements in a compound array.

INT GetCompoundArrayCount(void);

Parameters

This method has no parameters.

Return Values

This method returns an integer that indicates the number of elements in the compound array.

Example Code [C++]

The following example declares an array, sets the compound array, draws a line, and gets the number of elements in the compound array.

VOID Example_GetCompoundArray(HDC hdc)
{
   Graphics graphics(hdc);

   REAL compVals[6] = {0.0f, 0.2f, 0.5f, 0.7f, 0.9f, 1.0f};
   Pen pen(Color(255, 0, 0, 0), 30);
   pen.SetCompoundArray(compVals, 6);
   graphics.DrawLine(&pen, 5, 20, 405, 200);

   // Obtain information about the pen.
   INT count = 0;
   REAL* compValues = NULL;

   count = pen.GetCompoundArrayCount();
   compValues = (REAL*)malloc(count*sizeof(REAL));
   pen.GetCompoundArray(compValues, count);

   TraceInt(count);
   for(INT j = 0; j < count; ++j)
   {
      // Inspect or use the value in dashValues[j].
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetCompoundArray, SetCompoundArray
Tasks and Examples
Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::GetCustomEndCap(customCap)

The GetCustomEndCap method gets the custom end cap currently set for this Pen object.

Status GetCustomEndCap(
  CustomLineCap* customCap
);

Parameters

customCap
[out] Pointer to a CustomLineCap object that receives the custom end cap of this Pen object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object and adds a rectangle to it. The code then creates a Pen object, sets the custom end cap using the GraphicsPath object, and draws a line. Finally, the code gets the custom end cap of the pen and creates another Pen object using the same custom end cap. It then draws a second line.

VOID Example_GetCustomEndCap(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a GraphicsPath object and add a rectangle to it.
   GraphicsPath strokePath;
   strokePath.AddRectangle(Rect(-10, -5, 20, 10));

   // Create a pen with a custom end cap.
   Pen pen(Color(255, 0, 0, 255));
   CustomLineCap custCap(NULL, &strokePath);
   pen.SetCustomEndCap(&custCap);

   // Draw a line with a custom end cap.
   graphics.DrawLine(&pen, 0, 0, 200, 100);

   // Obtain the custom end cap for the pen.
   CustomLineCap customLineCap(NULL, NULL);
   pen.GetCustomEndCap(&customLineCap);

   // Create another pen, and use the same custom end cap.
   Pen pen2(Color(255, 0, 255, 0), 3);
   pen2.SetCustomEndCap(&customLineCap);

   // Draw a line using the second pen.
   graphics.DrawLine(&pen2, 0, 100, 200, 150);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetCustomStartCap, GetEndCap, GetStartCap, SetCustomEndCap, SetCustomStartCap
Tasks and Examples
Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::GetCustomStartCap(customCap)

The GetCustomStartCap method gets the custom start cap currently set for this Pen object.

Status GetCustomStartCap(
  CustomLineCap* customCap
);

Parameters

customCap
[out] Pointer to a CustomLineCap object that receives the start cap of this Pen object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object and adds a rectangle to it. The code then creates a Pen object, sets the custom start cap using the GraphicsPath object, and draws a line. Finally, the code gets the custom start cap of the pen and creates another Pen object using the same custom end cap. It then draws a second line.

VOID Example_GetCustomStartCap(HDC hdc)
{
   Graphics graphics(hdc);

   GraphicsPath strokePath;
   strokePath.AddRectangle(Rect(-10, -5, 20, 10));

  // Create a pen with a custom start cap.
   Pen pen(Color(255, 0, 0, 255));
   CustomLineCap custCap(NULL, &strokePath);
   pen.SetCustomStartCap(&custCap);

   graphics.DrawLine(&pen, 50, 50, 200, 100);

   // Obtain the custom start cap for the pen.
   CustomLineCap customLineCap(NULL, NULL);
   pen.GetCustomStartCap(&customLineCap);

   // Create another pen, and use the same custom start cap.
   Pen pen2(Color(255, 0, 255, 0), 3);
   pen2.SetCustomStartCap(&customLineCap);

   graphics.DrawLine(&pen2, 50, 100, 200, 150);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetCustomEndCap, SetCustomEndCap, SetCustomStartCap
Tasks and Examples
Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::GetDashCap()

The GetDashCap method gets the dash cap style currently set for this Pen object.

DashCap GetDashCap(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the DashCap enumeration that indicates the dash cap style currently set for this Pen object.

Example Code [C++]

The following example creates a Pen object, sets the dash cap style, and draws a line. The code then gets the dash cap style of the pen and creates a second Pen object with the same dash cap style. Finally, the code draws a second line using the second pen.

VOID Example_GetDashCap(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a pen with a dash cap.
   Pen pen(Color(255, 0, 0, 255), 15);
   pen.SetDashStyle(DashStyleDash);
   pen.SetDashCap(DashCapRound);

   graphics.DrawLine(&pen, 50, 50, 400, 200);

   // Obtain the dash cap for the pen.
   DashCap dashCap;
   dashCap = pen.GetDashCap();

   // Create another pen, and use the same dash cap.
   Pen pen2(Color(255, 0, 255, 0), 15);
   pen2.SetDashStyle(DashStyleDash);
   pen2.SetDashCap(dashCap);

   // Draw a second line.
   graphics.DrawLine(&pen2, 50, 100, 400, 300);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
DashCap, SetDashCap
Tasks and Examples
Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::GetDashOffset()

The GetDashOffset method gets the distance from the start of the line to the start of the first space in a dashed line.

REAL GetDashOffset(void);

Parameters

This method has no parameters.

Return Values

This method returns a real number that indicates the distance from the start of the line to the start of the dashes.

Remarks

A positive return value shifts the first dash forward along the path, and a negative return value shifts the start of the path forward along the first dash.

Example Code [C++]

The following example assumes that dashPen has been defined with a certain dash style and gets the dash offset value.

REAL dashOffset = dashPen.GetDashOffset();

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
SetDashOffset
Tasks and Examples
Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::GetDashPattern(dashArray, count)

The GetDashPattern method gets an array of custom dashes and spaces currently set for this Pen object.

Status GetDashPattern(
  REAL* dashArray,
  INT count
);

Parameters

dashArray
[out] Pointer to an array that receives the length of the dashes and spaces in a custom dashed line.
count
[in] Integer that specifies the number of elements in the dashArray array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The elements in the dashArray array set the length of each dash and space in the dash pattern. The first element sets the length of a dash, the second element sets the length of a space, the third element sets the length of a dash, and so forth.

The length of each dash and space in the dash pattern is the product of each element in the array and the width of the Pen object.

Example Code [C++]

The following example creates an array of real numbers and a Pen object, sets the dash pattern, and draws a custom dashed line. The code then gets the dash pattern currently set for the pen.

VOID Example_GetDashPattern(HDC hdc
{
   Graphics graphics(hdc);

   // Create a custom dashed pen, and use it to draw a line.
   REAL dashVals[4] = {5, 2, 15, 4};
   Pen pen(Color(255, 0, 0, 0), 5);
   pen.SetDashPattern(dashVals, 4);
   graphics.DrawLine(&pen, 5, 20, 405, 200);

   // Obtain information about the pen.
   INT count = 0;
   REAL* dashValues = NULL;

   count = pen.GetDashPatternCount();
   dashValues = new REAL[count];
   pen.GetDashPattern(dashValues, count);

   for(INT j = 0; j < count; ++j)
   {
      // Inspect or use the value in dashValues[j].
   }

   delete [] dashValues;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetDashPatternCount, SetDashPattern
Tasks and Examples
Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::GetDashPatternCount()

The GetDashPatternCount method gets the number of elements in a dash pattern array.

INT GetDashPatternCount(void);

Parameters

This method has no parameters.

Return Values

This method returns an integer that indicates the number of elements in the dash pattern array.

Example Code [C++]

The following example creates a Pen object, sets the dash pattern array, and draws a custom dashed line. The code then gets the number of elements in the custom dashed array.

VOID Example_GetDashPattern(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a custom dashed pen, and use it to draw a line.
   REAL dashVals[4] = {5, 2, 15, 4};
   Pen pen(Color(255, 0, 0, 0), 5);
   pen.SetDashPattern(dashVals, 4);
   graphics.DrawLine(&pen, 5, 20, 405, 200);

   // Obtain information about the pen.
   INT count = 0;
   REAL* dashValues = NULL;

   count = pen.GetDashPatternCount();
   dashValues = new REAL[count];
   pen.GetDashPattern(dashValues, count);

   for(INT j = 0; j < count; ++j)
   {
      // Inspect or use the value in dashValues[j].
   }

   delete [] dashValues;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetDashPattern, SetDashPattern
Tasks and Examples
Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::GetDashStyle()

The GetDashStyle method gets the dash style currently set for this Pen object.

DashStyle GetDashStyle(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the DashStyle enumeration that indicates the dash style for this Pen object.

Example Code [C++]

The following example creates a Pen object, sets the dash style, and draws a dashed line. The code then gets the dash style, creates a second pen with the dash style of the first pen, and draws a second dashed line.

VOID Example_GetDashStyle(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a dashed pen, and use it to draw a dashed line.
   Pen pen(Color(255, 255, 0, 0), 9);
   pen.SetDashStyle(DashStyleDashDot);
   graphics.DrawLine(&pen, 20, 20, 200, 100);

   // Obtain the dash style for the pen.
   DashStyle dashStyle;
   dashStyle = pen.GetDashStyle();

   // Create another pen, and use the same dash style.
   Pen pen2(Color(255, 0, 255, 0), 9);
   pen2.SetDashStyle(dashStyle);

   // Draw a second dashed line.
   graphics.DrawLine(&pen2, 20, 60, 200, 140);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
DashStyle, GetDashCap, GetDashOffset, GetDashPattern, GetDashPatternCount, SetDashPattern, SetDashCap, SetDashOffset, SetDashPattern, SetDashStyle
Tasks and Examples
Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::GetEndCap()

The GetEndCap method gets the end cap currently set for this Pen object.

LineCap GetEndCap(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the LineCap enumeration that indicates the end cap for this Pen object.

Example Code [C++]

The following example creates a Pen object with an end cap and draws a line. The code then gets the end cap setting, creates a second pen based on the first pen, and draws a second line.

VOID Example_GetEndCap(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a pen with an arrow end cap, and use that
   // pen to draw a line.
   Pen pen(Color(255, 255, 0, 0), 15);
   pen.SetEndCap(LineCapArrowAnchor);
   graphics.DrawLine(&pen, 20, 20, 200, 100);

   // Obtain the end cap for the pen.
   LineCap lineCap;
   lineCap = pen.GetEndCap();

   // Create another pen, and use the same end cap.
   Pen pen2(Color(255, 0, 255, 0), 9);
   pen2.SetEndCap(lineCap);

   // Draw a second line.
   graphics.DrawLine(&pen2, 20, 60, 200, 140);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetCustomEndCap, GetCustomStartCap, SetEndCap, LineCap, SetLineCap, SetStartCap
Tasks and Examples
Drawing a Line with Line Caps
Concepts
Pens, Lines, and Rectangles


Pen::GetLastStatus()

The GetLastStatus method returns a value that indicates the nature of this Pen object's most recent method failure.

Status GetLastStatus(void);

Parameters

This method has no parameters.

Return Values

The GetLastStatus method returns an element of the Status enumeration.

If no methods invoked on this Pen object have failed since the previous call to GetLastStatus, then GetLastStatus returns Ok.

If at least one method invoked on this Pen object has failed since the previous call to GetLastStatus, then GetLastStatus returns a value that indicates the nature of the most recent failure.

Remarks

You can call GetLastStatus immediately after constructing a Pen object to determine whether the constructor succeeded.

The first time you call the GetLastStatus method of a Pen object, it returns Ok if the constructor succeeded and all methods invoked so far on the Pen object succeeded. Otherwise, it returns a value that indicates the nature of the most recent failure.

Example Code [C++]

The following example creates a Pen object, sets the dash style, and draws a dashed line. The code then checks the status of the method that sets the dash style for the pen.

VOID Example_GetLastStatus(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a pen.
   Pen pen(Color(255, 255, 0, 0), 5);

   // Set the dash style, and draw a dashed line.
   pen.SetDashStyle(DashStyleDash);
   graphics.DrawLine(&pen, 0, 0, 200, 100);

   // Check the status of the method that sets the dash style for the pen.
   Status status = pen.GetLastStatus();

   if(status == Ok)
   {
      // The call to SetDashStyle was successful.
   }
   else
   {
      // There was a problem with the call to SetDashStyle.
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
Status


Pen::GetLineJoin()

The GetLineJoin method gets the line join style currently set forthis Pen object.

LineJoin GetLineJoin(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the LineJoin enumeration that indicates the style used at the point where line segments join.

Example Code [C++]

The following example creates a Pen object, sets the line join style, and draws a rectangle. The code then gets the line join style, creates a second pen based on the first pen, and draws a second rectangle.

VOID Example_GetLineJoin(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a pen with a round line join, and use
   // that pen to draw a rectangle.
   Pen pen(Color(255, 255, 0, 0), 15);
   pen.SetLineJoin(LineJoinRound);
   graphics.DrawRectangle(&pen, 20, 20, 200, 100);

   // Get the line join for the pen.
   LineJoin lineJoin = pen.GetLineJoin();

   // Create another pen, and use the same line join.
   Pen pen2(Color(255, 0, 255, 0), 15);
   pen2.SetLineJoin(lineJoin);

   // Draw a second rectangle.
   graphics.DrawRectangle(&pen2, 250, 20, 200, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
SetLineJoin
Tasks and Examples
Joining Lines
Concepts
Pens, Lines, and Rectangles


Pen::GetMiterLimit()

The GetMiterLimit method gets the miter length currently set for this Pen object.

REAL GetMiterLimit(void);

Parameters

This method has no parameters.

Return Values

This method returns a real number that indicates the miter limit of this Pen object.

Remarks

The miter length is the distance from the intersection of the line walls on the inside of the join to the intersection of the line walls outside of the join. The miter length can be large when the angle between two lines is small. The miter limit is the maximum allowed ratio of miter length to line width. The default value is 10.

Example Code [C++]

The following example creates a Pen object and gets the miter limit.

Pen pen(Color(255,255,0,0), 4.0f);
REAL miterLimit = pen.GetMiterLimit();

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
SetMiterLimit
Tasks and Examples
Joining Lines
Concepts
Pens, Lines, and Rectangles


Pen::GetPenType()

The GetPenType method gets the type currently set for this Pen object.

PenType GetPenType(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the PenType enumeration that indicates the style of pen currently set for this Pen object.

Remarks

A Pen object is created with a default pen type of PenTypeSolidColor, which is an element of the PenType enumeration.

Example Code [C++]

The following example creates a HatchBrush object and then passes the address of that HatchBrush object to a Pen constructor. The code uses the pen, which has a width of 15, to draw a line. The code calls the GetPenType method to determine the pen's type, and then checks to see whether the type is PenTypeHatchFill.

VOID Example_GetPenType(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a HatchBrush object.
   HatchBrush hatchBrush(
      HatchStyleVertical,
      Color(255, 255, 0, 0),
      Color(255, 0, 0, 255));

   // Create a pen based on a hatch brush, and use that
   // pen to draw a line.
   Pen pen(&hatchBrush, 15);
   graphics.DrawLine(&pen, 20, 20, 200, 100);

   // Obtain information about the pen.
   PenType penType = pen.GetPenType();

   if(penType == PenTypeHatchFill)
   {
      // The pen will draw with a hatch pattern.
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetBrush, SetBrush
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Pen::GetStartCap()

The GetStartCap method gets the start cap currently set for this Pen object.

LineCap GetStartCap(void);

Parameters

This method has no parameters.

Return Values

This method returns an element of the LineCap enumeration that specifies the start cap for this Pen object.

Example Code [C++]

The following example creates a Pen object, sets the start cap, and draws a line. The code then gets the start cap, creates a second pen based on the first pen, and draws a second line.

VOID Example_GetStartCap(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a pen with an arrow start cap, and use that
   // pen to draw a line.
   Pen pen(Color(255, 255, 0, 0), 15);
   pen.SetStartCap(LineCapArrowAnchor);
   graphics.DrawLine(&pen, 20, 20, 200, 100);

   // Obtain the end cap for the pen.
   LineCap lineCap;
   lineCap = pen.GetStartCap();

   // Create another pen, and use the same start cap.
   Pen pen2(Color(255, 0, 255, 0), 9);
   pen2.SetStartCap(lineCap);

   // Draw a second line.
   graphics.DrawLine(&pen2, 20, 60, 200, 140);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetCustomEndCap, GetCustomStartCap, LineCap, SetEndCap, SetLineCap, SetStartCap
Tasks and Examples
Drawing a Line with Line Caps
Concepts
Pens, Lines, and Rectangles


Pen::GetTransform(matrix)

The GetTransform method gets the world transformation matrix currently set for this Pen object.

Status GetTransform(
  Matrix* matrix
);

Parameters

matrix
[out] Pointer to a Matrix object that receives the transformation matrix.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Pen object and sets its transformation. The code then gets the transformation of the pen.

VOID Example_GetTransform(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a pen and set its transformation.
   Pen pen(Color(255, 255, 0, 0));
   pen.RotateTransform(45);

   // Obtain information about the pen.
   Matrix matrix;
   REAL elements[6];

   pen.GetTransform(&matrix);
   matrix.GetElements(elements);

   for(INT j = 0; j <=5; ++j)
   {
      // Inspect or use the value in elements[j].
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
Matrix, MultiplyTransform, ResetTransform, RotateTransform, ScaleTransform, SetTransform
Tasks and Examples
Transformations
Concepts
Coordinate Systems and Transformations


Pen::GetWidth()

The GetWidth method gets the width currently set for this Pen object.

REAL GetWidth(void);

Parameters

This method has no parameters.

Return Values

This method returns a real number that indicates the width of this Pen object.

Remarks

If you pass the address of a pen to one of the draw methods of a Graphics object, the width of the pen's stroke is dependent on the unit of measure specified in the Graphics object. The default unit of measure is UnitPixel, which is an element of the Unit enumeration.

Example Code [C++]

The following example creates a Pen object with a specified width and draws a line. The code then gets the width of the pen, creates a second pen based on the width of the first pen, and draws a second line.

VOID Example_GetWidth(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a pen with a width of 15, and
   // use that pen to draw a line.
   Pen pen(Color(255, 0, 0, 255), 15);
   graphics.DrawLine(&pen, 20, 20, 200, 100);

   // Get the width of the pen.
   REAL width = pen.GetWidth();

   // Create another pen that has the same width.
   Pen pen2(Color(255, 0, 255, 0), width);

   // Draw a second line.
   graphics.DrawLine(&pen2, 20, 60, 200, 140);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
SetWidth
Tasks and Examples
Setting Pen Width and Alignment
Concepts
Pens, Lines, and Rectangles


Pen::MultiplyTransform(matrix, order)

The MultiplyTransform method updates the world transformation matrix of this Pen object with the product of itself and another matrix.

Status MultiplyTransform(
  Matrix* matrix,
  MatrixOrder order
);

Parameters

matrix
[in] Pointer to a Matrix object that is multiplied with the world transformation matrix of this Pen object.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the passed matrix is on the left, and MatrixOrderAppend specifies that the passed matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example sets a matrix and creates a Pen object. The code then sets the width of the pen, applies a rotation matrix and a stretch matrix to the pen, and then draws an ellipse.

VOID Example_MultiplyTrans(HDC hdc)
{
   Graphics graphics(hdc);

   Matrix matrix(1, 0, 0, 4, 0, 0);  // vertical stretch

   Pen pen(Color(255, 0, 0, 255));
   pen.SetWidth(5);
   pen.RotateTransform(30);                             // first rotate
   pen.MultiplyTransform(&matrix, MatrixOrderPrepend);  // then stretch

   graphics.DrawEllipse(&pen, 50, 50, 200, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, ResetTransform, RotateTransform, ScaleTransform, SetTransform
Tasks and Examples
Transformations
Concepts
Coordinate Systems and Transformations


Pen::ResetTransform()

The ResetTransform method sets the world transformation matrix of this Pen object to the identity matrix.

Status ResetTransform(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The identity matrix represents a transformation that does nothing. If the world transformation matrix of a Pen object is the identity matrix, then no world transformation is applied to items drawn using that Pen object.

Example Code [C++]

The following example creates a Pen object, sets a scaling matrix to the pen, and draws a rectangle. The code then resets the transformation of the pen and draws a second rectangle.

VOID Example_ResetTrans(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a pen, and set its transformation.
   Pen pen(Color(255, 0, 0, 255), 2);
   pen.ScaleTransform(8, 4);

   // Draw a rectangle with the transformed pen.
   graphics.DrawRectangle(&pen, 50, 50, 150, 100);

   pen.ResetTransform();

   // Draw a rectangle with no pen transformation.
   graphics.DrawRectangle(&pen, 250, 50, 150, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MultiplyTransform, RotateTransform, ScaleTransform, SetTransform
Tasks and Examples
Transformations
Concepts
Coordinate Systems and Transformations


Pen::RotateTransform(angle, order)

The RotateTransform method updates the world transformation matrix of this Pen object with the product of itself and a rotation matrix.

Status RotateTransform(
  REAL angle,
  MatrixOrder order
);

Parameters

angle
[in] Real number that specifies the angle of rotation in degrees.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the rotation matrix is on the left, and MatrixOrderAppend specifies that the rotation matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Pen object. The code then applies a scaling matrix and a rotation matrix to the pen and draws an ellipse.

VOID Example_RotateTrans(HDC hdc)
{
   Graphics graphics(hdc);

   Pen pen(Color::Blue, 5);
   pen.ScaleTransform(1, 4);                     // first stretch
   pen.RotateTransform(30, MatrixOrderAppend);   // then rotate
   graphics.DrawEllipse(&pen, 50, 50, 200, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, MultiplyTransform, ResetTransform, ScaleTransform, SetTransform
Tasks and Examples
Transformations
Concepts
Coordinate Systems and Transformations


Pen::ScaleTransform(sx, sy, order)

The ScaleTransform method sets the Pen object's world transformation matrix equal to the product of itself and a scaling matrix.

Status ScaleTransform(
  REAL sx,
  REAL sy,
  MatrixOrder order
);

Parameters

sx
[in] Real number that specifies the horizontal scaling factor in the scaling matrix.
sy
[in] Real number that specifies the vertical scaling factor in the scaling matrix.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the scaling matrix is on the left, and MatrixOrderAppend specifies that the scaling matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Pen object and draws a rectangle. The code then applies a scaling transformation to the pen and draws a second rectangle.

VOID Example_ScaleTrans(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a pen, and use it to draw a rectangle.
   Pen pen(Color(255, 0, 0, 255), 2);
   graphics.DrawRectangle(&pen, 50, 50, 150, 100);

   // Apply a scaling transformation to the pen.
   pen.ScaleTransform(8, 4);

   // Draw a rectangle with the transformed pen.
   graphics.DrawRectangle(&pen, 250, 50, 150, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MatrixOrder, MultiplyTransform, ResetTransform, SetTransform
Tasks and Examples
Transformations
Concepts
Coordinate Systems and Transformations


Pen::SetAlignment(penAlignment)

The SetAlignment method sets the alignment for this Pen object relative to the line.

Status SetAlignment(
  PenAlignment penAlignment
);

Parameters

penAlignment
[in] Element of the PenAlignment enumeration that specifies the alignment setting of the pen relative to the line that is drawn. The default value is PenAlignmentCenter.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

If you set the alignment of a Pen object to PenAlignmentInset, you cannot use that pen to draw compound lines or triangular dash caps.

Example Code [C++]

The following example creates two Pen objects and sets the alignment for one of the pens. The code then draws two lines using each of the pens.

VOID Example_SetAlignment(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a black and a green pen.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   Pen greenPen(Color(255, 0, 255, 0), 15);

   // Set the alignment of the green pen.
   greenPen.SetAlignment(PenAlignmentInset);

   // Draw two lines using each pen.
   graphics.DrawEllipse(&greenPen, 0, 0, 100, 200);
   graphics.DrawEllipse(&blackPen, 0, 0, 100, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetAlignment, PenAlignment
Tasks and Examples
Setting Pen Width and Alignment
Concepts
Pens, Lines, and Rectangles


Pen::SetBrush(brush)

The SetBrush method sets the Brush object that a pen uses to fill a line.

Status SetBrush(
  const Brush* brush
);

Parameters

brush
[in] Pointer to a Brush object for the pen to use to fill a line.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a HatchBrush object and then passes the address of that HatchBrush object to a Pen constructor. The code then sets the brush for the pen and draws a line.

VOID Example_SetBrush(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a HatchBrush object.
   HatchBrush hatchBrush(
      HatchStyleVertical,
      Color(255, 255, 0, 0),   // red
      Color(255, 0, 0, 255));  // blue

   // Create a pen, and set the brush for the pen.
   Pen pen(Color(255, 255, 0, 0), 10);
   pen.SetBrush(&hatchBrush);

   // Draw a line with the pen.
   graphics.DrawLine(&pen, 0, 0, 200, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
Brush, HatchBrush, SetBrush
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


Pen::SetColor(color)

The SetColor method sets the color for this Pen object.

Status SetColor(
  const Color& color
);

Parameters

color
[in] Reference to a Color object that specifies the color for this Pen object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a red pen and draws a line. The code then sets the pen's color to blue and draws a second line.

VOID Example_SetColor(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a red pen, and use it to draw a line.
   Pen pen(Color(255, 255, 0, 0), 5);
   graphics.DrawLine(&pen, 0, 0, 200, 100);

   // Change the pen's color to blue, and draw a second line.
   pen.SetColor(Color(255, 0, 0, 255));
   graphics.DrawLine(&pen, 0, 40, 200, 140);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
Color, GetColor
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Pen::SetCompoundArray(compoundArray, count)

The SetCompoundArray method sets the compound array for this Pen object.

Status SetCompoundArray(
  const REAL* compoundArray,
  INT count
);

Parameters

compoundArray
[in] Pointer to an array of real numbers that specifies the compound array. The elements in the array must be in increasing order, not less than 0, and not greater than 1.
count
[in] Positive even integer that specifies the number of elements in the compoundArray array. The integer must not be greater than the number of elements in the compound array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Suppose you want a pen to draw two parallel lines where the width of the first line is 20 percent of the pen's width, the width of the space that separates the two lines is 50 percent of the pen' s width, and the width of the second line is 30 percent of the pen's width. Start by creating a Pen object and an array of real numbers. You can then set the compound array by passing the array with the values 0.0, 0.2, 0.7, and 1.0 to the SetCompoundArray method of the Pen object.

If you set the alignment of a Pen object to PenAlignmentInset, you cannot use that pen to draw compound lines.

Example Code [C++]

The following example creates a Pen object and sets the compound array for the pen. The code then draws a line using the Pen object.

VOID Example_SetCompoundArray(HDC hdc)
{
   Graphics graphics(hdc);

   // Create an array of real numbers and a Pen object.
   REAL compVals[6] = {0.0f, 0.2f, 0.5f, 0.7f, 0.9f, 1.0f};
   Pen pen(Color(255, 0, 0, 255), 30);

   // Set the compound array of the pen.
   pen.SetCompoundArray(compVals, 6);

   // Draw a line with the pen.
   graphics.DrawLine(&pen, 5, 20, 405, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetCompoundArray, GetCompoundArrayCount
Tasks and Examples
Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::SetCustomEndCap(customCap)

The SetCustomEndCap method sets the custom end cap for this Pen object.

Status SetCustomEndCap(
  const CustomLineCap* customCap
);

Parameters

customCap
[in] Pointer to a CustomLineCap object that specifies the custom end cap for this Pen object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object and adds a rectangle to it. The code then creates a Pen object, sets the custom end cap based on the GraphicsPath object, and draws a line.

VOID Example_SetCustomEndCap(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a GraphicsPath object, and add a rectangle to it.
   GraphicsPath strokePath;
   strokePath.AddRectangle(Rect(-10, -5, 20, 10));

   // Create a pen, and set the custom end cap based on the GraphicsPath object.
   Pen pen(Color(255, 0, 0, 255));
   CustomLineCap custCap(NULL, &strokePath);
   pen.SetCustomEndCap(&custCap);

   // Draw a line with the custom end cap.
   graphics.DrawLine(&pen, 0, 0, 200, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetCustomEndCap, GetCustomStartCap, GetEndCap, SetCustomStartCap, SetEndCap
Tasks and Examples
Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::SetCustomStartCap(customCap)

The SetCustomStartCap method sets the custom start cap for this Pen object.

Status SetCustomStartCap(
  const CustomLineCap* customCap
);

Parameters

customCap
[in] Pointer to a CustomLineCap object that specifies the custom start cap for this Pen object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a GraphicsPath object and adds a rectangle to it. The code then creates a Pen object, sets the custom start cap based on the GraphicsPath object, and draws a line.

VOID Example_SetCustomStartCap(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a GraphicsPath object, and add a rectangle to it.
   GraphicsPath strokePath;
   strokePath.AddRectangle(Rect(-10, -5, 20, 10));

   // Create a pen, and set the custom start cap based on the GraphicsPath object.
   Pen pen(Color(255, 0, 0, 255));
   CustomLineCap custCap(NULL, &strokePath);
   pen.SetCustomStartCap(&custCap);

   // Draw a line with the custom start cap.
   graphics.DrawLine(&pen, 20, 20, 200, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetCustomEndCap, GetCustomStartCap, SetCustomStartCap
Tasks and Examples
Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::SetDashCap(dashCap)

The SetDashCap method sets the dash cap style for this Pen object.

Status SetDashCap(
  DashCap dashCap
);

Parameters

dashCap
[in] Element of the DashCap enumeration that specifies the dash cap for this Pen object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

If you set the alignment of a Pen object to PenAlignmentInset, you cannot use that pen to draw triangular dash caps.

Example Code [C++]

The following example creates a Pen object, sets the dash style and the dash cap, and draws a dashed line.

VOID Example_SetCustomStartCap(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a pen.
   Pen pen(Color(255, 0, 0, 255), 20);

   // Set the dash style for the pen.
   pen.SetDashStyle(DashStyleDash);

   // Set a triangular dash cap for the pen.
   pen.SetDashCap(DashCapTriangle);

   // Draw a line using the pen.
   graphics.DrawLine(&pen, 20, 20, 200, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetCustomEndCap, GetCustomStartCap, GetDashCap, SetDashCap
Tasks and Examples
Drawing a Line with Line Caps, Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::SetDashOffset(dashOffset)

The SetDashOffset method sets the distance from the start of the line to the start of the first dash in a dashed line.

Status SetDashOffset(
  REAL dashOffset
);

Parameters

dashOffset
[in] Real number that specifies the number of times to shift the spaces in a dashed line. Each shift is equal to the length of a space in the dashed line.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A positive dashOffset value shifts the first dash forward along the path, and a negative dashOffset value shifts the start of the path forward along the first dash.

Example Code [C++]

The following example creates a Pen object, sets the dash style, and draws a line. The code then sets the pen's offset value and draws a second line.

VOID Example_SetDashOffset(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object, set the dash style, and draw a line.
   Pen pen(Color(255, 0, 0, 255), 15);
   pen.SetDashStyle(DashStyleDash);
   graphics.DrawLine(&pen, 0, 50, 400, 50);

   // Set the dash offset value for the pen, and draw a second line.
   pen.SetDashOffset(10);
   graphics.DrawLine(&pen, 0, 80, 400, 80);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetDashOffset, GetDashPattern, GetDashPatternCount, GetDashStyle, SetDashCap, SetDashPattern, SetDashStyle
Tasks and Examples
Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::SetDashPattern(dashArray, count)

The SetDashPattern method sets an array of custom dashes and spaces for this Pen object.

Status SetDashPattern(
  const REAL* dashArray,
  INT count
);

Parameters

dashArray
[in] Pointer to an array of real numbers that specifies the length of the custom dashes and spaces. All elements in the array must be positive real numbers.
count
[in] Integer that specifies the number of elements in the dashArray array. The integer must be greater than 0 and not greater than the total number of elements in the array.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

This method will set the DashStyle enumeration for this Pen object to DashStyleCustom.

The elements in the dashArray array set the length of each dash and space in the dash pattern. The first element sets the length of a dash, the second element sets the length of a space, the third element sets the length of a dash, and so forth.

The length of each dash and space in the dash pattern is the product of the element value in the array and the width of the Pen object.

Example Code [C++]

The following example creates an array of real numbers. The code then creates a Pen object, sets the dash pattern based on the array, and then draws the custom dashed line.

VOID Example_SetDashPattern(HDC hdc)
{
   Graphics graphics(hdc);

   // Create and set an array of real numbers.
   REAL dashVals[4] = {
      5.0f,   // dash length 5
      2.0f,   // space length 2
      15.0f,  // dash length 15
      4.0f};  // space length 4

   // Create a Pen object.
   Pen pen(Color(255, 0, 0, 0), 5);

   // Set the dash pattern for the custom dashed line.
   pen.SetDashPattern(dashVals, 4);

   // Draw the custom dashed line.
   graphics.DrawLine(&pen, 5, 20, 405, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetDashPattern, GetDashPatternCount
Tasks and Examples
Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::SetDashStyle(dashStyle)

The SetDashStyle method sets the dash style for this Pen object.

Status SetDashStyle(
  DashStyle dashStyle
);

Parameters

dashStyle
[in] Element of the DashStyle enumeration that specifies the dash style for this Pen object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The length of the dashes in a dashed line is dependent on the dash style and the width of the Pen object. The length of the space that separates two dashes in a dashed line is equal to the width of the Pen object.

Example Code [C++]

The following example creates a Pen object, sets the dash style, and draws a line. The code then resets the dash style, draws a second line, resets dash style again, and draws a third line.

VOID Example_SetDashStyle(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen pen(Color(255, 0, 0, 255), 15);

   // Set the dash style for the pen, and draw a dashed line.
   pen.SetDashStyle(DashStyleDash);
   graphics.DrawLine(&pen, 0, 50, 400, 150);

   // Reset the dash style for the pen, and draw a second line.
   pen.SetDashStyle(DashStyleDot);
   graphics.DrawLine(&pen, 0, 80, 400, 180);

   // Reset the dash style for the pen, and draw a third line.
   pen.SetDashStyle(DashStyleDashDot);
   graphics.DrawLine(&pen, 0, 110, 400, 210);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetDashCap, GetDashOffset, GetDashPattern, GetDashPatternCount, GetDashStyle, SetDashCap, SetDashOffset, SetDashPattern
Tasks and Examples
Drawing a Custom Dashed Line
Concepts
Pens, Lines, and Rectangles


Pen::SetEndCap(endCap)

The SetEndCap method sets the end cap for this Pen object.

Status SetEndCap(
  LineCap endCap
);

Parameters

endCap
[in] Element of the LineCap enumeration that specifies the end cap of a line.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Pen object, sets the end cap, and draws a line. The code then resets the end cap, draws a second line, resets the end cap again, and draws a third line.

VOID Example_SetEndCap(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Pen object.
   Pen pen(Color(255, 0, 0, 255), 15);

   // Set the end cap of the pen, and draw a line.
   pen.SetEndCap(LineCapArrowAnchor);
   graphics.DrawLine(&pen, 0, 50, 400, 150);

   // Reset the end cap, and draw a second line.
   pen.SetEndCap(LineCapTriangle);
   graphics.DrawLine(&pen, 0, 80, 400, 180);

   // Reset the end cap, and draw a third line.
   pen.SetEndCap(LineCapRound);
   graphics.DrawLine(&pen, 0, 110, 400, 210);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetEndCap, GetStartCap, LineCap, SetLineCap
Tasks and Examples
Drawing a Line with Line Caps
Concepts
Pens, Lines, and Rectangles


Pen::SetLineCap(startCap, endCap, dashCap)

The SetLineCap method sets the cap styles for the start, end, and dashes in a line drawn with this pen.

Status SetLineCap(
  LineCap startCap,
  LineCap endCap,
  DashCap dashCap
);

Parameters

startCap
[in] Element of the LineCap enumeration that specifies the start cap of a line.
endCap
[in] Element of the LineCap enumeration that specifies the end cap of a line.
dashCap
[in] Element of the DashCap enumeration that specifies the start and end caps of the dashes in a dashed line.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Pen object and sets the line caps. The code then sets the dash style for the pen and draws a line.

VOID Example_SetLineCap(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a pen.
   Pen pen(Color(255, 0, 0, 255), 15);

   // Set line caps for the pen.
   pen.SetLineCap(LineCapArrowAnchor, LineCapTriangle, DashCapRound);

   // Set the dash style for the pen.
   pen.SetDashStyle(DashStyleDash);

   // Draw a line.
   graphics.DrawLine(&pen, 50, 50, 420, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetEndCap, GetStartCap, LineCap, SetCustomEndCap, SetCustomStartCap, SetEndCap, SetLineCap
Tasks and Examples
Drawing a Line with Line Caps
Concepts
Pens, Lines, and Rectangles


Pen::SetLineJoin(lineJoin)

The SetLineJoin method sets the line join for this Pen object.

Status SetLineJoin(
  LineJoin lineJoin
);

Parameters

lineJoin
[in] Element of the LineJoin enumeration that specifies the join style used at the end of a line segment that meets another line segment.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Pen object, sets the line join style, and draws a rectangle. The code then resets the line join style and draws a second rectangle.

VOID Example_SetLineJoin(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a pen.
   Pen pen(Color(255, 0, 0, 255), 15);

   // Set the join style, and draw a rectangle.
   pen.SetLineJoin(LineJoinRound);
   graphics.DrawRectangle(&pen, 20, 20, 150, 100);

   // Reset the join style, and draw a second rectangle.
   pen.SetLineJoin(LineJoinBevel);
   graphics.DrawRectangle(&pen, 200, 20, 150, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetEndCap, GetStartCap, LineCap, SetEndCap, SetLineCap, SetStartCap
Tasks and Examples
Joining Lines
Concepts
Pens, Lines, and Rectangles


Pen::SetMiterLimit(miterLimit)

The SetMiterLimit method sets the miter limit of this Pen object.

Status SetMiterLimit(
  REAL miterLimit
);

Parameters

miterLimit
[in] Real number that specifies the miter limit of this Pen object. A real number value that is less than 1.0f will be replaced with 1.0f.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The miter length is the distance from the intersection of the line walls on the inside of the join to the intersection of the line walls outside of the join. The miter length can be large when the angle between two lines is small. The miter limit is the maximum allowed ratio of miter length to stroke width. The default value is 10.0f.

If the miter length of the join of the intersection exceeds the limit of the join, then the join will be beveled to keep it within the limit of the join of the intersection.

Example Code [C++]

The following example creates a Pen object and sets the miter limit for the pen.

Pen pen(Color(255,255,0,0), 4.0f);
Status stat = pen.SetMiterLimit(10.0f);

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetMiterLimit
Tasks and Examples
Joining Lines
Concepts
Pens, Lines, and Rectangles


Pen::SetStartCap(startCap)

The SetStartCap method sets the start cap for this Pen object.

Status SetStartCap(
  LineCap startCap
);

Parameters

startCap
[in] Element of the LineCap enumeration that specifies the start cap of a line.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Pen object, sets the start cap, and draws a line. The code then resets the start cap, draws a second line, resets the start cap again, and draws a third line.

VOID Example_SetStartCap(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a pen.
   Pen pen(Color(255, 0, 0, 255), 15);

   // Set the start cap of the pen, and draw a line.
   pen.SetStartCap(LineCapArrowAnchor);
   graphics.DrawLine(&pen, 50, 50, 400, 150);

   // Reset the start cap, and draw a second line.
   pen.SetStartCap(LineCapTriangle);
   graphics.DrawLine(&pen, 50, 80, 400, 180);

   // Reset the start cap, and draw a third line.
   pen.SetStartCap(LineCapRound);
   graphics.DrawLine(&pen, 50, 110, 400, 210);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetEndCap, GetStartCap, LineCap, SetEndCap, SetLineCap
Tasks and Examples
Drawing a Line with Line Caps
Concepts
Pens, Lines, and Rectangles


Pen::SetTransform(matrix)

The SetTransform method sets the world transformation of this Pen object.

Status SetTransform(
  const Matrix* matrix
);

Parameters

matrix
[in] Pointer to a Matrix object that specifies the world transformation.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

This method ignores the translation portion of the Matrix object.

Example Code [C++]

The following example creates a scale matrix and a Pen object, and then draws a rectangle. The code then scales the pen by the matrix and draws a second rectangle.

VOID Example_SetTransform(HDC hdc)
{
   Graphics graphics(hdc);

   Matrix matrix(20, 0, 0, 10, 0, 0);  // scale

   // Create a pen, and use it to draw a rectangle.
   Pen pen(Color(255, 0, 0, 255), 2);
   graphics.DrawRectangle(&pen, 10, 50, 150, 100);

   // Scale the pen width by a factor of 20 in the horizontal
   // direction and a factor of 10 in the vertical direction.
   pen.SetTransform(&matrix);

   // Draw a rectangle with the transformed pen.
   graphics.DrawRectangle(&pen, 200, 50, 150, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MultiplyTransform, ResetTransform, RotateTransform, ScaleTransform
Tasks and Examples
Transformations
Concepts
Coordinate Systems and Transformations


Pen::SetWidth(width)

The SetWidth method sets the width for this Pen object.

Status SetWidth(
  REAL width
);

Parameters

width
[in] Real number that specifies the width of the pen.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a Pen object with a specified width and draws a rectangle. The code then resets the width of the pen and draws a second rectangle.

VOID Example_SetWidth(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a pen of width 2, and use it to draw a rectangle.
   Pen pen(Color(255, 0, 0, 255), 2);
   graphics.DrawRectangle(&pen, 10, 50, 150, 100);

   // Reset the pen's width to 15, and draw another rectangle.
   pen.SetWidth(15);
   graphics.DrawRectangle(&pen, 200, 50, 150, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspen.h; include Gdiplus.h.

See Also

Reference
GetWidth
Tasks and Examples
Setting Pen Width and Alignment
Concepts
Pens, Lines and Rectangles


Point Class

The Point class encapsulates a point in a 2-D coordinate system.

Data Members

Data member | Description
X | INT. Horizontal coordinate.
Y | INT. Vertical coordinate.

Constructors

Constructor | Description
Point | Overloaded. Creates and initializes a new Point object.

Methods

Method | Description
Equals | Determines whether two points are equal (same coordinates).
operator+ | Adds two Point objects.
operator- | Subtracts two Point objects.


Point Constructors

This topic lists the constructors of the Point class. For a complete class listing, see Point Class.

  • Point()
  • Point(point)
  • Point(size)
  • Point(x, y)


Point::Point()

Creates a Point object and initializes the X and Y data members to zero. This is the default constructor.

Point(void);

Parameters

This method has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Point Constructors, PointF


Point::Point(point)

Creates a new Point object and copies the data members from another Point object.

Point(
  const Point& point
);

Parameters

point
[in] Reference to a Point object whose X and Y data members are copied into the X and Y data members of the new Point object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Point Constructors, PointF


Point::Point(size)

Creates a Point object using a Size object to initialize the X and Y data members.

Point(
  const Size& size
);

Parameters

size
[in] Reference to a Size object whose Width data member specifies the X data member of this Point object, and whose Height data member specifies the Y data member of this Point object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Point Constructors, PointF


Point::Point(x, y)

Creates a Point object using two integers to initialize the X and Y data members.

Point(
  INT x,
  INT y
);

Parameters

x
[in] Integer that specifies the x-coordinate of the Point object.
y
[in] Integer that specifies the y-coordinate of the Point object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Point Constructors, PointF


Point Methods

This topic lists the methods of the Point class. For a complete class listing, see Point Class.

  • Equals(point)
  • operator+(point)
  • operator-(point)


Point::Equals(point)

The Equals method determines whether two Point objects are equal. Two points are considered equal if they have the same X and Y data members.

BOOL Equals(
  const Point& point
);

Parameters

point
[in] Reference to a Point object that is compared to this Point object.

Return Values

If the Point objects are equal, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates two Point objects and determines whether they are equal.

Point point1(5, 3);
Point point2(5, 3);

if(point1.Equals(point2))
{
   // point1 and point2 are the same.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
operator+, operator-, PointF


Point::operator+(point)

The operator+ method adds the X and Y data members of two Point objects.

Point operator+(
  const Point& point
);

Parameters

point
[in] Reference to a Point object whose X and Y data members are added to the X and Y data members of this Point object.

Return Values

This method returns a Point object that is the sum of two Point objects.

Remarks

This method overloads the addition operator for Point objects. If A, B, and C are Point objects, the statement C = A + B is equivalent to C = A.operator+(B).

Example Code [C++]

The following example creates two Point objects, then adds the two Point objects and stores the result in a third Point object.

Point point1(40, 10);
Point point2(20, 30);

// Point 3 now contains the coordinates (60, 40).
Point point3 = point1 + point2;

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Equals, operator-, PointF


Point::operator-(point)

The operator- method subtracts the X and Y data members of two Point objects.

Point operator-(
  const Point& point
);

Parameters

point
[in] Reference to a Point object whose X and Y data members are subtracted from the X and Y data members of this Point object.

Return Values

This method returns a Point object that is the difference of two Point objects.

Remarks

This method overloads the subtraction operator for Point objects. If A, B, and C are Point objects, the statement C = A - B is equivalent to C = A.operator-(B).

Example Code [C++]

The following example creates two Point objects, then subtracts the second Point object from the first Point object and stores the result in a third Point object.

Point point1(40, 10);
Point point2(-20, -30);

// Point3 now contains the coordinates (60, 40).
Point point3 = point1 - point2;

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Equals, operator+, PointF


PointF Class

The PointF class encapsulates a point in a 2-D coordinate system.

Data Members

Data member | Description
X | REAL. Horizontal coordinate.
Y | REAL. Vertical coordinate.

Constructors

Constructor | Description
PointF | Creates and initializes a new PointF object.

Methods

Method | Description
Equals | Determines whether two points are equal (same coordinates).
operator+ | Adds two PointF objects.
operator- | Subtracts two PointF objects.


PointF Constructors

This topic lists the constructors of the PointF class. For a complete class listing, see PointF Class.

  • PointF()
  • PointF(point)
  • PointF(size)
  • PointF(x, y)


PointF::PointF()

Creates a PointF object and initializes the X and Y data members to zero. This is the default constructor.

PointF(void);

Parameters

This method has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Point, PointF Constructors


PointF::PointF(point)

Creates a new PointF object and copies the data from another PointF object.

PointF(
  const PointF& point
);

Parameters

point
[in] Reference to a PointF object whose X and Y data members are copied into the X and Y data members of the new PointF object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Point, PointF Constructors


PointF::PointF(size)

Creates a PointF object using a SizeF object to specify the X and Y data members.

PointF(
  const SizeF& size
);

Parameters

size
[in] Reference to a SizeF object whose Width data member specifies the X data member of this PointF object, and whose Height data member specifies the Y data member of this PointF object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Point, Point Constructors


PointF::PointF(x, y)

Creates a PointF object using two real numbers to specify the X and Y data members.

PointF(
  REAL x,
  REAL y
);

Parameters

x
[in] Real number that specifies the x-coordinate of the PointF object.
y
[in] Real number that specifies the y-coordinate of the PointF object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Point, Point Constructors


PointF Methods

This topic lists the methods of the PointF class. For a complete class listing, see PointF Class.

  • Equals(point)
  • operator+(point)
  • operator-(point)


PointF::Equals(point)

The Equals method determines whether two PointF objects are equal. Two points are considered equal if they have the same X and Y data members.

BOOL Equals(
  const PointF& point
);

Parameters

point
[in] Reference to a PointF object that is compared to this PointF object.

Return Values

If the PointF objects are equal, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates two PointF objects and determines whether they are equal.

PointF point1(5.0f, 3.0f);
PointF point2(5.0f, 3.0f);

if(point1.Equals(point2))
{
   // point1 and point2 are the same.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
operator+, operator-, Point


PointF::operator+(point)

The operator+ method adds the X and Y data members of two PointF objects.

PointF operator+(
  const PointF& point
);

Parameters

point
[in] Reference to a PointF object whose X and Y data members are added to the X and Y data members of this PointF object.

Return Values

This method returns a PointF object that is the sum of two PointF objects.

Remarks

This method overloads the addition operator for PointF objects. If A, B, and C are PointF objects, the statement C = A + B is equivalent to C = A.operator+(B).

Example Code [C++]

The following example creates two PointF objects, then adds the two PointF objects and stores the result in a third PointF object.

PointF point1(40.0f, 10.0f);
PointF point2(20.0f, 30.0f);

// Point3 now contains the coordinates (60.0f, 40.0f).
PointF point3 = point1 + point2;

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Equals, operator-, Point


PointF::operator-(point)

The operator- method subtracts the X and Y data members of two PointF objects.

PointF operator-(
  const PointF& point
);

Parameters

point
[in] Reference to a PointF object whose X and Y data members are subtracted from the X and Y data members of this PointF object.

Return Values

This method returns a PointF object that is the difference of two PointF objects.

Remarks

This method overloads the subtraction operator for PointF objects. If A, B, and C are PointF objects, the statement C = A - B is equivalent to C = A.operator-(B).

Example Code [C++]

The following example creates two PointF objects, then subtracts the second PointF object from the first PointF object and stores the result in a third PointF object.

PointF point1(40.0f, 10.0f);
PointF point2(-20.0f, -30.0f);

// Point3 now contains the coordinates (60.0f, 40.0f).
PointF point3 = point1 - point2;

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Equals, operator+, Point


PrivateFontCollection Class

The PrivateFontCollection is a collection class for fonts. This class keeps a collection of fonts specifically for an application. The fonts in the collection can include installed fonts as well as fonts that have not been installed on the system.

Inheritance

GdiplusBase
FontCollection
PrivateFontCollection

Constructors

Constructor | Description
PrivateFontCollection | Creates an empty PrivateFontCollection object.

Methods

Uninherited

Method | Description
AddFontFile | Adds a font file to this private font collection.
AddMemoryFont | Adds a font that is contained in system memory to a GDI+ font collection.
~PrivateFontCollection | PrivateFontCollection object destructor.

Inherited from FontCollection

Method | Description
GetFamilies | Gets the font families contained in this font collection.
GetFamilyCount | Gets the number of font families contained in this font collection.
GetLastStatus | Returns a value that indicates the result of this FontCollection object's previous method call.

Remarks

PrivateFontCollection allows applications to install a private version of an existing font without the need to replace the system version of the font. For example, GDI+ can create a private version of the Arial font in addition to the Arial font that the system uses. PrivateFontCollection can also be used to install fonts that don't exist in the operating system. This is a temporary font install that doesn't affect the system-installed collection. To see the installed collection use the InstalledFontCollection class.


PrivateFontCollection::PrivateFontCollection()

Creates an empty PrivateFontCollection object.

PrivateFontCollection(void);

Parameters

This method has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.


PrivateFontCollection Methods

This topic lists the methods of the PrivateFontCollection class. For a complete class listing, see PrivateFontCollection Class.

  • AddFontFile(filename)
  • AddMemoryFont(memory, length)
  • GetFamilies(numSought, gpfamilies, numFound)
  • GetFamilyCount()
  • GetLastStatus()


PrivateFontCollection::AddFontFile(filename)

The AddFontFile method adds a font file to this private font collection.

Status AddFontFile(
  const WCHAR* filename
);

Parameters

filename
[in] Pointer to a wide-character string that specifies the name of a font file.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a PrivateFontCollection object and adds three font files to the collection. The code then gets the font families that are in the collection and, for each family in the collection, creates a font which is used to draw text.

VOID Example_AddFontFile(HDC hdc)
{
   Graphics              graphics(hdc);
   SolidBrush            solidBrush(Color(255, 0, 0, 0));
   INT                   found = 0;
   INT                   count = 0;
   WCHAR                 familyName[50];
   FontFamily*           pFontFamily;
   PrivateFontCollection privateFontCollection;

   // Add three font files to the private collection.
   privateFontCollection.AddFontFile(L"C:\\WINNT\\Fonts\\Arial.ttf");
   privateFontCollection.AddFontFile(L"C:\\WINNT\\Fonts\\Cour.ttf");
   privateFontCollection.AddFontFile(L"C:\\WINNT\\Fonts\\Times.ttf");

   // How many font families are in the private collection?
   count = privateFontCollection.GetFamilyCount();

   // Allocate a buffer to hold the array of FontFamily objects returned by
   // the GetFamilies method.
   pFontFamily = (FontFamily*)malloc(count * sizeof(FontFamily));

   // Get the array of FontFamily objects.
   privateFontCollection.GetFamilies(count, pFontFamily, &found);

   for(INT j = 0; j < found; ++j)
   {
      // Get the font family name.
      pFontFamily[j].GetFamilyName(familyName);

      // Pass the family name and the address of the private collection to a
      // Font constructor.
      Font* pFont = new Font(familyName, 16, FontStyleRegular,
                             UnitPixel, &privateFontCollection);

      // Use the font to draw a string.
      graphics.DrawString(
                          L"Hello",
                          5,          // string length
                          pFont,
                          PointF(10.0f, (REAL)j*25),
                          &solidBrush);

      delete(pFont);
   }

   free(pFontFamily);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
InstalledFontCollection
Tasks and Examples
Using Text and Fonts, Creating a Private Font Collection


PrivateFontCollection::AddMemoryFont(memory, length)

The AddMemoryFont method adds a font that is contained in system memory to a GDI+ font collection.

Status AddMemoryFont(
  const VOID* memory,
  INT length
);

Parameters

memory
[in] Pointer to a font that is contained in memory.
length
[in] Integer that specifies the number of bytes of data in the font.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
AddFontFile
Tasks and Examples
Using Text and Fonts, Creating a Private Font Collection


PropertyItem Class

The PropertyItem class is a helper class for the Image and Bitmap classes. A PropertyItem object holds one piece of image metadata.

Data Members

The following table lists the data members of the PropertyItem class in the order that they are defined in the header file.

Data member | Description
id | PROPID. Integer that identifies the kind of metadata stored in this PropertyItem object. Constants that identify various kinds of metadata (PropertyTagEquipMake, PropertyTagEquipModel, and the like) are defined in Gdiplusimaging.h. The PROPID data type is defined in Wtypes.h.
length | ULONG. Size, in bytes, of the value array.
type | WORD. Integer that identifies the data type of the values in the value array. Constants that identify various data types (PropertyTagTypeByte, PropertyTagTypeASCII, and the like) are defined in Gdiplusimaging.h.
value | VOID*. Pointer to an array of values. Each value in the array has the data type specified by the type data member.

Remarks

To set a property item (piece of metadata), pass the address of a PropertyItem object to the SetPropertyItem method of an Image object. To retrieve a property item, pass the address of a PropertyItem object to the GetPropertyItem method of an Image object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimaging.h; include Gdiplus.h.

See Also

Reference
GetAllPropertyItems, GetPropertyIdList, GetPropertyItem, GetPropertyItemSize, GetPropertySize, RemovePropertyItem, SetPropertyItem
Tasks and Examples
Reading and Writing Metadata


Rect Class

A Rect object stores the upper-left corner, width, and height of a rectangle.

Data Members

Data member | Description
X | INT. X-coordinate of the upper-left corner of the rectangle.
Y | INT. Y-coordinate of the upper-left corner of the rectangle.
Width | INT. Width of the rectangle.
Height | INT. Height of the rectangle.

Constructors

Constructor | Description
Rect | Overloaded. Creates and initializes a new Rect object.

Methods

Method | Description
Clone | Creates a new Rect object from the existing Rect object.
Contains | Overloaded. Determines whether a point or rectangle is inside the rectangle.
Equals | Determines whether two rectangles are the same.
GetBottom | Gets the y-coordinate of the bottom edge of the rectangle.
GetBounds | Makes a copy of the existing rectangle.
GetLeft | Gets the x-coordinate of the left edge of the rectangle.
GetLocation | Gets the coordinates of the upper-left corner of the rectangle.
GetRight | Gets the x-coordinate if the right edge of the rectangle.
GetSize | Gets the width and height of the rectangle.
GetTop | Gets the y-coordinate of the top edge of the rectangle.
Inflate | Overloaded. Expands the rectangle on the left, right, top, and bottom.
Intersect | Overloaded. Determines the intersection of two rectangles.
IntersectsWith | Determines whether two rectangles intersect.
IsEmptyArea | Determines whether a rectangle is empty.
Offset | Overloaded. Moves the rectangle by a specified offset.
Union | Determines the union of two rectangles.


Rect Constructors

This topic lists the constructors of the Rect class. For a complete class listing, see Rect Class.

  • Rect()
  • Rect(location, size)
  • Rect(x, y, width, height)


Rect::Rect()

Creates a Rect object whose x-coordinate, y-coordinate, width, and height are all zero. This is the default constructor.

Rect(void);

Parameters

This method has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Rect Constructors, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::Rect(location, size)

Creates a Rect object by using a Point object to initialize the X and Y data members and a Size object to initialize the Width and Height data members.

Rect(
  const Point& location,
  const Size& size
);

Parameters

location
[in] Reference to a Point object that specifies the upper-left corner of this rectangle.
size
[in] Reference to a Size object that specifies the width and height of this rectangle.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Point, Rect Constructors, RectF, Size
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::Rect(x, y, width, height)

Creates a Rect object by using four integers to initialize the X, Y, Width, and Height data members.

Rect(
  INT x,
  INT y,
  INT width,
  INT height
);

Parameters

x
[in] Integer used to initialize the x-coordinate of the upper-left corner of the rectangle.
y
[in] Integer used to initialize the y-coordinate of the upper-left corner of the rectangle.
width
[in] Integer used to initialize the width of this rectangle.
height
[in] Integer used to initialize the height of this rectangle.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Rect Constructors, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect Methods

This topic lists the methods of the Rect class. For a complete class listing, see Rect Class.

  • Clone()
  • Contains(pt)
  • Contains(rect)
  • Contains(x, y)
  • Equals(rect)
  • GetBottom()
  • GetBounds(rect)
  • GetLeft()
  • GetLocation(point)
  • GetRight()
  • GetSize(size)
  • GetTop()
  • Inflate(dx, dy)
  • Inflate(point)
  • Intersect(c, a, b)
  • Intersect(rect)
  • IntersectsWith(rect)
  • IsEmptyArea()
  • Offset(dx, dy)
  • Offset(point)
  • Union(c, a, b)


Rect::Clone()

The Clone method creates a new Rect object and initializes it with the contents of this Rect object.

Rect* Clone(void) const;

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new Rect object.

Example Code [C++]

The following example creates a Rect object, makes a copy of the Rect object, and draws a rectangle based on the copied Rect object.

VOID Example_Clone(HDC hdc    )
{
   Graphics graphics(hdc);

   // Create a Rect object, and copy it to a new rect object.
   Rect rect(50, 50, 200, 100);
   Rect* pRect = rect.Clone();

   // Draw a rectangle based on the copied Rect object.
   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawRectangle(&pen, *pRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::Contains Methods

This topic lists the Contains methods of the Rect class. For a complete list of methods for the Rect class, see Rect Methods.

  • Contains(pt)
  • Contains(rect)
  • Contains(x, y)


Rect::Contains(pt)

The Contains method determines whether a point is inside this rectangle.

BOOL Contains(
  const Point& pt
) const;

Parameters

pt
[in] Reference to a point to be tested.

Return Values

If the point is inside the rectangle, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a Rect object and a Point object. The code then determines whether the point is inside the rectangle and then draws the rectangle and the point.

VOID Example_ContainsPoint(HDC hdc)
{
   Graphics graphics(hdc);

   Rect rect(50, 50, 200, 100);
   Point point(80, 90);

   if(rect.Contains(point))
   {
      // The point is inside the rectangle.
   }
   // Draw the rectangle and the point.
   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawRectangle(&pen, rect);
   graphics.DrawRectangle(&pen, point.X, point.Y, 1, 1);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Contains Methods, Point, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::Contains(rect)

The Contains method determines whether another rectangle is inside this rectangle.

BOOL Contains(
  Rect& rect
) const;

Parameters

rect
[in] Reference to a rectangle to test against this rectangle.

Return Values

If the rectangle is inside this rectangle, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates two Rect objects, determines whether the second Rect object is inside the first Rect object, and then draws the two rectangles.

VOID Example_ContainsRect(HDC hdc)
{
   Graphics graphics(hdc);

   // Create two rect objects.
   Rect rect1(50, 50, 200, 100);
   Rect rect2(50, 80, 100, 50);

   // Determine whether rect2 is inside rect1.
   if(rect1.Contains(rect2))
   {
      // rect1 contains rect2.
   }
   // Draw the two rectangles.
   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawRectangle(&pen, rect1);
   graphics.DrawRectangle(&pen, rect2);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Contains Methods, Intersect Methods, IntersectsWith, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::Contains(x, y)

The Contains method determines whether the point (x, y) is inside this rectangle.

BOOL Contains(
  INT x,
  INT y
) const;

Parameters

x
[in] Integer that specifies the x-coordinate of the point to be tested.
y
[in] Integer that specifies the y-coordinate of the point to be tested.

Return Values

If the point (x, y) is inside this rectangle, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a Rect object, determines whether a specified point is inside the Rect object, and then draws the rectangle and the specified point.

VOID Example_ContainsXY(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a rect object.
   Rect rect(50, 50, 200, 100);

   // Determine whether a specified point is inside the rectangle.
   if(rect.Contains(80, 90))
   {
      // The point (80, 90) is inside the rectangle.
   }
   // Draw the rectangle and the point (80, 90).
   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawRectangle(&pen, rect);
   graphics.DrawRectangle(&pen, 80, 90, 1, 1);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Contains Methods, Point, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::Equals(rect)

The Equals method determines whether two rectangles are the same.

BOOL Equals(
  const Rect& rect
) const;

Parameters

rect
[in] Reference to a rectangle to compare to this rectangle.

Return Values

If the rectangles are the same, this method returns TRUE; otherwise, it returns FALSE.

Remarks

Two rectangles are the same if their X, Y, Width, and Height data members are the same.

Example Code [C++]

The following example creates two Rect objects, moves the second Rect object horizontally by a specified value, and then determines whether the two Rect objects are the same.

Rect rect1(50, 50, 200, 100);
Rect rect2(20, 50, 200, 100);

rect2.Offset(30, 0);

if(rect2.Equals(rect1))
{
   // The two rectangles are the same.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::GetBottom()

The GetBottom method gets the y-coordinate of the bottom edge of the rectangle.

INT GetBottom(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the y-coordinate of the bottom edge of the rectangle.

Example Code [C++]

The following example creates a Rect object, gets the bottom edge of the rectangle, and then draws the rectangle and a line at the bottom of the rectangle.

VOID Example_GetBottom(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a rect object, and get the bottom edge of the rectangle.
   Rect rect(50, 50, 200, 100);
   INT bottom = rect.GetBottom();

   // Draw the rectangle with a thick green pen.
   Pen greenPen(Color(255, 0, 255, 0), 15);
   graphics.DrawRectangle(&greenPen, rect);

   // Draw a thin black line at the bottom of the rectangle.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   graphics.DrawLine(&blackPen, 0, bottom, 300, bottom);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetLeft, GetRight, GetTop, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::GetBounds(rect)

The GetBounds method makes a copy of this rectangle.

VOID GetBounds(
  Rect* rect
) const;

Parameters

rect
[out] Pointer to a Rect object that receives the copy of this rectangle.

Return Values

This method does not return a value.

Example Code [C++]

The following example creates a Rect object, offsets the rectangle, creates a second Rect object by using a copy of the first rectangle, and then draws the second Rect object.

VOID Example_GetBounds(HDC hdc)
{
   Graphics graphics(hdc);

   Rect rect1(50, 40, 200, 100);
   rect1.Offset(30, 20);

   Rect rect2;
   rect1.GetBounds(&rect2);

   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawRectangle(&pen, rect2);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetBottom, GetLeft, GetRight, GetTop, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::GetLeft()

The GetLeft method gets the x-coordinate of the left edge of the rectangle.

INT GetLeft(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the x-coordinate of the left edge of the rectangle.

Example Code [C++]

The following example creates a Rect object, gets the left edge of the rectangle, and then draws the rectangle and a line along the left edge of the rectangle.

VOID Example_GetLeft(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Rect object, and get the left edge of the rectangle.
   Rect rect(50, 50, 200, 100);
   INT left = rect.GetLeft();

   // Draw the rectangle with a thick green pen.
   Pen greenPen(Color(255, 0, 255, 0), 15);
   graphics.DrawRectangle(&greenPen, rect);

   // Draw a thin black line along the left edge of the rectangle.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   graphics.DrawLine(&blackPen, left, 0, left, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetBottom, GetRight, GetTop, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::GetLocation(point)

The GetLocation method gets the coordinates of the upper-left corner of the rectangle.

VOID GetLocation(
  Point* point
) const;

Parameters

point
[out] Pointer to a Point object that receives the coordinates of the upper-left corner.

Return Values

This method does not return a value.

Example Code [C++]

This example creates a Rect object, gets the point of the upper-left corner of the rectangle, and then draws a rectangle and line from the upper-left corner to the point (0, 0).

VOID Example_GetLocation(HDC hdc)
{
   Graphics graphics(hdc);

   Pen pen(Color(255, 0, 0, 255));
   Point location;
   Rect rect(50, 40, 200, 50);

   // Get the location of the upper-left corner of the rectangle.
   rect.GetLocation(&location);

   // Draw the rectangle.
   graphics.DrawRectangle(&pen, rect);

   // Draw a line from the upper-left corner of the rectangle to (0, 0).
   graphics.DrawLine(&pen, location, Point(0, 0));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetBottom, GetLeft, GetRight, GetTop, Point, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::GetRight()

The GetRight method gets the x-coordinate of the right edge of the rectangle.

INT GetRight(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the x-coordinate of the right edge of the rectangle.

Example Code [C++]

The following example creates a Rect object, gets the right edge of the rectangle, and then draws the rectangle and a line along the right edge of the rectangle.

VOID Example_GetRight(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a rect object, and get the right edge of the rectangle.
   Rect rect(50, 50, 200, 100);
   INT right = rect.GetRight();

   // Draw the rectangle with a thick green pen.
   Pen greenPen(Color(255, 0, 255, 0), 15);
   graphics.DrawRectangle(&greenPen, rect);

   // Draw a thin black line along the right edge of the rectangle.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   graphics.DrawLine(&blackPen, right, 0, right, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetBottom, GetLeft, GetTop, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::GetSize(size)

The GetSize method gets the width and height of the rectangle.

VOID GetSize(
  Size* size
) const;

Parameters

size
[out] Pointer to a Size object that receives the width and height of the rectangle.

Return Values

This method does not return a value.

Example Code [C++]

The following example creates a Rect object and gets the width and height of the rectangle.

VOID Example_GetSize(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Rect object and a Size object.
   Size size;
   Rect rect(50, 40, 200, 100);

   // Get the size of the rectangle.
   rect.GetSize(&size);

   // Inspect or use the values in size.Width and size.Height.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetBottom, GetLeft, GetRight, GetTop, RectF, Size
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::GetTop()

The GetTop method gets the y-coordinate of the top edge of the rectangle.

INT GetTop(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the y-coordinate of the top edge of the rectangle.

Example Code [C++]

The following example creates a Rect object, gets the top edge of the rectangle, and then draws the rectangle and a line along the top edge of the rectangle.

VOID Example_GetTop(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Rect object, and get the top edge of the rectangle.
   Rect rect(50, 50, 200, 100);
   INT top = rect.GetTop();

   // Draw the rectangle with a thick green pen.
   Pen greenPen(Color(255, 0, 255, 0), 15);
   graphics.DrawRectangle(&greenPen, rect);

   // Draw a thin black line at the top of the rectangle.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   graphics.DrawLine(&blackPen, 0, top, 300, top);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetBottom, GetLeft, GetRight, RectF, Size
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::Inflate Methods

This topic lists the Inflate methods of the Rect class. For a complete list of methods for the Rect class, see Rect Methods.

  • Inflate(dx, dy)
  • Inflate(point)


Rect::Inflate(dx, dy)

The Inflate method expands the rectangle by dx on the left and right edges, and by dy on the top and bottom edges.

VOID Inflate(
  INT dx,
  INT dy
);

Parameters

dx
[in] Integer that specifies the amount to expand the rectangle on the left and right edges.
dy
[in] Integer that specifies the amount to expand the rectangle on the top and bottom edges.

Return Values

This method does not return a value.

Remarks

The x-coordinate of the left edge is decreased by dx, and the x-coordinate of the right edge is increased by dx. The y-coordinate of the top edge is decreased by dy, and the y-coordinate of the bottom edge is increased by dy.

Example Code [C++]

The following example creates a Rect object, draws the rectangle, inflates the rectangle, and then redraws the rectangle.

VOID Example_InflateDxDy(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0));

   // Create and draw a rectangle.
   Rect rect(100, 100, 80, 40);
   graphics.DrawRectangle(&pen, rect);

   // Inflate the rectangle, and then redraw the rectangle.
   rect.Inflate(20, 10);
   graphics.DrawRectangle(&pen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::Inflate(point)

The Inflate method expands the rectangle by the value of point.X on the left and right edges, and by the value of point.Y on the top and bottom edges.

VOID Inflate(
  const Point& point
);

Parameters

point
[in] Reference to a Point object whose X data member specifies the amount to expand the rectangle on the left and right edges, and whose Y data member specifies the amount to expand the rectangle on the top and bottom edges.

Return Values

This method does not return a value.

Example Code [C++]

The following example creates a Rect object, draws the rectangle, inflates the rectangle, and then redraws the rectangle.

VOID Example_InflatePoint(HDC hdc)
{
   Graphics graphics(hdc);

   Pen pen(Color(255, 0, 0, 0));
   Point point(20, 10);

   Rect rect(100, 100, 80, 40);
   graphics.DrawRectangle(&pen, rect);
   rect.Inflate(point);
   graphics.DrawRectangle(&pen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Point, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::Intersect Methods

This topic lists the Intersect methods of the Rect class. For a complete list of methods for the Rect class, see Rect Methods.

  • Intersect(c, a, b)
  • Intersect(rect)


Rect::Intersect(c, a, b)

The Intersect method determines the intersection of two rectangles and stores the result in a Rect object.

static BOOL Intersect(
  Rect& c,
  const Rect& a,
  const Rect& b
);

Parameters

c
[out] Reference to a Rect object that receives the intersection of the two rectangles.
a
[in] Reference to one of the two rectangles to be intersected.
b
[in] Reference to one of the two rectangles to be intersected.

Return Values

If the intersection of the two rectangles is not empty, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates three Rect objects, draws the first two rectangles, and then draws the third rectangle that indicates the intersection of the first two rectangles.

VOID Example_IntersectABC(HDC hdc)
{
   Graphics graphics(hdc);
   Pen* pGreenPen;

   // Create three rect objects.
   Rect rectA(50, 50, 200, 100);
   Rect rectB(70, 20, 100, 200);
   Rect rectC;

   // Draw rectA and rectB with a thin black pen.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   graphics.DrawRectangle(&blackPen, rectA);
   graphics.DrawRectangle(&blackPen, rectB);

   // Draw the rectangle that indicates the intersection of the two rectangles.
   if(rectC.Intersect(rectC, rectA, rectB))
   {
      // rectC is not empty.
      // Draw the intersection with a thick green pen.
      pGreenPen = new Pen(Color(255, 0, 255, 0), 7);
     graphics.DrawRectangle(pGreenPen, rectC);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Intersect Methods, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::Intersect(rect)

The Intersect method replaces this rectangle with the intersection of itself and another rectangle.

BOOL Intersect(
  const Rect& rect
);

Parameters

rect
[in] Reference to a rectangle to intersect with this rectangle.

Return Values

If the intersection of the two rectangles is not empty, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates three Rect objects, draws the first two rectangles, and then draws the third rectangle that indicates the intersection of the first two rectangles.

VOID Example_IntersectRect(HDC hdc)
{
   Graphics graphics(hdc);

   // Create two rect objects.
   Rect rect1(50, 50, 200, 100);
   Rect rect2(70, 20, 100, 200);

   // Draw rect1 and rect2 with a thin black pen.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   graphics.DrawRectangle(&blackPen, rect1);
   graphics.DrawRectangle(&blackPen, rect2);

   // Form the intersection of rect1 and rect2, and store
   // the result in rect1.
   rect1.Intersect(rect2);

   // Draw the new rect1 with a thick green pen.
   Pen greenPen(Color(255, 0, 255, 0), 7);
   graphics.DrawRectangle(&greenPen, rect1);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Intersect Methods, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::IntersectsWith(rect)

The IntersectsWith method determines whether this rectangle intersects another rectangle.

BOOL IntersectsWith(
  const Rect& rect
) const;

Parameters

rect
[in] Reference to a rectangle to test.

Return Values

If the intersection of the two rectangles is not empty, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates two Rect objects, draws the first rectangle, and then determines if there is an intersection between the two rectangles. If the two rectangles intersect, the code draws the second rectangle.

VOID Example_IntersectsWith(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0), 1);

   // Create two Rect objects.
   Rect rect1(50, 50, 200, 100);
   Rect rect2(70, 20, 100, 200);

   // Draw rect1.
   graphics.DrawRectangle(&pen, rect1);

   // If rect1 intersects with rect2 then draw rect2.
   if(rect2.IntersectsWith(rect1))
      graphics.DrawRectangle(&pen, rect2);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Intersect Methods, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::IsEmptyArea()

The IsEmptyArea method determines whether this rectangle is empty.

BOOL IsEmptyArea(void) const;

Parameters

This method has no parameters.

Return Values

If the rectangle is empty, this method returns TRUE; otherwise, it returns FALSE.

Remarks

A rectangle is defined as empty if either the width or the height is zero or less.

Example Code [C++]

The following example creates a Rect object, inflates the dimensions of the rectangle, and determines whether the rectangle is empty.

VOID Example_IsEmptyArea(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a Rect object, and inflate the dimensions.
   Rect rect(50, 50, 200, 100);
   rect.Inflate(0, -120);

   // Determine whether the rectangle is empty.
   if(rect.IsEmptyArea())

   // The rectangle does not enclose any area.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Inflate Methods, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::Offset Methods

This topic lists the Offset methods of the Rect class. For a complete list of methods for the Rect class, see Rect Methods.

  • Offset(dx, dy)
  • Offset(point)


Rect::Offset(dx, dy)

The Offset method moves the rectangle by dx horizontally and by dy vertically.

VOID Offset(
  INT dx,
  INT dy
);

Parameters

dx
[in] Integer that specifies the amount to move the rectangle horizontally.
dy
[in] Integer that specifies the amount to move the rectangle vertically.

Return Values

This method does not return a value.

Example Code [C++]

The following example creates a Rect object, draws the rectangle, offsets the rectangle, and then redraws the rectangle.

VOID Example_OffsetDxDy(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0));

   // Create a Rect object, and draw the rectangle.
   Rect rect(100, 100, 80, 40);
   graphics.DrawRectangle(&pen, rect);

   // Offset the rectangle and redraw the rectangle.
   rect.Offset(30, 20);
   graphics.DrawRectangle(&pen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Offset Methods, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::Offset(point)

The Offset method moves this rectangle horizontally a distance of point.X and vertically a distance of point.Y.

VOID Offset(
  const Point& point
);

Parameters

point
[in] Reference to a Point object whose X data member specifies the distance to move the rectangle horizontally and whose Y data member specifies the distance to move the rectangle vertically.

Return Values

This method does not return a value.

Example Code [C++]

The following example creates a Point object and a Rect object and draws the rectangle. The code then offsets the rectangle by the specified Point object and redraws the rectangle.

VOID Example_OffsetPoint(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0));

   // Create a Point object.
   Point point(30, 20);

   // Create a Rect object, and then draw the rectangle.
   Rect rect(100, 100, 80, 40);
   graphics.DrawRectangle(&pen, rect);

   // Offset the rectangle by the point object.
   rect.Offset(point);

   // Redraw the rectangle.
   graphics.DrawRectangle(&pen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Offset Methods, Point, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Rect::Union(c, a, b)

The Union method determines the union of two rectangles and stores the result in a Rect object.

static BOOL Union(
  Rect& c,
  const Rect& a,
  const Rect& b
);

Parameters

c
[out] Reference to a Rect object that receives the union of the two rectangles.
a
[in] Reference to one of the two rectangles used to form the union.
b
[in] Reference to one of the two rectangles used to form the union.

Return Values

If the union of two rectangles is not empty, this method returns TRUE; otherwise, it returns FALSE.

Remarks

In GDI+, the union of two rectangles is the smallest rectangle that encloses the two rectangles. A rectangle is defined as empty if its width or height is less than or equal to zero.

Example Code [C++]

The following example creates three rectangles. The code forms the union of the first two rectangles and stores the result in the third rectangle. The code determines whether the union is nonempty and, if so, draws the union.

VOID Example_UnionABC(HDC hdc)
{
   Graphics graphics(hdc);
   Pen* pGreenPen;

   // Create three Rect objects.
   Rect rectA(50, 50, 200, 100);
   Rect rectB(70, 20, 100, 200);
   Rect rectC;

   // Determine the union of rectA and rectB, and store the result in rectC.
   if(rectC.Union(rectC, rectA, rectB))
   {
      // rectC is not empty.
      // Draw the union with a thick green pen.
      pGreenPen = new Pen(Color(255, 0, 255, 0), 7);
      graphics.DrawRectangle(pGreenPen, rectC);
      delete pGreenPen;
   }
   // Draw rectA and rectB with a thin black pen.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   graphics.DrawRectangle(&blackPen, rectA);
   graphics.DrawRectangle(&blackPen, rectB);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Intersect Methods, RectF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF Class

A RectF object stores the upper-left corner, width, and height of a rectangle.

Data Members

Data member | Description
X | REAL. X-coordinate of the upper-left corner of the rectangle. Height of the rectangle.
Y | REAL. Y-coordinate of the upper-left corner of the rectangle. Width of the rectangle.
Width | REAL. Width of the rectangle. Left coordinate of the rectangle.
Height | REAL. Height of the rectangle. Top coordinate of the rectangle.

Constructors

Constructor | Description
RectF | Overloaded. Creates and initializes a new RectF object.

Methods

Method | Description
Clone | Creates a new RectF object from the existing RectF object.
Contains | Overloaded. Determines whether the element specified in the argument is inside the rectangle.
Equals | Determines whether two rectangles are identical.
GetBottom | Gets the bottom coordinate of the rectangle. This is the value of the y-coordinate of the upper-left corner plus the height of the rectangle.
GetBounds | Gets the upper-left coordinate, width, and height of the rectangle.
GetLeft | Gets the left coordinate of the rectangle.
GetLocation | Gets the upper-left coordinates of the rectangle.
GetRight | Gets the right coordinate of the rectangle.
GetSize | Gets the width and height of the rectangle.
GetTop | Gets the top coordinate of the rectangle. This is the y-coordinate of the upper-left corner of the rectangle.
Inflate | Overloaded. Changes the size of a rectangle.
Intersect | Overloaded. Intersects two rectangles.
IntersectsWith | Determines whether two rectangles overlap.
IsEmptyArea | Determines whether a rectangle is empty.
Offset | Overloaded. Moves the rectangle by a specified amount.
Union | Combines two rectangles to produce a third rectangle.

Remarks

The upper-left corner of the rectangle is located at (x, y). The size of the rectangle is measured by width and height. There are methods for high-level functionality, such as moving, resizing, and performing or testing interactions with other rectangles.


RectF Constructors

This topic lists the constructors of the RectF class. For a complete class listing, see RectF Class.

  • RectF()
  • RectF(location, size)
  • RectF(x, y, width, height)


RectF::RectF()

Creates a RectF object and initializes the X and Y data members to zero. This is the default constructor.

RectF(void);

Parameters

This method has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Rect, RectF Constructors
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::RectF(location, size)

Creates a RectF object by using a PointF object to initialize the X and Y data members and uses a SizeF object to initialize the Width and Height data members of this rectangle.

RectF(
  const PointF& location,
  const SizeF& size
);

Parameters

location
[in] Reference to a PointF object that specifies the upper-left corner of this rectangle.
size
[in] Reference to a SizeF object that specifies the width and height of this rectangle.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
PointF, Rect, RectF Constructors, SizeF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::RectF(x, y, width, height)

Creates a RectF object by using four integers to initialize the X, Y, Width, and Height data members.

RectF(
  REAL x,
  REAL y,
  REAL width,
  REAL height
);

Parameters

x
[in] Real number used to initialize the x-coordinate of the upper-left corner of the rectangle.
y
[in] Real number used to initialize the y-coordinate of the upper-left corner of the rectangle.
width
[in] Real number used to initialize the width of this rectangle.
height
[in] Real number used to initialize the height of this rectangle.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Rect, RectF Constructors
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF Methods

This topic lists the methods of the RectF class. For a complete class listing, see RectF Class.

  • Clone()
  • Contains(pt)
  • Contains(rect)
  • Contains(x, y)
  • Equals(rect)
  • GetBottom()
  • GetBounds(rect)
  • GetLeft()
  • GetLocation(point)
  • GetRight()
  • GetSize(size)
  • GetTop()
  • Inflate(dx, dy)
  • Inflate(point)
  • Intersect(c, a, b)
  • Intersect(rect)
  • IntersectsWith(rect)
  • IsEmptyArea()
  • Offset(dx, dy)
  • Offset(point)
  • Union(c, a, b)


RectF::Clone()

The Clone method creates a new RectF object and initializes it with the contents of this RectF object.

RectF* Clone(void) const;

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new RectF object.

Example Code [C++]

The following example creates a RectF object, makes a copy of the RectF object, and draws a rectangle based on the copied RectF object.

VOID Example_Clone(HDC hdc    )
{
   Graphics graphics(hdc);

   // Create a RectF object, and copy it to a new RectF object.
   RectF rect(50, 50, 200, 100);
   RectF* pRect = rect.Clone();

   // Draw a rectangle based on the copied RectF object.
   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawRectangle(&pen, *pRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::Contains Methods

This topic lists the Contains methods of the RectF class. For a complete list of methods for the RectF class, see RectF Methods.

  • Contains(pt)
  • Contains(rect)
  • Contains(x, y)


RectF::Contains(pt)

The Contains method determines whether a point is inside this rectangle.

BOOL Contains(
  const PointF& pt
) const;

Parameters

pt
[in] Reference to a point to be tested.

Return Values

If the point is inside the rectangle, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a RectF object and a PointF object. The code then determines whether the point is inside the rectangle, and then it draws the rectangle and the point.

VOID Example_ContainsPointF(HDC hdc)
{
   Graphics graphics(hdc);

   RectF rect(50, 50, 200, 100);
   PointF point(80, 90);

   if(rect.Contains(point))
   {
      // The point is inside the rectangle.
   }
   // Draw the rectangle and the point.
   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawRectangle(&pen, rect);
   graphics.DrawRectangle(&pen, point.X, point.Y, 1.0f, 1.0f);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Contains Methods, PointF, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::Contains(rect)

The Contains method determines whether another rectangle is inside this rectangle.

BOOL Contains(
  const RectF& rect
) const;

Parameters

rect
[in] Reference to a rectangle to test against this rectangle.

Return Values

If the rectangle is inside this rectangle, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates two RectF objects, determines whether the second RectF object is inside the first RectF object, and then draws the two rectangles.

VOID Example_ContainsRectF(HDC hdc)
{
   Graphics graphics(hdc);

   // Create two RectF objects.
   RectF rect1(50, 50, 200, 100);
   RectF rect2(50, 80, 100, 50);

   // Determine whether rect2 is inside rect1.
   if(rect1.Contains(rect2))
   {
      // rect1 contains rect2.
   }
   // Draw the two rectangles.
   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawRectangle(&pen, rect1);
   graphics.DrawRectangle(&pen, rect2);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Contains Methods, Intersect Methods, IntersectsWith, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::Contains(x, y)

The Contains method determines whether the point (x, y) is inside this rectangle.

BOOL Contains(
  REAL x,
  REAL y
) const;

Parameters

x
[in] Real number that specifies the x-coordinate of the point to be tested.
y
[in] Real number that specifies the y-coordinate of the point to be tested.

Return Values

If the point to be tested (x, y) is inside this rectangle, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a RectF object, determines whether a specified point is inside the RectF object, and then draws the rectangle and the specified point.

VOID Example_ContainsXY(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a RectF object.
   RectF rect(50, 50, 200, 100);

   // Determine whether a specified point is inside the rectangle.
   if(rect.Contains(80, 90))
   {
      // The point (80, 90) is inside rectangle.
   }
   // Draw the rectangle and the point (80, 90).
   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawRectangle(&pen, rect);
   graphics.DrawRectangle(&pen, 80, 90, 1, 1);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Contains Methods, PointF, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::Equals(rect)

The Equals method determines whether two rectangles are the same.

BOOL Equals(
  const RectF& rect
) const;

Parameters

rect
[in] Reference to a rectangle to compare to this rectangle.

Return Values

If the rectangles are the same, this method returns TRUE; otherwise, it returns FALSE.

Remarks

Two rectangles are the same if their X, Y, Width, and Height data members are the same.

Example Code [C++]

The following example creates two RectF objects, moves the second RectF object horizontally by a specified value, and then determines whether the two RectF objects are the same.

VOID Example_Equals(HDC hdc)
{
   Graphics graphics(hdc);

   RectF rect1(50, 50, 200, 100);
   RectF rect2(20, 50, 200, 100);

   rect2.Offset(30, 0);

   if(rect2.Equals(rect1))
   {
      // The two rectangles are the same.
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::GetBottom()

The GetBottom method gets the y-coordinate of the bottom edge of the rectangle.

REAL GetBottom(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the y-coordinate of the bottom edge of the rectangle.

Example Code [C++]

The following example creates a RectF object, gets the bottom edge of the rectangle, and then draws the rectangle and a line at the bottom of the rectangle.

VOID Example_GetBottom(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a RectF object, and get the bottom edge of the rectangle.
   RectF rect(50, 50, 200, 100);
   INT bottom = rect.GetBottom();

   // Draw the rectangle with a thick green pen.
   Pen greenPen(Color(255, 0, 255, 0), 15);
   graphics.DrawRectangle(&greenPen, rect);

   // Draw a thin black line at the bottom of the rectangle.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   graphics.DrawLine(&blackPen, 0, bottom, 300, bottom);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetLeft, GetRight, GetTop, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::GetBounds(rect)

The GetBounds method makes a copy of this rectangle.

VOID GetBounds(
  RectF* rect
) const;

Parameters

rect
[out] Pointer to a RectF object that receives the copy of this rectangle.

Return Values

This method does not return a value.

Example Code [C++]

The following example creates a RectF object, offsets the rectangle, creates a second Rect object by using a copy of the first rectangle, and then draws the second RectF object.

VOID Example_GetBounds(HDC hdc)
{
   Graphics graphics(hdc);

   RectF rect1(50, 40, 200, 100);
   rect1.Offset(30, 20);

   RectF rect2;
   rect1.GetBounds(&rect2);

   Pen pen(Color(255, 0, 0, 255));
   graphics.DrawRectangle(&pen, rect2);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetBottom, GetLeft, GetRight, GetTop, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::GetLeft()

The GetLeft method gets the x- coordinate of the left edge of the rectangle.

REAL GetLeft(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the x-coordinate of the left edge of the rectangle.

Example Code [C++]

The following example creates a RectF object, gets the left edge of the rectangle, and then draws the rectangle and a line along the left edge of the rectangle.

VOID Example_GetLeft(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a RrectF object, and get the left edge of the rectangle.
   RectF rect(50, 50, 200, 100);
   INT left = rect.GetLeft();

   // Draw the rectangle with a thick green pen.
   Pen greenPen(Color(255, 0, 255, 0), 15);
   graphics.DrawRectangle(&greenPen, rect);

   // Draw a thin black line along the left edge of the rectangle.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   graphics.DrawLine(&blackPen, left, 0, left, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetBottom, GetRight, GetTop, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::GetLocation(point)

The GetLocation method gets the coordinates of the upper-left corner of this rectangle.

VOID GetLocation(
  PointF* point
) const;

Parameters

point
[out] Pointer to a PointF object that receives the coordinates of the upper-left corner of this rectangle.

Return Values

This method does not return a value.

Example Code [C++]

This example creates RectF object, gets the point of the upper-left corner of the rectangle, and then draws a rectangle and line from the upper-left corner to the point (0, 0).

VOID Example_GetLocation(HDC hdc)
{
   Graphics graphics(hdc);

   Pen pen(Color(255, 0, 0, 255));
   PointF location;
   RectF rect(50, 40, 200, 50);

   // Get the location of the upper-left corner of the rectangle.
   rect.GetLocation(&location);

   // Draw the rectangle.
   graphics.DrawRectangle(&pen, rect);

   // Draw a line from the upper-left corner of the rectangle to (0, 0).
   graphics.DrawLine(&pen, location, PointF(0, 0));
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetBottom, GetLeft, GetRight, GetTop, PointF, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::GetRight()

The GetRight method gets the x-coordinate of the right edge of the rectangle.

REAL GetRight(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the x-coordinate of the right edge of the rectangle.

Example Code [C++]

The following example creates a RectF object, gets the right edge of the rectangle, and then draws the rectangle and a line along the right edge of the rectangle.

VOID Example_GetRight(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a RectF object, and get the right edge of the rectangle.
   RectF rect(50, 50, 200, 100);
   INT right = rect.GetRight();

   // Draw the rectangle with a thick green pen.
   Pen greenPen(Color(255, 0, 255, 0), 15);
   graphics.DrawRectangle(&greenPen, rect);

   // Draw a thin black line along the right edge of the rectangle.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   graphics.DrawLine(&blackPen, right, 0, right, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetBottom, GetLeft, GetTop, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::GetSize(size)

The GetSize method gets the width and height of this rectangle.

VOID GetSize(
  SizeF* size
) const;

Parameters

size
[out] Pointer to a SizeF object that receives the width and height of this rectangle.

Return Values

This method does not return a value.

Example Code [C++]

The following example creates a RectF object and gets the width and height of the rectangle.

VOID Example_GetSize(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a RectF object and a SizeF object.
   SizeF size;
   RectF rect(50, 40, 200, 100);
   rect.GetSize(&size);

   // Inspect or use the values in size.Width and size.Height.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetBottom, GetLeft, GetRight, GetTop, Rect, SizeF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::GetTop()

The GetTop method gets the y-coordinate of the top edge of the rectangle.

REAL GetTop(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the y-coordinate of the top edge of the rectangle.

Example Code [C++]

The following example creates a RectF object, gets the top edge of the rectangle, and then draws the rectangle and a line along the top edge of the rectangle.

VOID Example_GetTop(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a RectF object, and get the top edge of the rectangle.
   RectF rect(50, 50, 200, 100);
   INT top = rect.GetTop();

   // Draw the rectangle with a thick green pen.
   Pen greenPen(Color(255, 0, 255, 0), 15);
   graphics.DrawRectangle(&greenPen, rect);

   // Draw a thin black line at the top of the rectangle.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   graphics.DrawLine(&blackPen, 0, top, 300, top);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
GetBottom, GetLeft, GetRight, Rect, SizeF
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::Inflate Methods

This topic lists the Inflate methods of the RectF class. For a complete list of methods for the RectF class, see RectF Methods.

  • Inflate(dx, dy)
  • Inflate(point)


RectF::Inflate(dx, dy)

The Inflate method expands the rectangle by dx on the left and right edges, and by dy on the top and bottom edges.

VOID Inflate(
  REAL dx,
  REAL dy
);

Parameters

dx
[in] Real number that specifies the amount to expand the rectangle on the left and right edges.
dy
[in] Real number that specifies the amount to expand the rectangle on the top and bottom edges.

Return Values

This method does not return a value.

Remarks

The x-coordinate of the left edge is decreased by dx, and the x-coordinate of the right edge is increased by dx. The y-coordinate of the top edge is decreased by dy, and the y-coordinate of the bottom edge is increased by dy.

Example Code [C++]

The following example creates a RectF object, draws the rectangle, inflates the rectangle, and then redraws the rectangle.

VOID Example_InflateDxDy(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0));

   // Create and draw a rectangle.
   RectF rect(100, 100, 80, 40);
   graphics.DrawRectangle(&pen, rect);

   // Inflate the rectangle, and then redraw the rectangle.
   rect.Inflate(20, 10);
   graphics.DrawRectangle(&pen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::Inflate(point)

The Inflate method expands the rectangle by the value of point.X on the left and right edges, and by the value of point.Y on the top and bottom edges.

VOID Inflate(
  const PointF& point
);

Parameters

point
[in] Reference to a PointF object whose X data member specifies the amount to expand the rectangle on the left and right edges, and whose Y data member specifies the amount to expand the rectangle on the top and bottom edges.

Return Values

This method does not return a value.

Example Code [C++]

The following example creates a RectF object, draws the rectangle, inflates the rectangle, and then redraws the rectangle.

VOID Example_InflatePointF(HDC hdc)
{
   Graphics graphics(hdc);

   Pen pen(Color(255, 0, 0, 0));
   PointF point(20, 10);

   RectF rect(100, 100, 80, 40);
   graphics.DrawRectangle(&pen, rect);
   rect.Inflate(point);
   graphics.DrawRectangle(&pen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
PointF, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::Intersect Methods

This topic lists the Intersect methods of the RectF class. For a complete list of methods for the RectF class, see RectF Methods.

  • Intersect(c, a, b)
  • Intersect(rect)


RectF::Intersect(c, a, b)

The Intersect method determines the intersection of two rectangles and stores the result in a RectF object.

static BOOL Intersect(
  RectF& c,
  const RectF& a,
  const RectF& b
);

Parameters

c
[out] Reference to a RectF object that receives the intersection of the two rectangles.
a
[in] Reference to one of the two rectangles to be intersected.
b
[in] Reference to one of the two rectangles to be intersected.

Return Values

If the intersection of the two rectangles is not empty, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates three RectF objects, draws the first two rectangles, and then draws the third rectangle that indicates the intersection of the first two rectangles.

VOID Example_IntersectABC(HDC hdc)
{
   Graphics graphics(hdc);
   Pen* pGreenPen;

   // Create three RectF objects.
   RectF rectA(50, 50, 200, 100);
   RectF rectB(70, 20, 100, 200);
   RectF rectC;

   // Draw rectA and rectB with a thin black pen.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   graphics.DrawRectangle(&blackPen, rectA);
   graphics.DrawRectangle(&blackPen, rectB);

   // Draw the rectangle that indicates the intersection of the two rectangles.
   if(rectC.Intersect(rectC, rectA, rectB))
   {
      // rectC is not empty.
      // Draw the intersection with a thick green pen.
      pGreenPen = new Pen(Color(255, 0, 255, 0), 7);
      graphics.DrawRectangle(pGreenPen, rectC);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Intersect Methods, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::Intersect(rect)

The Intersect method replaces this rectangle with the intersection of itself and another rectangle.

BOOL Intersect(
  const RectF& rect
);

Parameters

rect
[in] Reference to a rectangle that will be intersected with this rectangle.

Return Values

If the intersection of the two rectangles is not empty, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates three RectF objects, draws the first two rectangles, and then draws the third rectangle that indicates the intersection of the first two rectangles.

VOID Example_IntersectRectF(HDC hdc)
{
   Graphics graphics(hdc);

   // Create two RectF objects.
   RectF rect1(50, 50, 200, 100);
   RectF rect2(70, 20, 100, 200);

   // Draw rect1 and rect2 with a thin black pen.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   graphics.DrawRectangle(&blackPen, rect1);
   graphics.DrawRectangle(&blackPen, rect2);

   // Form the intersection of rect1 and rect2, and store
   // the result in rect1.
   rect1.Intersect(rect2);

   // Draw the new rect1 with a thick green pen.
   Pen greenPen(Color(255, 0, 255, 0), 7);
   graphics.DrawRectangle(&greenPen, rect1);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Intersect Methods, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::IntersectsWith(rect)

The IntersectsWith method determines whether this rectangle intersects another rectangle.

BOOL IntersectsWith(
  const RectF& rect
) const;

Parameters

rect
[in] Reference to a rectangle to test.

Return Values

If the intersection of the two rectangles is not empty, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates two RectF objects, draws the first rectangle, and then determines if there is an intersection between the two rectangles. If the two rectangles intersect, the code then draws the second rectangle.

VOID Example_IntersectsWith(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0), 1);

   // Create two RectF objects.
   RectF rect1(50, 50, 200, 100);
   RectF rect2(70, 20, 100, 200);

   // Draw rect1.   graphics.DrawRectangle(&pen, rect1);
   // If rect1 intersects with rect2 then draw rect2.
   if(rect2.IntersectsWith(rect1))
      graphics.DrawRectangle(&pen, rect2);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Intersect Methods, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::IsEmptyArea()

The IsEmptyArea method determines whether this rectangle is empty.

BOOL IsEmptyArea(void) const;

Parameters

This method has no parameters.

Return Values

If the rectangle is empty, this method returns TRUE; otherwise, it returns FALSE.

Remarks

A rectangle is defined as empty if either the width or the height is zero or less.

Example Code [C++]

The following example creates a RectF object, inflates the dimensions of the rectangle, and determines whether the rectangle is empty.

VOID Example_IsEmptyArea(HDC hdc)
{
   Graphics graphics(hdc);
   RectF rect(50, 50, 200, 100);
   rect.Inflate(0, -120);

   if(rect.IsEmptyArea())

   // The rectangle does not enclose any area.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Inflate Methods, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::Offset Methods

This topic lists the Offset methods of the RectF class. For a complete list of methods for the RectF class, see RectF Methods.

  • Offset(dx, dy)
  • Offset(point)


RectF::Offset(dx, dy)

The Offset method moves the rectangle by dx horizontally and by dy vertically.

VOID Offset(
  REAL dx,
  REAL dy
);

Parameters

dx
[in] Real number that specifies the amount to move the rectangle horizontally.
dy
[in] Real number that specifies the amount to move the rectangle vertically.

Return Values

This method does not return a value.

Example Code [C++]

The following example creates a RectF object, draws the rectangle, offsets the rectangle, and then redraws the rectangle.

VOID Example_OffsetDxDy(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0));

   // Create a RectF object, and draw the rectangle.
   RectF rect(100, 100, 80, 40);
   graphics.DrawRectangle(&pen, rect);

   // Offset the rectangle, and redraw the rectangle.
   rect.Offset(30, 20);
   graphics.DrawRectangle(&pen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Offset Methods, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::Offset(point)

The Offset method moves this rectangle horizontally a distance of point.X and vertically a distance of point.Y.

VOID Offset(
  const PointF& point
);

Parameters

point
[in] Reference to a PointF object whose X data member specifies the distance to move the rectangle horizontally and whose Y data member specifies the distance to move the rectangle vertically.

Return Values

This method does not return a value.

Example Code [C++]

The following example creates a PointF object and a RectF object and draws the rectangle. The code then offsets the rectangle by the specified PointF object and redraws the rectangle.

VOID Example_OffsetPointF(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0));

   // Create a PointF object.
   PointF point(30, 20);

   // Create a RectF object, and draw the rectangle.
   RectF rect(100, 100, 80, 40);
   graphics.DrawRectangle(&pen, rect);

   // Offset the rectangle by the PointF object.
   rect.Offset(point);

   // Redraw the rectangle.
   graphics.DrawRectangle(&pen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Offset Methods, PointF, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


RectF::Union(c, a, b)

The Union method determines the union of two rectangles and stores the result in a RectF object.

static BOOL Union(
  RectF& c,
  const RectF& a,
  const RectF& b
);

Parameters

c
[out] Reference to a RectF object that receives the union of the two rectangles.
a
[in] Reference to one of the two rectangles used to form the union.
b
[in] Reference to one of the two rectangles used to form the union.

Return Values

If the union of two rectangles is not empty, this method returns TRUE; otherwise, it returns FALSE.

Remarks

In GDI+, the union of two rectangles is the smallest rectangle that encloses the two rectangles. A rectangle is defined as empty if its width or height is less than or equal to zero.

Example Code [C++]

The following example creates three rectangles. The code forms the union of the first two rectangles and stores the result in the third rectangle. The code determines whether the union is nonempty and, if so, draws the union.

VOID Example_UnionABC(HDC hdc)
{
   Graphics graphics(hdc);
   Pen* pGreenPen;

   // Create three RectF objects.
   RectF rectA(50, 50, 200, 100);
   RectF rectB(70, 20, 100, 200);
   RectF rectC;

   // Determine the union of rectA and rectB, and store the result in rectC.
   if(rectC.Union(rectC, rectA, rectB))
   {
      // rectC is not empty.
      // Draw the union with a thick green pen.
      pGreenPen = new Pen(Color(255, 0, 255, 0), 7);
      graphics.DrawRectangle(pGreenPen, rectC);
      delete pGreenPen;
   }
   // Draw rectA and rectB with a thin black pen.
   Pen blackPen(Color(255, 0, 0, 0), 1);
   graphics.DrawRectangle(&blackPen, rectA);
   graphics.DrawRectangle(&blackPen, rectB);}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Intersect Methods, Rect
Tasks and Examples
Using a Pen to Draw Lines and Rectangles
Concepts
Pens, Lines, and Rectangles


Region Class

The Region class describes an area of the display surface. The area can be any shape. In other words, the boundary of the area can be a combination of curved and straight lines. Regions can also be created from the interiors of rectangles, paths, or a combination of these. Regions are used in clipping and hit-testing operations.

Inheritance

GdiplusBase
Region

Constructors

Constructor | Description
Region | Overloaded. Creates and initializes a new Region object.

Methods

Method | Description
Clone | Makes a copy of the existing Region object and returns the address of the new Region object.
Complement | Overloaded. Updates this region to the portion of the specified element's interior that does not intersect this region.
Equals | Compares this region to another region to determine whether they are equal.
Exclude | Overloaded. Updates this region to the portion of itself that does not intersect the specified element's interior.
FromHRGN | Creates a GDI+ Region object from a GDI region.
GetBounds | Overloaded. Gets a rectangle that encloses this region.
GetData | Gets data that describes this region.
GetDataSize | Gets the number of bytes of data that describes this region.
GetHRGN | Creates a GDI region from this region.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetRegionScans | Overloaded. Gets an array of rectangles that approximate this region.
GetRegionScansCount | Gets the number of rectangles that approximate this region.
Intersect | Overloaded. Updates this region to the portion of itself that intersects the specified element's interior.
IsEmpty | Determines whether this region is empty.
IsInfinite | Determines whether this region is infinite.
IsVisible | Overloaded. Determines whether the element specified by the parameter is inside or partially inside this region.
MakeEmpty | Updates this region to an empty region.
MakeInfinite | Updates this region to an infinite region.
Transform | Transforms this region.
Translate | Overloaded. Offsets this region.
Union | Overloaded. Updates this region to all portions (intersecting and nonintersecting) of itself and all portions of the specified element's interior.
Xor | Overloaded. Updates this region to the nonintersecting portions of itself and the specified element's interior.
~Region | Region object destructor.

Remarks

A GDI+ region is stored in world coordinates whereas a GDI region is stored in device coordinates. Therefore, a GDI+ region is scalable and a GDI region is not. For more information, see Scalable Regions.

An application can use regions to clip the output of drawing operations. The Window Manager uses regions to define the drawing area of windows. These regions are called clipping regions. An application can also use regions in hit-testing operations, such as checking whether a point is in a region or whether a rectangle intersects a region. For more information, see Regions, Clipping, and Using Regions.


Region Constructors

This topic lists the constructors of the Region class. For a complete class listing, see Region Class.

  • Region()
  • Region(path)
  • Region(hRgn)
  • Region(Rect& rect)
  • Region(RectF& rect)
  • Region(regionData, size)


Region::Region()

Creates a region that is infinite. This is the default constructor.

Region(void);

Parameters

This method has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.


Region::Region(path)

Creates a region that is defined by a path (a GraphicsPath object) and has a fill mode that is contained in the GraphicsPath object.

Region(
  const GraphicsPath* path
);

Parameters

path
[in] Pointer to a GraphicsPath object that specifies the path.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, Status
Tasks and Examples
Using Regions
Concepts
Regions


Region::Region(hRgn)

Creates a region that is identical to the region that is specified by a handle to a GDI region.

Region(
  HRGN hRgn
);

Parameters

hRgn
[in] Handle to an existing GDI region.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.


Region::Region(Rect& rect)

Creates a region that is defined by a rectangle.

Region(
  const Rect& rect
);

Parameters

rect
[in] Reference to a rectangle.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect


Region::Region(RectF& rect)

Creates a region that is defined by a rectangle.

Region(
  const RectF& rect
);

Parameters

rect
[in] Reference to a rectangle.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect


Region::Region(regionData, size)

Creates a region that is defined by data obtained from another region.

Region(
  const BYTE* regionData,
  INT size
);

Parameters

regionData
[in] Pointer to an array of bytes that specifies a region. The data contained in the bytes is obtained from another region by using the GetData method.
size
[in] Integer that specifies the number of bytes in the regionData array.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.


Region Methods

This topic lists the methods of the Region class. For a complete class listing, see Region Class.

  • Clone()
  • Complement(path)
  • Complement(Rect& rect)
  • Complement(RectF& rect)
  • Complement(region)
  • Equals(region, g)
  • Exclude(path)
  • Exclude(Rect& rect)
  • Exclude(RectF& rect)
  • Exclude(region)
  • FromHRGN(hRgn)
  • GetBounds(Rect* rect, Graphics* g)
  • GetBounds(RectF* rect, Graphics* g)
  • GetData(buffer, bufferSize, sizeFilled)
  • GetDataSize()
  • GetHRGN(g)
  • GetLastStatus()
  • GetRegionScans(Matrix* matrix, Rect* rects, INT* count)
  • GetRegionScans(Matrix* matrix, RectF* rects, INT* count)
  • GetRegionScansCount(matrix)
  • Intersect(path)
  • Intersect(Rect& rect)
  • Intersect(RectF& rect)
  • Intersect(region)
  • IsEmpty(g)
  • IsInfinite(g)
  • IsVisible(Point& point, Graphics* g)
  • IsVisible(PointF& point, Graphics* g)
  • IsVisible(Rect& rect, Graphics* g)
  • IsVisible(RectF& rect, Graphics* g)
  • IsVisible(INT x, INT y, Graphics* g)
  • IsVisible(REAL x, REAL y, Graphics* g)
  • IsVisible(INT x, INT y, INT width, INT height, Graphics* g)
  • IsVisible(REAL x, REAL y, REAL width, REAL height, Graphics* g)
  • MakeEmpty()
  • MakeInfinite()
  • Transform(matrix)
  • Translate(INT dx, INT dy)
  • Translate(REAL dx, REAL dy)
  • Union(path)
  • Union(Rect& rect)
  • Union(RectF& rect)
  • Union(region)
  • Xor(path)
  • Xor(Rect& rect)
  • Xor(RectF& rect)
  • Xor(region)


Region::Clone()

The Clone method makes a copy of this Region object and returns the address of the new Region object.

Region* Clone(void);

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new Region object.

Example Code [C++]

The following example creates two regions, one from a rectangle and the other from a path. Next, the code clones the region that was created from a path and uses a solid brush to fill the cloned region. Then, it forms the union of the two regions and fills it.

VOID Example_Clone(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush solidBrush(Color(255, 255, 0, 0));
   SolidBrush alphaBrush(Color(128, 0, 0, 255));

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);
   GraphicsPath path;

   path.AddClosedCurve(points, 6);

   // Create a region from a rectangle.
   Region rectRegion(rect);

   // Create a region from a curved path.
   Region pathRegion(&path);

   // Make a copy (clone) of the curved region.
   Region* pClonedRegion = pathRegion.Clone();

   // Fill the cloned region with a red brush.
   graphics.FillRegion(&solidBrush, pClonedRegion);

   // Form the union of the cloned region and the rectangular region.
   pClonedRegion->Union(&rectRegion);

   // Fill the union of the two regions with a semitransparent blue brush.
   graphics.FillRegion(&alphaBrush, pClonedRegion);

   delete pClonedRegion;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.


Region::Complement Methods

This topic lists the Complement methods of the Region class. For a complete list of methods for the Region class, see Region Methods.

  • Complement(path)
  • Complement(Rect& rect)
  • Complement(RectF& rect)
  • Complement(region)


Region::Complement(path)

The Complement method updates this region to the portion of the specified path's interior that does not intersect this region.

Status Complement(
  const GraphicsPath* path
);

Parameters

path
[in] Pointer to a GraphicsPath object that specifies the path to use to update this Region object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a path. Next, the code creates a region from a rectangle and then uses the path to update the region.

VOID Example_ComplementPath(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush solidBrush(Color(255, 255, 0, 0));

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);
   GraphicsPath path;

   path.AddClosedCurve(points, 6);

   // Create a region from a rectangle.
   Region region(rect);

   // Update the region so that it consists of all points inside a path but
   // outside the rectangular region.
   region.Complement(&path);

   graphics.FillRegion(&solidBrush, &region);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, Rect, Status


Region::Complement(Rect& rect)

The Complement method updates this region to the portion of the specified rectangle's interior that does not intersect this region.

Status Complement(
  const Rect& rect
);

Parameters

rect
[in] Reference to a rectangle to use to update this Region object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a path and then uses a rectangle to update the region.

VOID Example_ComplementRect(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush solidBrush(Color(255, 255, 0, 0));

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);

   GraphicsPath path;

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region region(&path);

   // Update the region so that it consists of all points inside the
   // rectangle but outside the path region.
   region.Complement(rect);

   graphics.FillRegion(&solidBrush, &region);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Region::Complement(RectF& rect)

The Complement method updates this region to the portion of the specified rectangle's interior that does not intersect this region.

Status Complement(
  const RectF& rect
);

Parameters

rect
[in] Reference to a rectangle to use to update this Region object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a path and then uses a rectangle to update the region.

VOID Example_ComplementRectF(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush solidBrush(Color(255, 255, 0, 0));

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   RectF rect(65.3f, 15.1f, 70.0f, 45.8f);

   GraphicsPath path;

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region region(&path);

   // Update the region so that it consists of all points inside the
   // rectangle but outside the path region.
   region.Complement(rect);

   graphics.FillRegion(&solidBrush, &region);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
RectF, Status


Region::Complement(region)

The Complement method updates this region to the portion of another region that does not intersect this region.

Status Complement(
  const Region* region
);

Parameters

region
[in] Pointer to a Region object to use to update this Region object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a rectangle and a region from a path. Then the code uses the path region to update the rectangular region.

VOID Example_ComplementReg(HDC hdc)
{
   Graphics graphics(hdc);

  SolidBrush solidBrush(Color(255, 255, 0, 0));

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);
   GraphicsPath path;

   path.AddClosedCurve(points, 6);

   // Create a region from a rectangle.
   Region rectRegion(rect);

   // Create a region from a path.
   Region pathRegion(&path);

   // Update the rectangular region so that it consists of all points inside
   // the path region but outside the rectangular region.
   rectRegion.Complement(&pathRegion);

   graphics.FillRegion(&solidBrush, &rectRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Region::Equals(region, g)

The Equals method determines whether this region is equal to a specified region.

BOOL Equals(
  const Region* region,
  const Graphics* g
) const;

Parameters

region
[in] Pointer to a Region object to test against this Region object.
g
[in] Pointer to a Graphics object that contains the world and page transformations required to calculate the device coordinates of this region and the region that is specified by the region parameter.

Return Values

If this region is identical to the specified region, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates two regions, one from a rectangle and the other from a path. The code then tests to determine whether the two regions are the same and performs a task based on the result of the test.

VOID Example_Equals(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush solidBrush(Color(255, 255, 0, 0));
   SolidBrush alphaBrush(Color(128, 0, 0, 255));

   Point points[] = {
      Point(20, 20),
      Point(120, 20),
      Point(120, 70),
      Point(20, 70)};

   Rect rect(20, 20, 100, 50);
   GraphicsPath path;

   path.AddPolygon(points, 4);

   // Create a region from a rectangle.
   Region rectRegion(rect);
   graphics.FillRegion(&solidBrush, &rectRegion);

   // Create a region from a path.
   Region pathRegion(&path);
   graphics.FillRegion(&alphaBrush, &pathRegion);

   if (pathRegion.Equals(&rectRegion, &graphics))
   {
      // The two regions are the same.
      // Perform some task.
   }
   else
   {
      // The two regions are not the same.
      // Perform a different task.
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, Rect


Region::Exclude Methods

This topic lists the Exclude methods of the Region class. For a complete list of methods for the Region class, see Region Methods.

  • Exclude(path)
  • Exclude(Rect& rect)
  • Exclude(RectF& rect)
  • Exclude(region)


Region::Exclude(path)

The Exclude method updates this region to the portion of itself that does not intersect the specified path's interior.

Status Exclude(
  const GraphicsPath* path
);

Parameters

path
[in] Pointer to a GraphicsPath object that specifies the path to use to update this Region object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a rectangle and then uses a path to update the region.

VOID Example_ExcludePath(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);
   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a rectangle.
   Region rectRegion(rect);

   // Exclude the intersecting portion of the path interior from the region.
   rectRegion.Exclude(&path);

   graphics.FillRegion(&solidBrush, &rectRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, Status


Region::Exclude(Rect& rect)

The Exclude method updates this region to the portion of itself that does not intersect the specified rectangle's interior.

Status Exclude(
  const Rect& rect
);

Parameters

rect
[in] Reference to a rectangle to use to update this Region object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a path and then uses a rectangle to update the region.

VOID Example_ExcludeRect(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);

   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);

   // Exclude a rectangle from the path region.
   pathRegion.Exclude(rect);

   graphics.FillRegion(&solidBrush, &pathRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Region::Exclude(RectF& rect)

The Exclude method updates this region to the portion of itself that does not intersect the specified rectangle's interior.

Status Exclude(
  const RectF& rect
);

Parameters

rect
[in] Reference to a rectangle to use to update this Region object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a path and then uses a rectangle to update the region.

VOID Example_ExcludeRectF(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   RectF rect(65.3f, 15.1f, 70.0f, 45.8f);

   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);

   // Exclude a rectangle from the path region.
   pathRegion.Exclude(rect);

   graphics.FillRegion(&solidBrush, &pathRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
RectF, Status


Region::Exclude(region)

The Exclude method updates this region to the portion of itself that does not intersect another region.

Status Exclude(
  const Region* region
);

Parameters

region
[in] Pointer to a Region object to use to update this Region object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates two regions, one from a rectangle and the other from a path. Then the code uses the rectangular region to update the path region.

VOID Example_ExcludeReg(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);
   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a rectangle.
   Region rectRegion(rect);

   // Create a region from a path.
   Region pathRegion(&path);

   // Exclude a rectangle region from the path region.
   pathRegion.Exclude(&rectRegion);

   graphics.FillRegion(&solidBrush, &pathRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.


Region::FromHRGN(hRgn)

The FromHRGN method creates a GDI+ Region object from a GDI region.

static Region* FromHRGN(
  HRGN hRgn
);

Parameters

hRgn
[in] Handle to an existing GDI region.

Return Values

This method returns a pointer to the new Region object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.


Region::GetBounds Methods

This topic lists the GetBounds methods of the Region class. For a complete list of methods for the Region class, see Region Methods.

  • GetBounds(Rect* rect, Graphics* g)
  • GetBounds(RectF* rect, Graphics* g)


Region::GetBounds(Rect* rect, Graphics* g)

The GetBounds method gets a rectangle that encloses this region.

Status GetBounds(
  Rect* rect,
  const Graphics* g
) const;

Parameters

rect
[out] Pointer to a Rect object that receives the enclosing rectangle.
g
[in] Pointer to a Graphics object that contains the world and page transformations required to calculate the device coordinates of this region and the rectangle.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The current world and page transformations of the graphics object are used to calculate the region and the rectangle as they are drawn on the display device. The rectangle returned by GetBounds is not always the smallest possible rectangle.

Example Code [C++]

The following example creates a region from a path, gets the region's enclosing rectangle, and then displays both.

VOID Example_GetBoundsRect(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   GraphicsPath path;
    SolidBrush solidBrush(Color(255, 255, 0, 0));
    Pen pen(Color(255, 0, 0, 0));
    Rect rect;

   path.AddClosedCurve(points, 6);

    // Create a region from a path.
    Region pathRegion(&path);

    // Get the region's enclosing rectangle.
    pathRegion.GetBounds(&rect, &graphics);

    // Show the region and the enclosing rectangle.
    graphics.FillRegion(&solidBrush, &pathRegion);
    graphics.DrawRectangle(&pen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, Rect, Status


Region::GetBounds(RectF* rect, Graphics* g)

The GetBounds method gets a rectangle that encloses this region.

Status GetBounds(
  RectF* rect,
  const Graphics* g
) const;

Parameters

rect
[out] Pointer to a RectF object that receives the enclosing rectangle.
g
[in] Pointer to a Graphics object that contains the world and page transformations required to calculate the device coordinates of this region and the rectangle.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The current world and page transformations of the graphics object are used to calculate the region and the rectangle as they are drawn on the display device. The rectangle returned by GetBounds is not always the smallest possible rectangle.

Example Code [C++]

The following example creates a region from a path, gets the region's enclosing rectangle, and then displays both.

VOID Example_GetBoundsRectF(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   GraphicsPath path;
    SolidBrush solidBrush(Color(255, 255, 0, 0));
    Pen pen(Color(255, 0, 0, 0));
    RectF rect;

   path.AddClosedCurve(points, 6);

    // Create a region from a path.
    Region pathRegion(&path);

    // Get the region's enclosing rectangle.
    pathRegion.GetBounds(&rect, &graphics);

    // Show the region and the enclosing rectangle.
    graphics.FillRegion(&solidBrush, &pathRegion);
    graphics.DrawRectangle(&pen, rect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GraphicsPath


Region::GetData(buffer, bufferSize, sizeFilled)

The GetData method gets data that describes this region.

Status GetData(
  BYTE* buffer,
  UINT bufferSize,
  UINT* sizeFilled
) const;

Parameters

buffer
[out] Pointer to an array of BYTEs that receives the region data.
bufferSize
[in] Integer that specifies the size, in bytes, of the buffer array. The size of the buffer array can be greater than or equal to the number of bytes required to store the region data. The exact number of bytes required can be determined by calling the GetDataSize method.
sizeFilled
[out] Optional. Pointer to an INT that receives the number of bytes of data actually received by the buffer array. The default value is NULL.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The GetDataSize method can be used before the GetData method to determine the number of bytes needed to store the region data. Then, you can allocate a buffer that is the correct size to store the region data and set the buffer parameter to point to the buffer.

Example Code [C++]

The following example creates a region from a path and then gets the data that describes the region.

VOID Example_GetData(HDC)
{
   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   GraphicsPath path;
   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);

   // Get the region data.
   UINT bufferSize = 0;
   UINT sizeFilled = 0;
   BYTE* pData = NULL;

   bufferSize = pathRegion.GetDataSize();

   pData = new BYTE[bufferSize];
   pathRegion.GetData(pData, bufferSize, &sizeFilled);

   // Inspect or use the region data.
   ...

   delete pData;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.


Region::GetDataSize()

The GetDataSize method gets the number of bytes of data that describes this region.

UINT GetDataSize(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the number of bytes of region data.

Remarks

The GetDataSize method can be used before the GetData method to determine the number of bytes needed to store the region data. Then, you can allocate a buffer that is the correct size to store the region data that is obtained by the GetData.

Example Code [C++]

The following example creates a region from a path and then gets the data that describes the region.

VOID Example_GetData(HDC)
{
   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   GraphicsPath path;
   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);

   // Get the region data.
   UINT bufferSize = 0;
   UINT sizeFilled = 0;
   BYTE* pData = NULL;

   bufferSize = pathRegion.GetDataSize();
   pData = (BYTE*)malloc(bufferSize*sizeof(BYTE));
   pathRegion.GetData(pData, bufferSize, &sizeFilled);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GetData


Region::GetHRGN(g)

The GetHRGN method creates a GDI region from this region.

HRGN GetHRGN(
  const Graphics* g
) const;

Parameters

g
[in] Pointer to a Graphics object that contains the world and page transformations required to calculate the device coordinates of this region.

Return Values

This method returns a Windows handle to a GDI region that is created from this region.

Remarks

It is the caller's responsibility to call the GDI function DeleteObject to free the GDI region when it is no longer needed.

Example Code [C++]

The following example creates a GDI+ region from a path and then uses the GDI+ region to create a GDI region. The code then uses a GDI function to display the GDI region.

VOID Example_GetHRGN(HDC hdc)
{
   Graphics graphics(hdc);

    Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   GraphicsPath path;
   path.AddClosedCurve(points, 6);

    // Create a region from a path.
    Region pathRegion(&path);

   // Get a handle to a GDI region.
   HRGN hRegion;
   hRegion = pathRegion.GetHRGN(&graphics);

   // Use GDI to display the region.
   HBRUSH hBrush = CreateSolidBrush(RGB(255, 0, 0));
   FillRgn(hdc, hRegion, hBrush);

   DeleteObject(hBrush);
   DeleteObject(hRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, Rect, DeleteObject


Region::GetLastStatus()

The GetLastStatus method returns a value that indicates the nature of this Region object's most recent method failure.

Status GetLastStatus(void);

Parameters

This method has no parameters.

Return Values

The GetLastStatus method returns an element of the Status enumeration.

If no methods invoked on this Region object have failed since the previous call to GetLastStatus, then GetLastStatus returns Ok.

If at least one method invoked on this Region object has failed since the previous call to GetLastStatus, then GetLastStatus returns a value that indicates the nature of the most recent failure.

Remarks

You can call GetLastStatus immediately after constructing a Region object to determine whether the constructor succeeded.

The first time you call the GetLastStatus method of a Region object, it returns Ok if the constructor succeeded and all methods invoked so far on the Region object succeeded. Otherwise, it returns a value that indicates the nature of the most recent failure.

Example Code [C++]

The following example creates a region from a path. Next, the code calls GetBounds, followed by a call to GetDataSize. The code then calls GetLastStatus. If all method calls have been successful up to this point, GetLastStatus returns OK.

VOID Example_GetLastStatus(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect;
   UINT size;
   GraphicsPath path;

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);

   pathRegion.GetBounds(&rect, &graphics);
   size = pathRegion.GetDataSize();

   if(pathRegion.GetLastStatus() == Ok)
   {
       // All methods called thus far have been successful.
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.


Region::GetRegionScans Methods

This topic lists the GetRegionScans methods of the Region class. For a complete list of methods for the Region class, see Region Methods.

  • GetRegionScans(Matrix* matrix, Rect* rects, INT* count)
  • GetRegionScans(Matrix* matrix, RectF* rects, INT* count)


Region::GetRegionScans(Matrix* matrix, Rect* rects, INT* count)

The GetRegionScans method gets an array of rectangles that approximate this region. The region is transformed by a specified matrix before the rectangles are calculated.

Status GetRegionScans(
  const Matrix* matrix,
  Rect* rects,
  INT* count
) const;

Parameters

matrix
[in] Pointer to a Matrix object that is used to transform the region.
rects
[out] Pointer to an array of Rect objects that receives the rectangles.
count
[out] Pointer to an INT that receives a value that indicates the number of rectangles that approximate this region. The value is valid even if rects is a NULL pointer.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The GetRegionScansCount method can be used first to determine the number of rectangles. Then, you can allocate a buffer that is the correct size and set the rects parameter to point to the buffer.

Example Code [C++]

The following example creates a region from a path and gets a set of rectangles that approximate the region. The code then draws each of the rectangles.

VOID Example_GetRegionScansRect(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush solidBrush(Color(255, 255, 0, 0));
   Pen pen(Color(255, 0, 0, 0));
   GraphicsPath path;
   Matrix matrix;
   Rect* rects = NULL;
   INT count = 0;

   // Create a region from a path.
   path.AddEllipse(10, 10, 50, 300);
   Region pathRegion(&path);
   graphics.FillRegion(&solidBrush, &pathRegion);

   // Get the rectangles.
   graphics.GetTransform(&matrix);
   count = pathRegion.GetRegionScansCount(&matrix);
   rects = (Rect*)malloc(count*sizeof(Rect));
   pathRegion.GetRegionScans(&matrix, rects, &count);

   // Draw the rectangles.
   for(INT j = 0; j < count; ++j)
      graphics.DrawRectangle(&pen, rects[j]);

   free(rects);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Matrix, Rect, Status, GetRegionScansCount
Tasks and Examples
Hit Testing with a Region
Concepts
Regions


Region::GetRegionScans(Matrix* matrix, RectF* rects, INT* count)

The GetRegionScans method gets an array of rectangles that approximate this region. The region is transformed by a specified matrix before the rectangles are calculated.

Status GetRegionScans(
  const Matrix* matrix,
  RectF* rects,
  INT* count
) const;

Parameters

matrix
[in] Pointer to a Matrix object that is used to transform the region.
rects
[out] Pointer to an array of RectF objects that receives the rectangles.
count
[out] Pointer to an INT that receives a value that indicates the number of rectangles that approximate this region. The value is valid even if rects is a NULL pointer.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The GetRegionScansCount method can be used first to determine the number of rectangles. Then, you can allocate a buffer that is the correct size and set the rects parameter to point to the buffer.

Example Code [C++]

The following example creates a region from a path and gets a set of rectangles that approximate the region. The code then draws each of the rectangles.

VOID Example_GetRegionScansRectF(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush solidBrush(Color(255, 255, 0, 0));
   Pen pen(Color(255, 0, 0, 0));
   GraphicsPath path;
   Matrix matrix;
   RectF* rects = NULL;
   INT count = 0;

   // Create a region from a path.
   path.AddEllipse(10, 10, 50, 300);
   Region pathRegion(&path);
   graphics.FillRegion(&solidBrush, &pathRegion);

   // Get the rectangles.
   graphics.GetTransform(&matrix);
   count = pathRegion.GetRegionScansCount(&matrix);
   rects = (RectF*)malloc(count*sizeof(RectF));
   pathRegion.GetRegionScans(&matrix, rects, &count);

   // Draw the rectangles.
   for(INT j = 0; j < count; ++j)
      graphics.DrawRectangle(&pen, rects[j]);

   free(rects);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Matrix, Rect, Status, GetRegionScansCount
Tasks and Examples
Hit Testing with a Region
Concepts
Regions


Region::GetRegionScansCount(matrix)

The GetRegionScansCount method gets the number of rectangles that approximate this region. The region is transformed by a specified matrix before the rectangles are calculated.

UINT GetRegionScansCount(
  const Matrix* matrix
) const;

Parameters

matrix
[in] Pointer to a matrix that is used to transform the region.

Return Values

This method returns an integer that indicates the number of rectangles that approximate this region.

Remarks

The GetRegionScansCount method can be used before the GetRegionScans method to determine the number of rectangles. Then, you can allocate a buffer that is the correct size to store the rectangles that are obtained with the GetRegionScans method.

Example Code [C++]

The following example creates a region from a path and gets a set of rectangles that approximate the region. The code then draws each of the rectangles.

VOID Example_GetRegionScansCount(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush solidBrush(Color(255, 255, 0, 0));
   Pen pen(Color(255, 0, 0, 0));
   GraphicsPath path;
   Matrix matrix;
   RectF* rects = NULL;
   INT count = 0;

   // Create a region from a path.
   path.AddEllipse(10, 10, 50, 300);
   Region pathRegion(&path);
   graphics.FillRegion(&solidBrush, &pathRegion);

   // Get the rectangles.
   graphics.GetTransform(&matrix);
   count = pathRegion.GetRegionScansCount(&matrix);
   rects = (RectF*)malloc(count*sizeof(RectF));
   pathRegion.GetRegionScans(&matrix, rects, &count);

   // Draw the rectangles.
   for(INT j = 0; j < count; ++j)
      graphics.DrawRectangle(&pen, rects[j]);

   free(rects);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Matrix, Rect, GetRegionScans


Region::Intersect Methods

This topic lists the Intersect methods of the Region class. For a complete list of methods for the Region class, see Region Methods.

  • Intersect(path)
  • Intersect(Rect& rect)
  • Intersect(RectF& rect)
  • Intersect(region)


Region::Intersect(path)

The Intersect method updates this region to the portion of itself that intersects the specified path's interior.

Status Intersect(
  const GraphicsPath* path
);

Parameters

path
[in] Pointer to a GraphicsPath object that specifies the path to use to update this region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a rectangle and then uses a path to update the region.

VOID Example_IntersectPath(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);
   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a rectangle.
   Region rectRegion(rect);

   // Update the region to the portion that intersects with the path.
   rectRegion.Intersect(&path);

   graphics.FillRegion(&solidBrush, &rectRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, Rect, Status


Region::Intersect(Rect& rect)

The Intersect method updates this region to the portion of itself that intersects the specified rectangle's interior.

Status Intersect(
  const Rect& rect
);

Parameters

rect
[in] Reference to a rectangle to use to update this region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a path and then uses a rectangle to update the region.

VOID Example_IntersectRect(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);
   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
    Region pathRegion(&path);

   // Update the region to the portion that intersects with the rectangle.
   pathRegion.Intersect(rect);

   graphics.FillRegion(&solidBrush, &pathRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Region::Intersect(RectF& rect)

The Intersect method updates this region to the portion of itself that intersects the specified rectangle's interior.

Status Intersect(
  const RectF& rect
);

Parameters

rect
[in] Reference to a rectangle to use to update this Region object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a path and then uses a rectangle to update the region.

VOID Example_IntersectRectF(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   RectF rect(65.2f, 15.0f, 70.9f, 45.0f);
   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);

   // Update the region to the portion that intersects with the rectangle.
   pathRegion.Intersect(rect);

   graphics.FillRegion(&solidBrush, &pathRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Region::Intersect(region)

The Intersect method updates this region to the portion of itself that intersects another region.

Status Intersect(
  const Region* region
);

Parameters

region
[in] Pointer to a Region object to use to update this Region object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates two regions, one from a path and the other from a rectangle. The code then uses the rectangular region to update the path region.

VOID Example_IntersectReg(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);
   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);

   // Create a region from a rectangle.
   Region rectRegion(rect);

   // Update the region to the portion that intersects with another region.
   pathRegion.Intersect(&rectRegion);

   graphics.FillRegion(&solidBrush, &pathRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Region::IsEmpty(g)

The IsEmpty method determines whether this region is empty.

BOOL IsEmpty(
  const Graphics* g
) const;

Parameters

g
[in] Pointer to a Graphics object that contains the world and page transformations required to calculate the device coordinates of this region.

Return Values

If this region is empty, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates two regions, one from a path and the other from a rectangle. The code then updates the path region with the rectangular region and tests the updated region to determine if it is empty.

VOID Example_IsEmpty(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(5, 15, 70, 45);
   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);
   graphics.FillRegion(&solidBrush, &pathRegion);

   // Create a region from a rectangle.
   Region rectRegion(rect);
   graphics.FillRegion(&solidBrush, &rectRegion);

   // Update the path region to the portion that intersects the
   // rectangular region.
   pathRegion.Intersect(&rectRegion);

   if(pathRegion.IsEmpty(&graphics))
   {
      // The intersection is empty.
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, Rect, Status, IsInfinite, MakeEmpty, MakeInfinite


Region::IsInfinite(g)

The IsInfinite method determines whether this region is infinite.

BOOL IsInfinite(
  const Graphics* g
) const;

Parameters

g
[in] Pointer to a Graphics object that contains the world and page transformations required to calculate the device coordinates of this region.

Return Values

If this region is infinite, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example uses the default constructor to create an infinite region. Then the code tests the region to determine if it is infinite and performs a task based on the result.

VOID Example_IsInfinite(HDC hdc)
{
   Graphics graphics(hdc);

   graphics.SetPageUnit(UnitInch);

   Rect rect(0, 0, 100, 50);
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   // The default constructor creates an infinite region.
   Region region;

   if(region.IsInfinite(&graphics))
   {
      // The region is infinite. Perform some task.
   }
   else
   {
      // Perform a different task.
   }

   graphics.FillRegion(&solidBrush, &region);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, Rect, Status, IsEmpty, MakeEmpty, MakeInfinite


Region::IsVisible Methods

This topic lists the IsVisible methods of the Region class. For a complete list of methods for the Region class, see Region Methods.

  • IsVisible(Point& point, Graphics* g)
  • IsVisible(PointF& point, Graphics* g)
  • IsVisible(Rect& rect, Graphics* g)
  • IsVisible(RectF& rect, Graphics* g)
  • IsVisible(INT x, INT y, Graphics* g)
  • IsVisible(REAL x, REAL y, Graphics* g)
  • IsVisible(INT x, INT y, INT width, INT height, Graphics* g)
  • IsVisible(REAL x, REAL y, REAL width, REAL height, Graphics* g)


Region::IsVisible(Point& point, Graphics* g)

The IsVisible method determines whether a point is inside this region.

BOOL IsVisible(
  const Point& point,
  const Graphics* g
) const;

Parameters

point
[in] Reference to a point to test.
g
[in] Optional. Pointer to a Graphics object that contains the world and page transformations required to calculate the device coordinates of this region and the point. The default value is NULL.

Return Values

If the point is inside this region, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a region from a path and then tests to determine whether a point is in the region.

VOID Example_IsVisiblePoint(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);
   graphics.FillRegion(&solidBrush, &pathRegion);

   // Check to see whether a point is in the region.
   Point testPoint(125, 30);

   if(pathRegion.IsVisible(testPoint, &graphics))
   {
      // The test point is in the region.
   }

   // Fill a small circle centered at the test point.
   SolidBrush brush(Color(255, 0, 0, 0));
   graphics.FillEllipse(&brush, testPoint.X - 4, testPoint.Y - 4, 8, 8);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, Point, Status


Region::IsVisible(PointF& point, Graphics* g)

The IsVisible method determines whether a point is inside this region.

BOOL IsVisible(
  const PointF& point,
  const Graphics* g
) const;

Parameters

point
[in] Reference to a point to test.
g
[in] Optional. Pointer to a Graphics object that contains the world and page transformations required to calculate the device coordinates of this region and the point. The default value is NULL.

Return Values

If the point is inside this region, this method returns TRUE; otherwise, it returns FALSE.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, Point, Status


Region::IsVisible(Rect& rect, Graphics* g)

The IsVisible method determines whether a rectangle intersects this region.

BOOL IsVisible(
  const Rect& rect,
  const Graphics* g
) const;

Parameters

rect
[in] Reference to a rectangle to test.
g
[in] Optional. Pointer to a Graphics object that contains the world and page transformations required to calculate the device coordinates of this region and the rectangle. The default value is NULL.

Return Values

If the rectangle intersects this region, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a region from a path and then tests to determine whether a rectangle intersects the region.

VOID Example_IsVisibleRect(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);
   graphics.FillRegion(&solidBrush, &pathRegion);

   // Check to see whether a rectangle intersects the region.
   Rect testRect(65, 25, 70, 30);

   if(pathRegion.IsVisible(testRect, &graphics))
   {
      // All or part of the rectangle is in the region.
   }

   // Draw the test rectangle.
   Pen pen(Color(255, 0, 0, 0));
   graphics.DrawRectangle(&pen, testRect);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, Point


Region::IsVisible(RectF& rect, Graphics* g)

The IsVisible method determines whether a rectangle intersects this region.

BOOL IsVisible(
  const RectF& rect,
  const Graphics* g
) const;

Parameters

rect
[in] Reference to a rectangle to test.
g
[in] Optional. Pointer to a Graphics object that contains the world and page transformations required to calculate the device coordinates of this region and the rectangle. The default value is NULL.

Return Values

If the rectangle intersects this region, this method returns TRUE; otherwise, it returns FALSE.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, Rect


Region::IsVisible(INT x, INT y, Graphics* g)

The IsVisible method determines whether a point is inside this region.

BOOL IsVisible(
  INT x,
  INT y,
  const Graphics* g
) const;

Parameters

x
[in] Integer that specifies the x-coordinate of the point to test.
y
[in] Integer that specifies the y-coordinate of the point to test.
g
[in] Optional. Pointer to a Graphics object that contains the world and page transformations required to calculate the device coordinates of this region and the point. The default value is NULL.

Return Values

If the point is inside this region, this method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a region from a path and then tests to determine whether a point is inside the region.

VOID Example_IsVisibleXY(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);
   graphics.FillRegion(&solidBrush, &pathRegion);

   // Check to see whether the point (125, 40) is in the region.
   INT x = 125;
   INT y = 40;
   if(pathRegion.IsVisible(x, y, &graphics))
   {

      // The point is in the region.
   }

   // Fill a small circle centered at the point (125, 40).
   SolidBrush brush(Color(255, 0, 0, 0));
   graphics.FillEllipse(&brush, x - 4, y - 4, 8, 8);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, Rect


Region::IsVisible(REAL x, REAL y, Graphics* g)

The IsVisible method determines whether a point is inside this region.

BOOL IsVisible(
  REAL x,
  REAL y,
  const Graphics* g
) const;

Parameters

x
[in] Real number that specifies the x-coordinate of the point to test.
y
[in] Real number that specifies the y-coordinate of the point to test.
g
[in] Optional. Pointer to a Graphics object that contains the world and page transformations required to calculate the device coordinates of this region and the point. The default value is NULL.

Return Values

If the point is inside this region, this method returns TRUE; otherwise, it returns FALSE.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, Rect


Region::IsVisible(INT x, INT y, INT width, INT height, Graphics* g)

The IsVisible method determines whether a rectangle intersects this region.

BOOL IsVisible(
  INT x,
  INT y,
  INT width,
  INT height,
  const Graphics* g
) const;

Parameters

x
[in] Integer that specifies the x-coordinate of the upper-left corner of the rectangle to test.
y
[in] Integer that specifies the y-coordinate of the upper-left corner of the rectangle to test.
width
[in] Integer that specifies the width of the rectangle to test.
height
[in] Integer that specifies the height of the rectangle to test.
g
[in] Optional. Pointer to a Graphics object that contains the world and page transformations required to calculate the device coordinates of this region and the rectangle. The default value is NULL.

Return Values

If the rectangle intersects this region, the method returns TRUE; otherwise, it returns FALSE.

Example Code [C++]

The following example creates a region from a path and then tests to determine whether a rectangle intersects the region.

VOID Example_IsVisibleXYWH(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);
   graphics.FillRegion(&solidBrush, &pathRegion);

   // Check to see whether the rectangle intersects the region.
   // The rectangle has upper-left corner (65, 25), width 70, and height 30.
   if(pathRegion.IsVisible(65, 25, 70, 30, &graphics))
   {
      // All or part of the rectangle is in the region.
   }

   // Draw the rectangle.
   Pen pen(Color(255, 0, 0, 0));
   graphics.DrawRectangle(&pen, 65, 25, 70, 30);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, Rect


Region::IsVisible(REAL x, REAL y, REAL width, REAL height, Graphics* g)

The IsVisible method determines whether a rectangle intersects this region.

BOOL IsVisible(
  REAL x,
  REAL y,
  REAL width,
  REAL height,
  const Graphics* g
) const;

Parameters

x
[in] Real number that specifies the x-coordinate of the upper-left corner of the rectangle to test.
y
[in] Real number that specifies the y-coordinate of the upper-left corner of the rectangle to test.
width
[in] Real number that specifies the width of the rectangle to test.
height
[in] Real number that specifies the height of the rectangle to test.
g
[in] Optional. Pointer to a Graphics object that contains the world and page transformations required to calculate the device coordinates of this region and the rectangle. The default value is NULL.

Return Values

If the rectangle intersects this region, this method returns TRUE; otherwise, it returns FALSE.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Graphics, Rect


Region::MakeEmpty()

The MakeEmpty method updates this region to an empty region. In other words, the region occupies no space..

Status MakeEmpty(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a rectangle and paints it with a brush. Then the code makes the region empty and paints the region with a different color to show that the region occupies no space on the display device.

VOID Example_MakeEmpty(HDC hdc)
{
   Graphics graphics(hdc);

   Rect rect(65, 15, 70, 45);
   SolidBrush redBrush(Color(255, 255, 0, 0));
   SolidBrush blueBrush(Color(255, 0, 0, 255));

   // Create a region, and fill it with a red brush.
   Region rectRegion(rect);
   graphics.FillRegion(&redBrush, &rectRegion);

   // Make the region empty, and then fill it with a blue brush.
   rectRegion.MakeEmpty();
   graphics.FillRegion(&blueBrush, &rectRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
IsEmpty, IsInfinite, Status


Region::MakeInfinite()

The MakeInfinite method updates this region to an infinite region.

Status MakeInfinite(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a rectangle, makes the region infinite, and fills the region to show the infinite region.

VOID Example_MakeInfinite(HDC hdc)
{
   Graphics graphics(hdc);

   Rect rect(65, 15, 70, 45);
   SolidBrush blueBrush(Color(255, 0, 0, 255));

   // Create a rectangular region.
   Region rectRegion(rect);

   // Make the region infinite, and then fill it with a blue brush.
   rectRegion.MakeInfinite();
   graphics.FillRegion(&blueBrush, &rectRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
IsEmpty, IsInfinite, Status


Region::Transform(matrix)

The Transform method transforms this region by multiplying each of its data points by a specified matrix.

Status Transform(
  const Matrix* matrix
);

Parameters

matrix
[in] Pointer to a matrix that specifies the transformation.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a path and fills it. The code then transforms the region and fills the transformed region to show the transformation.

VOID Example_Transform(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);
   graphics.FillRegion(&solidBrush, &pathRegion);

   // Transform the region.
   Matrix matrix(1, 0, 0, 3, 100, 0);  // vertical stretch, shift right
   pathRegion.Transform(&matrix);
   graphics.FillRegion(&solidBrush, &pathRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Matrix, Rect, Status, Translate


Region::Translate Methods

This topic lists the Translate methods of the Region class. For a complete list of methods for the Region class, see Region Methods.

  • Translate(INT dx, INT dy)
  • Translate(REAL dx, REAL dy)


Region::Translate(INT dx, INT dy)

The Translate method offsets this region by specified amounts in the horizontal and vertical directions.

Status Translate(
  INT dx,
  INT dy
);

Parameters

dx
[in] Integer that specifies the amount to shift the region in the x direction.
dy
[in] Integer that specifies the amount to shift the region in the y direction.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a path and fills it. The code then translates the region and fills the translated region to show how the region has shifted.

VOID Example_Translate(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);
   graphics.FillRegion(&solidBrush, &pathRegion);

   // Translate the region.
   INT dx = 100;
   INT dy = 60;
   pathRegion.Translate(dx, dy);
   graphics.FillRegion(&solidBrush, &pathRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect, Status, Transform


Region::Translate(REAL dx, REAL dy)

The Translate method offsets this region by specified amounts in the horizontal and vertical directions.

Status Translate(
  REAL dx,
  REAL dy
);

Parameters

dx
[in] Real number that specifies the amount to shift the region in the x direction.
dy
[in] Real number that specifies the amount to shift the region in the y direction.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect, Status, Transform


Region::Union Methods

This topic lists the Union methods of the Region class. For a complete list of methods for the Region class, see Region Methods.

  • Union(path)
  • Union(Rect& rect)
  • Union(RectF& rect)
  • Union(region)


Region::Union(path)

The Union method updates this region to all portions (intersecting and nonintersecting) of itself and all portions of the specified path's interior.

Status Union(
  const GraphicsPath* path
);

Parameters

path
[in] Pointer to a GraphicsPath object that specifies the path to use to update this Region object.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a rectangle and then uses a path to update the region. The updated region is the union of the rectangular region and the path.

VOID Example_UnionPath(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);
   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a rectangle.
   Region rectRegion(rect);

   // Form the union of the region and the interior of a path.
   rectRegion.Union(&path);

   graphics.FillRegion(&solidBrush, &rectRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, Rect, Status


Region::Union(Rect& rect)

The Union method updates this region to all portions (intersecting and nonintersecting) of itself and all portions of the specified rectangle's interior.

Status Union(
  const Rect& rect
);

Parameters

rect
[in] Reference to a rectangle to use to update this region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a path and then uses a rectangle to update the region. The updated region is the union of the path region and a rectangle.

VOID Example_UnionRect(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);
   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);

   // Form the union of the region and a rectangle.
   pathRegion.Union(rect);

   graphics.FillRegion(&solidBrush, &pathRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Region::Union(RectF& rect)

The Union method updates this region to all portions (intersecting and nonintersecting) of itself and all portions of the specified rectangle's interior.

Status Union(
  const RectF& rect
);

Parameters

rect
[in] Reference to a rectangle to use to update this region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Region::Union(region)

The Union method updates this region to all portions (intersecting and nonintersecting) of itself and all portions of another region.

Status Union(
  const Region* region
);

Parameters

region
[in] Pointer to a Region object to use to update this region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates two regions, one from a path and the other from a rectangle. The code then uses the rectangular region to update the path region. The updated region is the union of the two regions.

VOID Example_UnionReg(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);
   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);

   // Create a region from a rectangle.
   Region rectRegion(rect);

   // Form the union of the two regions.
   pathRegion.Union(&rectRegion);

   graphics.FillRegion(&solidBrush, &pathRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Region::Xor Methods

This topic lists the Xor methods of the Region class. For a complete list of methods for the Region class, see Region Methods.

  • Xor(path)
  • Xor(Rect& rect)
  • Xor(RectF& rect)
  • Xor(region)


Region::Xor(path)

The Xor method updates this region to the nonintersecting portions of itself and the specified path's interior.

Status Xor(
  const GraphicsPath* path
);

Parameters

path
[in] Pointer to a GraphicsPath that specifies the path to use to update this region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a rectangle and then uses a path to update the region.

VOID Example_XorPath(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);
   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a rectangle.
   Region rectRegion(rect);

   // Perform an exclusive OR operation on the region and a path.
   rectRegion.Xor(&path);

   graphics.FillRegion(&solidBrush, &rectRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, Rect, Status


Region::Xor(Rect& rect)

The Xor method updates this region to the nonintersecting portions of itself and the specified rectangle's interior.

Status Xor(
  const Rect& rect
);

Parameters

rect
[in] Reference to a rectangle to use to update this region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a region from a path and then uses a rectangle to update the region.

VOID Example_XorRect(HDC hdc)
{
   Graphics graphics(hdc);

  Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);
   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);

   // Perform an exclusive OR operation on the region and a rectangle.
   pathRegion.Xor(rect);

   graphics.FillRegion(&solidBrush, &pathRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Region::Xor(RectF& rect)

The Xor method updates this region to the nonintersecting portions of itself and the specified rectangle's interior.

Status Xor(
  const RectF& rect
);

Parameters

rect
[in] Reference to a rectangle to use to update this region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Region::Xor(region)

The Xor method updates this region to the nonintersecting portions of itself and another region.

Status Xor(
  const Region* region
);

Parameters

region
[in] Pointer to a region to use to update this region.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates two regions, one from a path and the other from a rectangle. The code then uses the rectangular region to update the path region.

VOID Example_XorReg(HDC hdc)
{
   Graphics graphics(hdc);

   Point points[] = {
      Point(110, 20),
      Point(120, 30),
      Point(100, 60),
      Point(120, 70),
      Point(150, 60),
      Point(140, 10)};

   Rect rect(65, 15, 70, 45);
   GraphicsPath path;
   SolidBrush solidBrush(Color(255, 255, 0, 0));

   path.AddClosedCurve(points, 6);

   // Create a region from a path.
   Region pathRegion(&path);

   // Create a region from a rectangle.
   Region rectRegion(rect);

   // Perform an exclusive OR operation on the two regions.
   pathRegion.Xor(&rectRegion);

   graphics.FillRegion(&solidBrush, &pathRegion);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusheaders.h; include Gdiplus.h.

See Also

Reference
Rect, Status


Size Class

The Size class encapsulates a Width and Height dimension in a 2-D coordinate system.

Data Members

Data member | Description
Height | INT. Vertical measurement of the Size object.
Width | INT. Horizontal measurement of the Size object.

Constructors

Constructor | Description
Size | Overloaded. Creates and initializes a new Size object.

Methods

Method | Description
Empty | Determines whether a Size object has a width and height of zero.
Equals | Determines whether two Size objects are equal (same width and height).
operator+ | Adds one Size object to another.
operator- | Subtracts one Size object from another.


Size Constructors

This topic lists the constructors of the Size class. For a complete class listing, see Size Class.

  • Size()
  • Size(size)
  • Size(width, height)


Size::Size()

Creates a new Size object and initializes the members to zero. This is the default constructor.

Size(void);

Parameters

This method has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Size Constructors


Size::Size(size)

Creates a Size object and initializes its members by copying the members of another Size object.

Size(
  const Size& size
);

Parameters

size
[in] Reference to a Size object that is used to initialize this Size object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Size Constructors


Size::Size(width, height)

Creates a Size object and initializes its Width and Height data members.

Size(
  INT width,
  INT height
);

Parameters

width
[in] Integer that specifies the initial value of the Width data member.
height
[in] Integer that specifies the initial value of the Height data member.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Size Constructors


Size Methods

This topic lists the methods of the Size class. For a complete class listing, see Size Class.

  • Empty()
  • Equals(sz)
  • operator+(sz)
  • operator-(sz)


Size::Empty()

The Empty method determines whether a Size object is empty.

BOOL Empty(void);

Parameters

This method has no parameters.

Return Values

If the Width and Height data members are both equal to zero, this method returns TRUE; otherwise, it returns FALSE.

Remarks

A Size object is defined as empty if the Width and Height data members are both equal to zero.

Example Code [C++]

Rect rect(50, 50, 100, 200);
Size size;

rect.Inflate(-50, -100);
rect.GetSize(&size);

if(size.Empty())
{
   // The width and height are both 0.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Rect, SizeF


Size::Equals(sz)

The Equals method determines whether two Size objects are equal.

BOOL Equals(
  const Size& sz
);

Parameters

sz
[in] Reference to a Size object that is compared to this Size object.

Return Values

If the Width and Height data members of the two Size objects are equal, this method returns TRUE; otherwise, it returns FALSE.

Remarks

Two Size objects are defined as equal if the Width and Height data members are equal.

Example Code [C++]

The following example creates a Rect object, gets the size of the rectangle, and determines whether the rectangles are equal.

Rect rect(50, 30, 200, 100);
Size desiredSize(200, 100);
Size rectSize;

// Get the size of the rectangle.
rect.GetSize(&rectSize);

if(rectSize.Equals(desiredSize))
{
   // The rectangle has the desired size.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
Rect, SizeF


Size::operator+(sz)

The operator+ method adds the Width and Height data members of two Size objects.

Size operator+(
  const Size& sz
);

Parameters

sz
[in] Reference to a Size object whose Width and Height data members are added to the Width and Height data members of this Size object.

Return Values

This method returns the sum of this Size object and another Size object.

Remarks

This method overloads the addition operator for Size objects. If A, B, and C are Size objects, the statement C = A + B is equivalent to C = A.operator+(B).

Example Code [C++]

VOID Example_OperatorPlus(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0));

   Size size1(80, 30);
   Size size2(50, 20);

   Size size3 = size1 + size2;

   graphics.DrawRectangle(&pen, 50, 50, size1.Width, size1.Height);
   graphics.DrawRectangle(&pen, 50, 50, size2.Width, size2.Height);
   graphics.DrawRectangle(&pen, 50, 50, size3.Width, size3.Height);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
operator-, SizeF


Size::operator-(sz)

The operator- method subtracts the Width and Height data members of two Size objects.

Size operator-(
  const Size& sz
);

Parameters

sz
[in] Reference to a Size object whose Width and Height data members are subtracted from the Width and Height data members of this Size object.

Return Values

This method returns the difference of this Size object and another Size object.

Remarks

This method overloads the subtraction operator for Size objects. If A, B, and C are Size objects, the statement C = A - B is equivalent to C = A.operator-(B).

Example Code [C++]

VOID Example_OperatorMinus(HWND hWnd)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0));

   Size size1(200, 100);
   Size size2(50, 40);

   Size size3 = size1 - size2;

   graphics.DrawRectangle(&pen, 50, 50, size1.Width, size1.Height);
   graphics.DrawRectangle(&pen, 50, 50, size2.Width, size2.Height);
   graphics.DrawRectangle(&pen, 50, 50, size3.Width, size3.Height);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
operator+, SizeF


SizeF Class

The SizeF class encapsulates a Width and Height dimension in a 2-D coordinate system. The SizeF class uses floating point coordinates.

Data Members

Data member | Description
Height | REAL. Vertical measurement of the SizeF object.
Width | REAL. Horizontal measurement of the SizeF object.

Constructors

Constructor | Description
SizeF | Overloaded. Creates and initializes a new SizeF object.

Methods

Method | Description
Empty | Determines whether a SizeF object has a width and height of zero.
Equals | Determines whether two SizeF objects are equal (same width and height).
operator+ | Adds one SizeF object to another.
operator- | Subtracts one SizeF object from another.


SizeF Constructors

This topic lists the constructors of the SizeF class. For a complete class listing, see SizeF Class.

  • SizeF()
  • SizeF(size)
  • SizeF(width, height)


SizeF::SizeF()

Creates a SizeF object and initializes the members to zero. This is the default constructor.

SizeF(void);

Parameters

This method has no parameters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
SizeF Constructors


SizeF::SizeF(size)

Creates a SizeF object and initializes its members by copying the members of another SizeF object.

SizeF(
  const SizeF& size
);

Parameters

size
[in] Reference to a SizeF object that is used to initialize this SizeF object.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
SizeF Constructors


SizeF::SizeF(width, height)

Creates a SizeF object and initializes its Width and Height data members.

SizeF(
  REAL width,
  REAL height
);

Parameters

width
[in] Real number that specifies the initial value of the Width data member.
height
[in] Real number that specifies the initial value of the Height data member.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
SizeF Constructors


SizeF Methods

This topic lists the methods of the SizeF class. For a complete class listing, see SizeF Class.

  • Empty()
  • Equals(sz)
  • operator+(sz)
  • operator-(sz)


SizeF::Empty()

The Empty method determines whether a SizeF object is empty.

BOOL Empty(void);

Parameters

This method has no parameters.

Return Values

If the Width and Height data members are both equal to zero, this method returns TRUE; otherwise, it returns FALSE.

Remarks

A SizeF object is defined as empty if the Width and Height data members are both equal to zero.

Example Code [C++]

RectF rect(50.0f, 50.0f, 100.0f, 200.0f);
SizeF size;

rect.Inflate(-50.0f, -100.0f);
rect.GetSize(&size);

if(size.Empty())
{

   // The width and height are both 0.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
RectF, Size


SizeF::Equals(sz)

The Equals method determines whether two SizeF objects are equal.

BOOL Equals(
  const SizeF& sz
);

Parameters

sz
[in] Reference to a SizeF object that is compared to this SizeF object.

Return Values

If the Width and Height data members of the two SizeF objects are equal, this method returns TRUE; otherwise, it returns FALSE.

Remarks

Two SizeF objects are defined as equal if the Width and Height data members are equal.

Example Code [C++]

RectF rect(50.0f, 30.0f, 200.0f, 100.0f);
SizeF desiredSizeF(200.0f, 100.0f);
SizeF rectSizeF;

// Get the size of the rectangle.
rect.GetSize(&rectSizeF);

if(rectSizeF.Equals(desiredSizeF))
{
   // The rectangle has the wanted size.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
RectF, Size Constructors


SizeF::operator+(sz)

The operator+ method adds the Width and Height data members of two SizeF objects.

SizeF operator+(
  const SizeF& sz
);

Parameters

sz
[in] Reference to a SizeF object whose Width and Height data members are added to the Width and Height data members of this SizeF object.

Return Values

This method returns the sum of this SizeF object and another SizeF object.

Remarks

This method overloads the addition operator for SizeF objects. If A, B, and C are SizeF objects, the statement C = A + B is equivalent to C = A.operator+(B).

Example Code [C++]

VOID Example_OperatorPlus(HDC hdc)
{

   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0));

   SizeF size1(80.0f, 30.0f);
   SizeF size2(50.0f, 20.0f);

   SizeF size3 = size1 + size2;

   graphics.DrawRectangle(&pen, 50.0f, 50.0f, size1.Width, size1.Height);
   graphics.DrawRectangle(&pen, 50.0f, 50.0f, size2.Width, size2.Height);
   graphics.DrawRectangle(&pen, 50.0f, 50.0f, size3.Width, size3.Height);

}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
operator-, Size


SizeF::operator-(sz)

The operator- method subtracts the Width and Height data members of two SizeF objects.

SizeF operator-(
  const SizeF& sz
);

Parameters

sz
[in] Reference to a SizeF object whose Width and Height data members are subtracted from the Width and Height data members of this SizeF object.

Return Values

This method returns the difference of this SizeF object and another SizeF object.

Remarks

This method overloads the subtraction operator for SizeF objects. If A, B, and C are Size objects, the statement C = A - B is equivalent to C = A.operator-(B).

Example Code [C++]

VOID Example_OperatorMinus(HDC hdc)
{
   Graphics graphics(hdc);
   Pen pen(Color(255, 0, 0, 0));

   SizeF size1(200.0f, 100.0f);
   SizeF size2(50.0f, 40.0f);

   SizeF size3 = size1 - size2;

   graphics.DrawRectangle(&pen, 50.0f, 50.0f, size1.Width, size1.Height);
   graphics.DrawRectangle(&pen, 50.0f, 50.0f, size2.Width, size2.Height);
   graphics.DrawRectangle(&pen, 50.0f, 50.0f, size3.Width, size3.Height);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.

See Also

Reference
operator+, Size


SolidBrush Class

The SolidBrush class defines a solid color Brush object. A Brush object is used to fill in shapes similar to the way a paint brush can paint the inside of a shape. This class inherits from the Brush abstract base class.

Inheritance

GdiplusBase
Brush
SolidBrush

Constructors

Constructor | Description
SolidBrush | Creates and initializes a new SolidBrush object based on a specified color.

Methods

Uninherited

Method | Description
GetColor | Gets the color of this solid brush.
SetColor | Sets the color of this solid brush.

Inherited from Brush

Method | Description
Clone | Creates a new Brush object based on this brush.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetType | Gets the type of this brush.


SolidBrush::SolidBrush(color)

Creates a SolidBrush object based on a color.

SolidBrush(
  const Color& color
);

Parameters

color
[in] Reference to a Color object that specifies the initial color of this solid brush.

Return Values

This method does not return a value.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


SolidBrush Methods

This topic lists the methods of the SolidBrush class. For a complete class listing, see SolidBrush Class.

  • Clone()
  • GetColor(color)
  • GetLastStatus()
  • GetType()
  • SetColor(color)


SolidBrush::GetColor(color)

The GetColor method gets the color of this solid brush.

Status GetColor(
  Color* color
) const;

Parameters

color
[out] Pointer to a Color object that receives the color of this solid brush.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a solid brush and uses it to fill a rectangle. The code gets the color of the solid brush and stores it. Then, the code creates a second solid brush using the stored color and paints a second rectangle with the second solid brush.

VOID Example_GetColor(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a solid brush, and use it to fill a rectangle.
   SolidBrush solidBrush(Color(255, 0, 0, 255));  // blue
   graphics.FillRectangle(&solidBrush, 10, 10, 200, 100);

   // Get the color of the solid brush.
   Color color;
   solidBrush.GetColor(&color);

   // Create a second solid brush with that same color.
   SolidBrush solidBrush2(color);

   // Paint a second rectangle with the second solid brush.
   graphics.FillRectangle(&solidBrush2, 220, 10, 200, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, SetColor
Tasks and Examples
Filling a Shape with a Solid Color
Concepts
Brushes and Filled Shapes


SolidBrush::SetColor(color)

The SetColor method sets the color of this solid brush.

Status SetColor(
  const Color& color
);

Parameters

color
[in] Reference to a Color object that specifies the color to be set in this solid brush.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a solid brush and uses it to fill a rectangle. The code uses SetColor to change the color of the solid brush and then paints a second rectangle the new color.

VOID Example_SetColor(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a solid brush, and use it to fill a rectangle.
   SolidBrush solidBrush(Color(255, 0, 0, 255));  // blue
   graphics.FillRectangle(&solidBrush, 10, 10, 200, 100);

   // Change the color of the brush, and fill another rectangle.
   solidBrush.SetColor(Color(255, 255, 0, 0));    // red
   graphics.FillRectangle(&solidBrush, 220, 10, 200, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Color, GetColor
Tasks and Examples
Filling a Shape with a Solid Color
Concepts
Brushes and Filled Shapes


StringFormat Class

The StringFormat class encapsulates text layout information (such as alignment, orientation, tab stops, and clipping) and display manipulations (such as trimming, font substitution for characters that are not supported by the requested font, and digit substitution for languages that do not use Western European digits). A StringFormat object can be passed to the Graphics::DrawString method to format a string.

Inheritance

GdiplusBase
StringFormat

Constructors

Constructor | Description
StringFormat | Overloaded. Creates and initializes a new StringFormat object.

Methods

Method | Description
Clone | Creates a copy of this StringFormat object.
GenericDefault | Creates a generic, default StringFormat object.
GenericTypographic | Creates a generic typographic StringFormat object.
GetAlignment | Gets an element of the StringAlignment enumeration that indicates the character alignment of the string in relation to the origin of the layout rectangle.
GetDigitSubstitutionLanguage | Gets the language that corresponds with the digits that are to be substituted for Western European digits.
GetDigitSubstitutionMethod | Gets an element of the StringDigitSubstitute enumeration that indicates the digit substitution method that is used by this StringFormat object.
GetFormatFlags | Gets the string format flags.
GetHotkeyPrefix | Gets an element of the HotkeyPrefix enumeration that indicates the type of processing that is performed on a string when a hot key prefix is encountered.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetLineAlignment | Gets an element of the StringAlignment enumeration that indicates the line alignment in relation to the origin of the layout rectangle.
GetMeasurableCharacterRangeCount | Gets the number of measurable character ranges that are currently set.
GetTabStopCount | Gets the number of tab-stop offsets in the StringFormat object.
GetTabStops | Gets the offsets of the tab stops.
GetTrimming | Gets an element of the StringTrimming enumeration that indicates the trimming style.
SetAlignment | Sets the character alignment of the string in relation to the origin of the layout rectangle.
SetDigitSubstitution | Sets the digit substitution method and the language that corresponds to the digit substitutes.
SetFormatFlags | Sets the string format flags.
SetHotkeyPrefix | Sets the type of processing that is performed on a string when a hot key prefix is encountered.
SetLineAlignment | Sets the line alignment in relation to the origin of the layout rectangle.
SetMeasurableCharacterRanges | Sets a series of character ranges that can be measured in a string.
SetTabStops | Sets the offsets for tab stops.
SetTrimming | Sets the trimming style that specifies how to trim a string so that it fits into the layout rectangle.
~StringFormat | StringFormat object destructor.


StringFormat Constructors

This topic lists the constructors of the StringFormat class. For a complete class listing, see StringFormat Class.

  • StringFormat(format)
  • StringFormat(formatFlags, language)


StringFormat::StringFormat(format)

Creates a StringFormat object from another StringFormat object.

StringFormat(
  const StringFormat* format
);

Parameters

format
[in] Pointer to a StringFormat object to copy.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
StringFormatFlags


StringFormat::StringFormat(formatFlags, language)

Creates a StringFormat object based on string format flags and a language.

StringFormat(
  INT formatFlags,
  LANGID language
);

Parameters

formatFlags
[in] Optional. Value that specifies the format flags that control most of the characteristics of the StringFormat object. The flags are set by applying a bitwise OR to elements of the StringFormatFlags enumeration. The default value is 0 (no flags set).
language
[in] Optional. Sixteen-bit value that specifies the language to use. The default value is LANG_NEUTRAL, which is the user's default language.

Remarks

When specifying LANG_NEUTRAL as the language ID, it is common practice to pass just LANG_NEUTRAL as in the following example:

stat = FontFamily.GetFamilyName(name, LANG_NEUTRAL);

If you are specifying a language other than LANG_NEUTRAL, use MAKELANGID to create the language and sublanguage combination as in the following example:

LANGID language = MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL);

For a list of the available languages and sublanguages, see Winnt.h.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
StringFormatFlags


StringFormat Methods

This topic lists the methods of the StringFormat class. For a complete class listing, see StringFormat Class.

  • Clone()
  • GenericDefault()
  • GenericTypographic()
  • GetAlignment()
  • GetDigitSubstitutionLanguage()
  • GetDigitSubstitutionMethod()
  • GetFormatFlags()
  • GetHotkeyPrefix()
  • GetLastStatus()
  • GetLineAlignment()
  • GetMeasurableCharacterRangeCount()
  • GetTabStopCount()
  • GetTabStops(count, firstTabOffset, tabStops)
  • GetTrimming()
  • SetAlignment(align)
  • SetDigitSubstitution(language, substitute)
  • SetFormatFlags(flags)
  • SetHotkeyPrefix(hotkeyPrefix)
  • SetLineAlignment(align)
  • SetMeasurableCharacterRanges(rangeCount, ranges)
  • SetTabStops(firstTabOffset, count, tabStops)
  • SetTrimming(trimming)


StringFormat::Clone()

The Clone method creates a new StringFormat object and initializes it with the contents of this StringFormat object.

StringFormat* Clone(void);

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new StringFormat object.

Example Code [C++]

The following example creates a StringFormat object, clones it, and then uses the clone to draw a formatted string.

VOID Example_Clone(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush  solidBrush(Color(255, 255, 0, 0));
   FontFamily  fontFamily(L"Times New Roman");
   Font        font(&fontFamily, 24, FontStyleRegular, UnitPixel);

   // Create a StringFormat object.
   StringFormat stringFormat;
   stringFormat.SetAlignment(StringAlignmentCenter);

   // Clone the StringFormat object.
   StringFormat* pStringFormat = stringFormat.Clone();

   // Use the cloned StringFormat object in a call to DrawString.
   graphics.DrawString(
      L"This text was formatted by a cloned StringFormat object.",
      56,  // string length
      &font,
      RectF(30, 30, 200, 200),
      pStringFormat,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 30, 30, 200, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
StringFormatFlags


StringFormat::GenericDefault()

The GenericDefault method creates a generic, default StringFormat object.

static const StringFormat* GenericDefault(void);

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new StringFormat object.

Remarks

A generic, default StringFormat object has the following characteristics:

  • No string format flags are set.
  • Character alignment and line alignment are set to StringAlignmentNear.
  • Language ID is set to neutral language, which means that the current language associated with the calling thread is used.
  • String digit substitution is set to StringDigitSubstituteUser.
  • Hot key prefix is set to HotkeyPrefixNone.
  • Number of tab stops is set to zero.
  • String trimming is set to StringTrimmingCharacter.

Example Code [C++]

The following example creates a generic, default StringFormat object and then uses it to draw a formatted string. The code also draws the string's layout rectangle.

VOID Example_GenericDefault(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush  solidBrush(Color(255, 255, 0, 0));
   FontFamily  fontFamily(L"Times New Roman");
   Font        font(&fontFamily, 12, FontStyleRegular, UnitPoint);

   // Create a generic StringFormat object.
   const StringFormat* pStringFormat = StringFormat::GenericDefault();

   // Use the generic StringFormat object in a call to DrawString.
  graphics.DrawString(
      L"This text was formatted by a generic StringFormat object.",
      57,  // string length
      &font,
      RectF(30, 30, 100, 120),
      pStringFormat,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 30, 30, 100, 120);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
Font, HotKeyPrefix, LOGFONT, RectF, StringAlignment, StringDigitSubstitute, StringFormatFlags, StringTrimming


StringFormat::GenericTypographic()

The GenericTypographic method creates a generic, typographic StringFormat object.

static const StringFormat* GenericTypographic(void);

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the new StringFormat object.

Remarks

A generic, typographic StringFormat object has the following characteristics:

  • String format flags StringFormatFlagsLineLimit, StringFormatFlagsNoClip, and StringFormatFlagsNoFitBlackBox are set.
  • Character alignment and line alignment are set to StringAlignmentNear.
  • Language ID is set to neutral language, which means that the current language associated with the calling thread is used.
  • String digit substitution is set to StringDigitSubstituteUser.
  • Hot key prefix is set to HotkeyPrefixNone.
  • Number of tab stops is set to zero.
  • String trimming is set to StringTrimmingNone.

Example Code [C++]

The following example creates a generic, typographic StringFormat object and then uses it to draw a formatted string. The code also draws the string's layout rectangle.

VOID Example_GenericTypographic(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush  solidBrush(Color(255, 255, 0, 0));
   FontFamily  fontFamily(L"Times New Roman");
   Font        font(&fontFamily, 12, FontStyleRegular, UnitPoint);

   // Create a generic typographic StringFormat object.
   const StringFormat* pStringFormat = StringFormat::GenericTypographic();

   // Use the generic typographic StringFormat object
   // in a call to DrawString.
  graphics.DrawString(
      L"Formatted by a generic typographic StringFormat object",
      54,  // string length
      &font,
      RectF(30, 30, 100, 120),
      pStringFormat,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 30, 30, 100, 120);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
Font, HotKeyPrefix, LOGFONT, RectF, StringAlignment, StringDigitSubstitute, StringFormatFlags, StringTrimming


StringFormat::GetAlignment()

The GetAlignment method gets an element of the StringAlignment enumeration that indicates the character alignment of this StringFormat object in relation to the origin of the layout rectangle. A layout rectangle is used to position the displayed string.

StringAlignment GetAlignment(void) const;

Parameters

This method has no parameters.

Return Values

This method returns an element of the StringAlignment enumeration.

Example Code [C++]

The following example creates a StringFormat object, sets the string's character alignment, gets the alignment value, and stores it in a variable. The code then creates a second StringFormat object and uses the stored alignment value to set the character alignment of the second StringFormat object. Next, the code uses the second StringFormat object to draw a formatted string. The code also draws the string's layout rectangle.

VOID Example_GetAlignment(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush  solidBrush(Color(255, 255, 0, 0));
   FontFamily  fontFamily(L"Times New Roman");
   Font        font(&fontFamily, 24, FontStyleRegular, UnitPixel);

   // Create a StringFormat object, and set its alignment.
   StringFormat stringFormat;
   stringFormat.SetAlignment(StringAlignmentFar);

   // Get the alignment setting from the StringFormat object.
   StringAlignment stringAlignment = stringFormat.GetAlignment();

   // Create a second StringFormat object with the same alignment.
   StringFormat stringFormat2;
   stringFormat2.SetAlignment(stringAlignment);

   // Use the second StringFormat object in a call to DrawString.
  graphics.DrawString(
      L"This text was formatted by a second StringFormat object.",
      56,  // string length
      &font,
      RectF(30, 30, 150, 200),
      &stringFormat2,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 30, 30, 150, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
Font, Graphics, LOGFONT, RectF, Status, StringAlignment, StringFormatFlags


StringFormat::GetDigitSubstitutionLanguage()

The GetDigitSubstitutionLanguage method gets the language that corresponds with the digits that are to be substituted for Western European digits.

LANGID GetDigitSubstitutionLanguage(void) const;

Parameters

This method has no parameters.

Return Values

This method returns a 16-bit value that forms a National Language Support (NLS) language identifier. This identifier indicates the language that corresponds with the substitution digits. For example, if this StringFormat object uses Arabic substitution digits, then this method will return a value that indicates an Arabic language. An NLS language identifier is constructed by the MAKELANGID macro declared in Winnt.h.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.


StringFormat::GetDigitSubstitutionMethod()

The GetDigitSubstitutionMethod method gets an element of the StringDigitSubstitute enumeration that indicates the digit substitution method that is used by this StringFormat object.

StringDigitSubstitute GetDigitSubstitutionMethod(void) const;

Parameters

This method has no parameters.

Return Values

This method returns an element of the StringDigitSubstitute enumeration.

Remarks

The digit substitution method replaces, in a string, Western European digits with digits that correspond to a user's locale or language.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.


StringFormat::GetFormatFlags()

The GetFormatFlags method gets the string format flags for this StringFormat object.

INT GetFormatFlags(void) const;

Parameters

This method has no parameters.

Return Values

This method returns a value that indicates which string format flags are set for this StringFormat object. This value can be any combination (the result of a bitwise OR applied to two or more elements) of elements of the StringFormatFlags enumeration.

Example Code [C++]

The following example creates a StringFormat object, sets the string's format flags, and then gets the 32-bit value that contains the format flags and stores it in a variable. The code then creates another StringFormat object and uses the stored format flags value to set the format flags of the second StringFormat object. Next, the code uses the second StringFormat object to draw a formatted string . The code also draws the string's layout rectangle.

VOID Example_GetFormatFlags(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush  solidBrush(Color(255, 255, 0, 0));
   FontFamily  fontFamily(L"Times New Roman");
   Font        font(&fontFamily, 24, FontStyleRegular, UnitPoint);

   // Create a StringFormat object, and set its format flags.
   StringFormat stringFormat;
   stringFormat.SetFormatFlags(
      StringFormatFlagsDirectionVertical | StringFormatFlagsNoFitBlackBox);

   // Get the format flags from the StringFormat object.
   INT flags = stringFormat.GetFormatFlags();

   // Create a second StringFormat object with the same flags.
   StringFormat stringFormat2;
   stringFormat2.SetFormatFlags(flags);

   // Use the second StringFormat object in a call to DrawString.
  graphics.DrawString(
      L"This text is vertical because of a format flag.",
      47,  // string length
      &font,
      RectF(30, 30, 150, 200),
      &stringFormat2,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 30, 30, 150, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
Status, StringFormatFlags


StringFormat::GetHotkeyPrefix()

The GetHotkeyPrefix method gets an element of the HotkeyPrefix enumeration that indicates the type of processing that is performed on a string when a hot key prefix, an ampersand (&), is encountered.

HotkeyPrefix GetHotkeyPrefix(void) const;

Parameters

This method has no parameters.

Return Values

This method returns an element of the HotkeyPrefix enumeration that indicates the type of hot key prefix processing that is performed on a string.

Remarks

Hot keys, also called access keys, are keys that are programmed to provide an end user with keyboard shortcuts to functionality and are activated by pressing the ALT key. The keys are application dependent and are identified by an underscored letter, typically in a menu name or menu item; for example, when you press ALT, the letter F of the File menu is underscored. The F key is a shortcut to display the File menu.

A client programmer designates a hot key in an application by using the hot key prefix, an ampersand (&), in a string that typically is displayed as the name of a menu or an item in a menu and by using the SetHotkeyPrefix method to set the appropriate type of processing. When a character in a string is preceded with an ampersand, the key that corresponds to the character becomes a hot key during the processing that occurs when the string is drawn on the display device. The ampersand is called a hot key prefix because it precedes the character to be activated. If HotkeyPrefixNone is passed to SetHotkeyPrefix, no processing of hot key prefixes occurs.

Note The term hot key is used synonymously here with the term access key. The term hot key may have a different meaning in other Windows APIs.

Example Code [C++]

The following example creates a StringFormat object, sets the type of hot key prefix processing to be performed on the string, and then gets the type of processing and stores it in a variable. The code then creates a second StringFormat object and uses the stored value to set the type of hot key prefix processing for the second StringFormat object. The code uses the second StringFormat object to draw a string that contains the hot key prefix character. The code also draws the string's layout rectangle.

VOID Example_GetHotkeyPrefix(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush  solidBrush(Color(255, 255, 0, 0));
   FontFamily  fontFamily(L"Times New Roman");
   Font        font(&fontFamily, 24, FontStyleRegular, UnitPixel);

   // Create a StringFormat object, and set its hot key prefix.
   StringFormat stringFormat;
   stringFormat.SetHotkeyPrefix(HotkeyPrefixShow);

   // Get the hot key prefix from the StringFormat object.
   HotkeyPrefix hotkeyPrefix = stringFormat.GetHotkeyPrefix();

   // Create a second StringFormat object with the same hot key prefix.
   StringFormat stringFormat2;
   stringFormat2.SetHotkeyPrefix(hotkeyPrefix);

   // Use the second StringFormat object in a call to DrawString.
  graphics.DrawString(
      L"This &text has some &underlined characters.",
      43,  // string length
      &font,
      RectF(30, 30, 160, 200),
      &stringFormat2,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 30, 30, 160, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
HotkeyPrefix
Concepts
Menu Access Keys, Menu Shortcut Keys, Hot-Key Support


StringFormat::GetLastStatus()

The GetLastStatus method returns a value that indicates the nature of this StringFormat object's most recent method failure.

Status GetLastStatus(void) const;

Parameters

This method has no parameters.

Return Values

The GetLastStatus method returns an element of the Status enumeration.

If no methods invoked on this StringFormat object have failed since the previous call to GetLastStatus, then GetLastStatus returns Ok.

If at least one method invoked on this StringFormat object has failed since the previous call to GetLastStatus, then GetLastStatus returns a value that indicates the nature of the most recent failure.

Remarks

You can call GetLastStatus immediately after constructing a StringFormat object to determine whether the constructor succeeded.

The first time you call the GetLastStatus method of a StringFormat object, it returns Ok if the constructor succeeded and all methods invoked so far on the StringFormat object succeeded. Otherwise, it returns a value that indicates the nature of the most recent failure.

Example Code [C++]

The following example creates a StringFormat object, calls two StringFormat methods, and then checks the status to see if an error occurred during the construction or either of the method calls.

StringFormat stringFormat;
stringFormat.SetAlignment(StringAlignmentCenter);
HotkeyPrefix hotkeyPrefix = stringFormat.GetHotkeyPrefix();

if (stringFormat.GetLastStatus() == Ok)
{
   // There have been no errors since the previous call to GetLastStatus.
}
else
{
   // An error occurred since the previous call to GetLastStatus.
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
StringFormatFlags


StringFormat::GetLineAlignment()

The GetLineAlignment method gets an element of the StringAlignment enumeration that indicates the line alignment of this StringFormat object in relation to the origin of the layout rectangle. The line alignment setting specifies how to align the string vertically in the layout rectangle. The layout rectangle is used to position the displayed string.

StringAlignment GetLineAlignment(void) const;

Parameters

This method has no parameters.

Return Values

This method returns an element of the StringAlignment enumeration.

Example Code [C++]

The following example creates a StringFormat object, sets the string's line alignment, and then gets the line alignment setting and stores it in a variable. The code then creates a second StringFormat object and uses the stored alignment value to set the line alignment of the second StringFormat object. Next, the code uses the second StringFormat object to draw a formatted string. The code also draws the string's layout rectangle.

VOID Example_GetLineAlignment(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush  solidBrush(Color(255, 255, 0, 0));
   FontFamily  fontFamily(L"Times New Roman");
   Font        font(&fontFamily, 24, FontStyleRegular, UnitPixel);

   // Create a StringFormat object, and set its line alignment.
   StringFormat stringFormat;
   stringFormat.SetLineAlignment(StringAlignmentCenter);

   // Get the line alignment setting from the StringFormat object.
   StringAlignment stringAlignment = stringFormat.GetLineAlignment();

   // Create a second StringFormat object with the same line alignment.
   StringFormat stringFormat2;
   stringFormat2.SetLineAlignment(stringAlignment);

   // Use the second StringFormat object in a call to DrawString.
   graphics.DrawString(
      L"This text was formatted by a second StringFormat object.",
      56,  // string length
      &font,
      RectF(30, 30, 150, 200),
      &stringFormat2,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 30, 30, 150, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
StringFormatFlags, StringAlignment


StringFormat::GetMeasurableCharacterRangeCount()

The GetMeasurableCharacterRangeCount method gets the number of measurable character ranges that are currently set. The character ranges that are set can be measured in a string by using the Graphics::MeasureCharacterRanges method.

INT GetMeasurableCharacterRangeCount(void) const;

Parameters

This method has no parameters.

Return Values

This method returns an integer that indicates the number of character ranges that can be measured by Graphics::MeasureCharacterRanges.

Example Code [C++]

The following example defines three ranges of character positions within a string and sets those ranges in a StringFormat object. Next, the GetMeasurableCharacterRangeCount method is used to get the number of character ranges that are currently set in the StringFormat object. This number is then used to allocate a buffer large enough to store the regions that correspond with the ranges. Then, the Graphics::MeasureCharacterRanges method is used to get the three regions of the display that are occupied by the characters that are specified by the ranges.

VOID GetMeasCharRangeCount(HDC hdc)
{
   Graphics graphics(hdc);

   // Brushes and pens used for drawing and painting
   SolidBrush blueBrush(Color(255, 0, 0, 255));
   SolidBrush redBrush(Color(100, 255, 0, 0));
   Pen        blackPen(Color(255, 0, 0, 0));

   // Layout rectangle used for drawing string
   RectF   layoutRect(20.0f, 20.0f, 130.0f, 130.0f);

   // Three ranges of character positions within the string
   CharacterRange charRanges[3] = { CharacterRange(3, 5),
                                    CharacterRange(15, 2),
                                    CharacterRange(30, 15), };

   // Font and string format used to apply to string when drawing
   Font         myFont(L"Times New Roman", 16.0f);
   StringFormat strFormat;

    // Other variables
   Region* pCharRangeRegions; // pointer to CharacterRange regions
   short   i;                 // loop counter
   INT     count;             // number of character ranges set
   WCHAR   string[] = L"The quick, brown fox easily jumps over the lazy dog.";

   // Set three ranges of character positions.
   strFormat.SetMeasurableCharacterRanges(3, charRanges);

   // Get the number of ranges that have been set, and allocate memory to
   // store the regions that correspond to the ranges.
   count = strFormat.GetMeasurableCharacterRangeCount();
   pCharRangeRegions = new Region[count];

   // Get the regions that correspond to the ranges within the string.
   // Then draw the string and show the regions.
   graphics.MeasureCharacterRanges(string, -1,
      &myFont, layoutRect, &strFormat, count, pCharRangeRegions);
   graphics.DrawString(string, -1,
      &myFont, layoutRect, &strFormat, &blueBrush);
   graphics.DrawRectangle(&blackPen, layoutRect);
   for ( i = 0; i < count; i++)
   {
      graphics.FillRegion(&redBrush, pCharRangeRegions + i);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
MeasureCharacterRanges, SetMeasurableCharacterRanges


StringFormat::GetTabStopCount()

The GetTabStopCount method gets the number of tab-stop offsets in this StringFormat object.

INT GetTabStopCount(void) const;

Parameters

This method has no parameters.

Return Values

This method returns an integer that indicates the number of tab stops in this StringFormat object.

Example Code [C++]

The following example creates a StringFormat object, sets tab stops, and uses the StringFormat object to draw a string that contains tab characters (\t). The code also draws the string's layout rectangle. Then, the code gets the tab stops and proceeds to use or inspect the tab stops in some way.

VOID Example_GetTabStop(HDC hdc)
{
   Graphics graphics(hdc);

   REAL         tabs[] = {150, 100, 100};
   FontFamily   fontFamily(L"Courier New");
   Font         font(&fontFamily, 12, FontStyleRegular, UnitPoint);
   SolidBrush   solidBrush(Color(255, 0, 0, 255));

   StringFormat stringFormat;
   stringFormat.SetTabStops(0, 3, tabs);
   graphics.DrawString(
      L"Name\tTest 1\tTest 2\tTest 3",
      25,
      &font,
      RectF(20, 20, 500, 100),
      &stringFormat,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 20, 20, 500, 100);

   // Get the tab stops.
   INT   tabStopCount = 0;
   REAL  firstTabOffset = 0;
   REAL* tabStops = NULL;

   tabStopCount = stringFormat.GetTabStopCount();
   tabStops = (REAL*)malloc(tabStopCount*sizeof(REAL));
   stringFormat.GetTabStops(tabStopCount, &firstTabOffset, tabStops);

   for(INT j = 0; j < tabStopCount; ++j)
   {
      // Inspect or use the value in tabStops[j].
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.


StringFormat::GetTabStops(count, firstTabOffset, tabStops)

The GetTabStops method gets the offsets of the tab stops in this StringFormat object.

Status GetTabStops(
  INT count,
  REAL* firstTabOffset,
  REAL* tabStops
) const;

Parameters

count
[in] Integer that specifies the number of tab-stop offsets in the tabStops array.
firstTabOffset
[out] Pointer to a REAL that receives the initial offset position. This initial offset position is relative to the string's origin and the offset of the first tab stop is relative to the initial offset position.
tabStops
[out] Pointer to an array of type REAL that receives the tab-stop offsets. The offset of the first tab stop is the first value in the array, the offset of the second tab stop, the second value in the array, and so on.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Each tab-stop offset in the tabStops array, except the first one, is relative to the previous one. The first tab-stop offset is relative to the initial offset position indicated by firstTabOffset. For example, if the initial offset position is 8 and the first tab-stop offset is 50, then the first tab stop is at position 58. If the initial offset position is zero, then the first tab-stop offset is relative to position 0, the string origin.

Example Code [C++]

The following example creates a StringFormat object, sets tab stops, and uses the StringFormat object to draw a string that contains tab characters (\t). The code also draws the string's layout rectangle. Then, the code gets the tab stops and proceeds to use or inspect the tab stops in some way.

VOID Example_GetTabStop(HDC hdc)
{
   Graphics graphics(hdc);

   REAL         tabs[] = {150, 100, 100};
   FontFamily   fontFamily(L"Courier New");
   Font         font(&fontFamily, 12, FontStyleRegular, UnitPoint);
   SolidBrush   solidBrush(Color(255, 0, 0, 255));

   StringFormat stringFormat;
   stringFormat.SetTabStops(0, 3, tabs);
   graphics.DrawString(
      L"Name\tTest 1\tTest 2\tTest 3",
      25,
      &font,
      RectF(20, 20, 500, 100),
      &stringFormat,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 20, 20, 500, 100);

   // Get the tab stops.
   INT   tabStopCount = 0;
   REAL  firstTabOffset = 0;
   REAL* tabStops = NULL;

   tabStopCount = stringFormat.GetTabStopCount();
   tabStops = (REAL*)malloc(tabStopCount*sizeof(REAL));
   stringFormat.GetTabStops(tabStopCount, &firstTabOffset, tabStops);

   for(INT j = 0; j < tabStopCount; ++j)
   {
      // Inspect or use the value in tabStops[j].
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
Status
Tasks and Examples
Formatting Text


StringFormat::GetTrimming()

The GetTrimming method gets an element of the StringTrimming enumeration that indicates the trimming style of this StringFormat object. The trimming style determines how to trim characters from a string that is too large to fit in the layout rectangle.

StringTrimming GetTrimming(void) const;

Parameters

This method has no parameters.

Return Values

This method returns an element of the StringTrimming enumeration.

Example Code [C++]

The following example creates a StringFormat object, sets the string's trimming style, and then gets the trimming style and stores it in a variable. The code then creates a second StringFormat object and uses the stored trimming style to set the trimming style of the second StringFormat object. Next, the code uses the second StringFormat object to draw a formatted string. The code also draws the string's layout rectangle.

VOID Example_GetTrimming(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush  solidBrush(Color(255, 255, 0, 0));
   FontFamily  fontFamily(L"Times New Roman");
   Font        font(&fontFamily, 24, FontStyleRegular, UnitPixel);

   // Create a StringFormat object, and set its trimming style.
   StringFormat stringFormat;
   stringFormat.SetTrimming(StringTrimmingWord);

   // Get the trimming setting from the StringFormat object.
   StringTrimming stringTrimming = stringFormat.GetTrimming();

   // Create a second StringFormat object with the same trimming style.
   StringFormat stringFormat2;
   stringFormat2.SetTrimming(stringTrimming);

   // Use the second StringFormat object in a call to DrawString.
   graphics.DrawString(
      L"One two three four five six seven eight nine ten",
      47,  // string length
      &font,
      RectF(30, 30, 160, 60),
      &stringFormat2,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 30, 30, 160, 60);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.


StringFormat::SetAlignment(align)

The SetAlignment method sets the character alignment of this StringFormat object in relation to the origin of the layout rectangle. A layout rectangle is used to position the displayed string.

Status SetAlignment(
  StringAlignment align
);

Parameters

align
[in] Element of the StringAlignment enumeration that specifies how a string is aligned in reference to the bounding rectangle.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a StringFormat object, sets the character alignment, and draws the string using that alignment. The code also draws the string's layout rectangle.

VOID Example_SetAlignment(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush  solidBrush(Color(255, 255, 0, 0));
   FontFamily  fontFamily(L"Times New Roman");
   Font        font(&fontFamily, 24, FontStyleRegular, UnitPixel);

   StringFormat stringFormat;
   stringFormat.SetAlignment(StringAlignmentFar);

   graphics.DrawString(
      L"This text was formatted by a StringFormat object.",
      49,  // string length
      &font,
      RectF(30, 30, 150, 200),
      &stringFormat,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 30, 30, 150, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
Font, RectF, Status, StringAlignment


StringFormat::SetDigitSubstitution(language, substitute)

The SetDigitSubstitution method sets the digit substitution method and the language that corresponds to the digit substitutes.

Status SetDigitSubstitution(
  LANGID language,
  StringDigitSubstitute substitute
);

Parameters

language
[in] Sixteen-bit value that forms a National Language Support (NLS) language identifier. The identifier specifies the language associated with the substitute digits. For example, if this StringFormat object uses Arabic substitution digits, then this method will return a value that indicates an Arabic language. An NLS language identifier is constructed by the MAKELANGID macro, declared in Winnt.h.
substitute
[in] Element of the StringDigitSubstitute enumeration that specifies the digit substitution method to be used.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

The digit substitution method, specified by an element of the StringDigitSubstitute enumeration, replaces, in a string, Western European digits with digits that correspond to a user's locale or language.

When specifying LANG_NEUTRAL as the language ID, it is common practice to pass just LANG_NEUTRAL as in the following example:

stat = FontFamily.GetFamilyName(name, LANG_NEUTRAL);

If you are specifying a language other than LANG_NEUTRAL, use MAKELANGID to create the language and sublanguage combination as in the following example:

LANGID language = MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL);

For a list of the available languages and sublanguages, see Winnt.h.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.


StringFormat::SetFormatFlags(flags)

The SetFormatFlags method sets the format flags for this StringFormat object. The format flags determine most of the characteristics of a StringFormat object.

Status SetFormatFlags(
  INT flags
);

Parameters

flags
[in] Thirty-two bit value that specifies the format flags that control most of the characteristics of the StringFormat object. The flags are set by applying a bitwise OR to elements of the StringFormatFlags enumeration.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a StringFormat object, sets the format flags, and draws the formatted string. The code also draws the string's layout rectangle.

VOID Example_SetFormatFlags(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush  solidBrush(Color(255, 255, 0, 0));
   FontFamily  fontFamily(L"Times New Roman");
   Font        font(&fontFamily, 24, FontStyleRegular, UnitPoint);

   StringFormat stringFormat;
   stringFormat.SetFormatFlags(
      StringFormatFlagsDirectionVertical | StringFormatFlagsNoFitBlackBox);

   graphics.DrawString(
      L"This text is vertical because of a format flag.",
      47,  // string length
      &font,
      RectF(30, 30, 150, 200),
      &stringFormat,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 30, 30, 150, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
Status


StringFormat::SetHotkeyPrefix(hotkeyPrefix)

The SetHotkeyPrefix method sets the type of processing that is performed on a string when the hot key prefix, an ampersand (&), is encountered. The ampersand is called the hot key prefix and can be used to designate certain keys as hot keys.

Status SetHotkeyPrefix(
  HotkeyPrefix hotkeyPrefix
);

Parameters

hotkeyPrefix
[in] Element of the HotkeyPrefix enumeration that specifies how to process the hot key prefix.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Hot keys, also called access keys, are keys that are programmed to provide an end user with keyboard shortcuts to functionality and are activated by pressing the ALT key. The keys are application dependent and are identified by an underscored letter, typically in a menu name or menu item; for example, when you press ALT, the letter F of the File menu is underscored. The F key is a shortcut to display the File menu.

A client programmer designates a hot key in an application by using the hot key prefix, an ampersand (&), in a string that typically is displayed as the name of a menu or an item in a menu and by using the SetHotkeyPrefix method to set the appropriate type of processing. When a character in a string is preceded with an ampersand, the key that corresponds to the character becomes a hot key during the processing that occurs when the string is drawn on the display device. The ampersand is called a hot key prefix because it precedes the character to be activated. If HotkeyPrefixNone is passed to SetHotkeyPrefix, no processing of the hot key prefix occurs.

Note The term hot key is used synonymously here with the term access key. The term hot key may have a different meaning in other Windows APIs.

Example Code [C++]

The following example creates a StringFormat object and sets the type of hot key prefix processing to be performed on the string. The code then uses the StringFormat object to draw a string that contains the hot key prefix character. The code also draws the string's layout rectangle.

VOID Example_SetHotkeyPrefix(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush  solidBrush(Color(255, 255, 0, 0));
   FontFamily  fontFamily(L"Times New Roman");
   Font        font(&fontFamily, 24, FontStyleRegular, UnitPixel);

   StringFormat stringFormat;
   stringFormat.SetHotkeyPrefix(HotkeyPrefixShow);

   graphics.DrawString(
      L"This &text has some &underlined characters.",
      43,  // string length
      &font,
      RectF(30, 30, 160, 200),
      &stringFormat,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 30, 30, 160, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
GetHotkeyPrefix, HotkeyPrefix
Concepts
Menu Access Keys, Menu Shortcut Keys, Hot-Key Support


StringFormat::SetLineAlignment(align)

The SetLineAlignment method sets the line alignment of this StringFormat object in relation to the origin of the layout rectangle. The line alignment setting specifies how to align the string vertically in the layout rectangle. The layout rectangle is used to position the displayed string.

Status SetLineAlignment(
  StringAlignment align
);

Parameters

align
[in] Element of the StringAlignment enumeration that specifies how to align a string in reference to the layout rectangle.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a StringFormat object, sets the line alignment, and draws the string using that alignment. The code also draws the string's layout rectangle.

VOID Example_SetLineAlignment(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush  solidBrush(Color(255, 255, 0, 0));
   FontFamily  fontFamily(L"Times New Roman");
   Font        font(&fontFamily, 24, FontStyleRegular, UnitPixel);

   StringFormat stringFormat;
   stringFormat.SetLineAlignment(StringAlignmentCenter);

   graphics.DrawString(
      L"This text was formatted by a StringFormat object.",
      48,  // string length
      &font,
      RectF(30, 30, 150, 200),
      &stringFormat,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 30, 30, 150, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
Font, Graphics, RectF, SolidBrush, StringAlignment, StringFormatFlags, Status


StringFormat::SetMeasurableCharacterRanges(rangeCount, ranges)

The SetMeasurableCharacterRanges method sets a series of character ranges for this StringFormat object that, when in a string, can be measured by the Graphics::MeasureCharacterRanges method.

Status SetMeasurableCharacterRanges(
  INT rangeCount,
  const CharacterRange* ranges
);

Parameters

rangeCount
[in] Integer that specifies the number of character ranges in the ranges array.
ranges
[in] Pointer to an array of CharacterRange objects that specify the character ranges to be measured.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example defines three ranges of character positions within a string and sets those ranges in a StringFormat object. Next, the Graphics::MeasureCharacterRanges method is used to get the three regions of the display that are occupied by the characters that are specified by the ranges. This is done for three different layout rectangles to show how the regions change according to the layout of the string. Also, on the third repetition, the string format flags are changed so that the regions measured will include trailing spaces.

VOID SetMeasCharRanges(HDC hdc)
{
   Graphics graphics(hdc);

   // Brushes and pens used for drawing and painting
   SolidBrush blueBrush(Color(255, 0, 0, 255));
   SolidBrush redBrush(Color(100, 255, 0, 0));
   Pen        blackPen(Color(255, 0, 0, 0));

   // Layout rectangles used for drawing strings
   RectF   layoutRect_A(20.0f, 20.0f, 130.0f, 130.0f);
   RectF   layoutRect_B(160.0f, 20.0f, 165.0f, 130.0f);
   RectF   layoutRect_C(335.0f, 20.0f, 165.0f, 130.0f);

   // Three ranges of character positions within the string
   CharacterRange charRanges[3] = { CharacterRange(3, 5),
                                    CharacterRange(15, 2),
                                    CharacterRange(30, 15), };

   // Font and string format used to apply to string when drawing
   Font         myFont(L"Times New Roman", 16.0f);
   StringFormat strFormat;

    // Other variables
   Region* pCharRangeRegions; // pointer to CharacterRange regions
   short   i;                 // loop counter
   INT     count;             // number of character ranges set
   WCHAR   string[] = L"The quick, brown fox easily jumps over the lazy dog.";

   // Set three ranges of character positions.
   strFormat.SetMeasurableCharacterRanges(3, charRanges);

   // Get the number of ranges that have been set, and allocate memory to
   // store the regions that correspond to the ranges.
   count = strFormat.GetMeasurableCharacterRangeCount();
   pCharRangeRegions = new Region[count];

   // Get the regions that correspond to the ranges within the string when
   // layout rectangle A is used. Then draw the string, and show the
   // regions.
   graphics.MeasureCharacterRanges(string, -1,
      &myFont, layoutRect_A, &strFormat, count, pCharRangeRegions);
   graphics.DrawString(string, -1,
      &myFont, layoutRect_A, &strFormat, &blueBrush);
   graphics.DrawRectangle(&blackPen, layoutRect_A);
   for ( i = 0; i < count; i++)
   {
      graphics.FillRegion(&redBrush, pCharRangeRegions + i);
   }

   // Get the regions that correspond to the ranges within the string when
   // layout rectangle B is used. Then draw the string, and show the
// regions.
   graphics.MeasureCharacterRanges(string, -1,
      &myFont, layoutRect_B, &strFormat, count, pCharRangeRegions);
   graphics.DrawString(string, -1,
      &myFont, layoutRect_B, &strFormat, &blueBrush);
   graphics.DrawRectangle(&blackPen, layoutRect_B);
   for ( i = 0; i < count; i++)
   {
      graphics.FillRegion(&redBrush, pCharRangeRegions + i);
   }

   // Get the regions that correspond to the ranges within the string when
   // layout rectangle C is used. Set trailing spaces to be included in the
   // regions. Then draw the string, and show the regions.
strFormat.SetFormatFlags(StringFormatFlagsMeasureTrailingSpaces);
   graphics.MeasureCharacterRanges(string, -1,
      &myFont, layoutRect_C, &strFormat, count, pCharRangeRegions);
   graphics.DrawString(string, -1,
      &myFont, layoutRect_C, &strFormat, &blueBrush);
   graphics.DrawRectangle(&blackPen, layoutRect_C);
   for ( i = 0; i < count; i++)
   {
      graphics.FillRegion(&redBrush, pCharRangeRegions + i);
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
GetMeasurableCharacterRangeCount, MeasureCharacterRanges


StringFormat::SetTabStops(firstTabOffset, count, tabStops)

The SetTabStops method sets the offsets for tab stops in this StringFormat object.

Status SetTabStops(
  REAL firstTabOffset,
  INT count,
  const REAL* tabStops
);

Parameters

firstTabOffset
[in] Real number that specifies the initial offset position. This initial offset position is relative to the string's origin and the offset of the first tab stop is relative to the initial offset position.
count
[in] Integer that specifies the number of tab-stop offsets in the tabStops array.
tabStops
[in] Pointer to an array of real numbers that specify the tab-stop offsets. The offset of the first tab stop is the first value in the array, the offset of the second tab stop, the second value in the array, and so on.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Each tab-stop offset in the tabStops array, except the first one, is relative to the previous one. The first tab-stop offset is relative to the initial offset position specified by firstTabOffset. For example, if the initial offset position is 8 and the first tab-stop offset is 50, then the first tab stop is at position 58. If the initial offset position is zero, then the first tab-stop offset is relative to position 0, the string origin.

Example Code [C++]

The following example creates a StringFormat object, sets tab stops, and uses the StringFormat object to draw a string that contains tab characters (\t). The code also draws the string's layout rectangle.

VOID Example_SetTabStops(HDC hdc)
{
   Graphics graphics(hdc);

   REAL         tabs[] = {150, 100, 100};
   FontFamily   fontFamily(L"Courier New");
   Font         font(&fontFamily, 12, FontStyleRegular, UnitPoint);
   SolidBrush   solidBrush(Color(255, 0, 0, 255));

   StringFormat stringFormat;
   stringFormat.SetTabStops(0, 3, tabs);
   graphics.DrawString(
      L"Name\tTest 1\tTest 2\tTest 3",
      25,
      &font,
      RectF(20, 20, 500, 100),
      &stringFormat,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 20, 20, 500, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
GetTabStops
Tasks and Examples
Formatting Text


StringFormat::SetTrimming(trimming)

The SetTrimming method sets the trimming style for this StringFormat object. The trimming style determines how to trim a string so that it fits into the layout rectangle.

Status SetTrimming(
  StringTrimming trimming
);

Parameters

trimming
[in] Element of the StringTrimming enumeration that specifies the style of trimming to be performed on the string.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a StringFormat object, sets the trimming style, and uses the StringFormat object to draw a string. The code also draws the string's layout rectangle.

VOID Example_SetTrimming(HDC hdc)
{
   Graphics graphics(hdc);

   SolidBrush  solidBrush(Color(255, 255, 0, 0));
   FontFamily  fontFamily(L"Times New Roman");
   Font        font(&fontFamily, 24, FontStyleRegular, UnitPixel);

   StringFormat stringFormat;
   stringFormat.SetTrimming(StringTrimmingEllipsisWord);

   graphics.DrawString(
      L"One two three four five six seven eight nine ten",
      47,  // string length
      &font,
      RectF(30, 30, 160, 60),
      &stringFormat,
      &solidBrush);

   // Draw the rectangle that encloses the text.
   Pen pen(Color(255, 255, 0, 0));
   graphics.DrawRectangle(&pen, 30, 30, 160, 60);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusstringformat.h; include Gdiplus.h.

See Also

Reference
Font, Pen, RectF, SolidBrush, Status, StringTrimming


TextureBrush Class

The TextureBrush class defines a Brush object that contains an Image object that is used for the fill. The fill image can be transformed by using the local Matrix object contained in the Brush object.

Inheritance

GdiplusBase
Brush
TextureBrush

Constructors

Constructor | Description
TextureBrush | Overloaded. Creates a new TextureBrush object.

Methods

Uninherited

Method | Description
GetImage | Gets a pointer to the Image object defined by this texture brush.
GetTransform | Gets the transformation matrix of this texture brush.
GetWrapMode | Gets the wrap mode currently set for this texture brush.
MultiplyTransform | Updates this brush's transformation matrix with the product of itself and another matrix.
ResetTransform | Resets the transformation matrix of this texture brush to the identity matrix.
RotateTransform | Updates this texture brush's current transformation matrix with the product of itself and a rotation matrix.
ScaleTransform | Updates this texture brush's current transformation matrix with the product of itself and a scaling matrix.
SetTransform | Sets the transformation matrix of this texture brush.
SetWrapMode | Sets the wrap mode of this texture brush.
TranslateTransform | Updates this brush's current transformation matrix with the product of itself and a translation matrix.

Inherited from Brush

Method | Description
Clone | Creates a new Brush object based on this brush.
GetLastStatus | Gets a value that indicates the nature of the most recent method failure.
GetType | Gets the type of this brush.


TextureBrush Constructors

This topic lists the constructors of the TextureBrush class. For a complete class listing, see TextureBrush Class.

  • TextureBrush(Image* image, Rect& dstRect, ImageAttributes* imageAttributes)
  • TextureBrush(Image* image, RectF& dstRect, ImageAttributes* imageAttributes)
  • TextureBrush(image, wrapMode)
  • TextureBrush(Image* image, WrapMode wrapMode, Rect& dstRect)
  • TextureBrush(Image* image, WrapMode wrapMode, RectF& dstRect)
  • TextureBrush(Image* image, WrapMode wrapMode, INT dstX, INT dstY, INT dstWidth, INT dstHeight)
  • TextureBrush(Image* image, WrapMode wrapMode, REAL dstX, REAL dstY, REAL dstWidth, REAL dstHeight)


TextureBrush::TextureBrush(Image* image, Rect& dstRect, ImageAttributes* imageAttributes)

Creates a TextureBrush object based on an image, a defining rectangle, and a set of image properties.

TextureBrush(
  Image* image,
  Rect& dstRect,
  ImageAttributes* imageAttributes
);

Parameters

image
[in] Pointer to an Image object that contains the bitmap of the image to use.
dstRect
[in] Reference to a rectangle that defines the size of this texture brush and the portion of the image to be used by this texture brush. If the Image object is created from a metafile, the brush uses the entire image, which is scaled to fit the size of the brush.
imageAttributes
[in] Optional. Pointer to an ImageAttributes object that contains properties of the image. The default value is NULL.

Remarks

The width and height of the dstRect rectangle define the width and height of a texture brush. A texture brush is always oriented at (0, 0). The upper-left point, width, and height of the rectangle specify the starting point, width, and height of the portion of the image to be used by a texture brush.

How this constructor uses the dstRect rectangle with nonmetafile images

If the dimensions of the dstRect rectangle are smaller than those of the image on which the brush is based, the brush's image is cropped — it is a portion of the image. If the dimensions of the dstRect rectangle are equal to those of the image, the brush's image is identical to the image. The dstRect rectangle must not include areas outside the dimensions of the image. Doing so will either produce unpredictable behavior or generate a run-time error. For example, suppose you have an image that is 256×256 pixels and you create a TextureBrush object based on this image, passing Rect(0, 156, 200, 100) as the dstRect parameter. The brush will use the lower-left portion of the image. The lower-left corner of this portion is also the lower-left corner of the image. Now suppose that you create another TextureBrush object based on the same image, passing Rect(0, 157, 200, 100) as the dstRect parameter. Note that this rectangle has its uppermost coordinate at 157 instead of 156. This rectangle extends one unit beyond the height of the image and will most likely generate an access violation.

How this constructor uses the dstRect rectangle with metafile images

If the dimensions of the dstRect rectangle are different from those of the image, the brush's image is scaled smaller or larger as needed to fit the rectangle. For example, suppose you have a metafile image that is 256×256 pixels and you create a TextureBrush object, passing Rect(0, 156, 200, 100) as the dstRect parameter. The brush's image will include all of the metafile image but will be scaled to fit the brush: It will be squished vertically and stretched horizontally. If the dimensions of the rectangle are equal to those of the image, the brush's image is identical to the image.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Image, ImageAttributes, Rect
Tasks and Examples
Filling a Shape with an Image Texture
Concepts
Brushes and Filled Shapes


TextureBrush::TextureBrush(Image* image, RectF& dstRect, ImageAttributes* imageAttributes)

Creates a TextureBrush object based on an image, a defining rectangle, and a set of image properties.

TextureBrush(
  Image* image,
  RectF& dstRect,
  ImageAttributes* imageAttributes
);

Parameters

image
[in] Pointer to an Image object that contains the bitmap of the image to use.
dstRect
[in] Reference to a rectangle that defines the size of this texture brush and the portion of the image to be used by this texture brush. If the Image object is created from a metafile, the brush uses the entire image, which is scaled to fit the size of the brush.
imageAttributes
[in] Optional. Pointer to an ImageAttributes object that contains properties of the image. The default value is NULL.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Image, ImageAttributes, Rect
Tasks and Examples
Filling a Shape with an Image Texture
Concepts
Brushes and Filled Shapes


TextureBrush::TextureBrush(image, wrapMode)

Creates a TextureBrush object based on an image and a wrap mode. The size of the brush defaults to the size of the image, so the entire image is used by the brush.

TextureBrush(
  Image* image,
  WrapMode wrapMode
);

Parameters

image
[in] Pointer to an Image object that contains the bitmap of the image to use.
wrapMode
[in] Optional. Element of the WrapMode enumeration that specifies how repeated copies of an image are used to tile an area when it is painted with this texture brush. The default value is WrapModeTile.

Remarks

An area that extends beyond the boundaries of the brush is tiled with repeated copies of the brush. A texture brush may have alternate tiles flipped in a certain direction, as specified by the wrap mode. Flipping has the effect of reversing the brush's image. For example, if the wrap mode is specified as WrapModeTileFlipX, the brush is flipped about a line that is parallel to the y-axis.

The texture brush is always oriented at (0, 0). If the wrap mode is specified as WrapModeClamp, no area outside of the brush is tiled. For example, suppose you create a texture brush, specifying WrapModeClamp as the wrap mode:

TextureBrush(&SomeImage, WrapModeClamp)

Then, you paint an area with the brush. If the size of the brush has a height of 50 and the painted area is a rectangle with its upper-left corner at (0, 50), you will see no repeated copies of the brush (no tiling).

The default wrap mode for a texture brush is WrapModeTile, which specifies no flipping of the tile and no clamping.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetWrapMode, Image, SetWrapMode, WrapMode
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


TextureBrush::TextureBrush(Image* image, WrapMode wrapMode, Rect& dstRect)

Creates a TextureBrush object based on an image, a wrap mode, and a defining rectangle.

TextureBrush(
  Image* image,
  WrapMode wrapMode,
  const Rect& dstRect
);

Parameters

image
[in] Pointer to an Image object that contains the bitmap of the image to use.
wrapMode
[in] Element of the WrapMode enumeration that specifies how repeated copies of an image are used to tile an area when it is painted with this texture brush.
dstRect
[in] Reference to a rectangle that defines the size of this texture brush and the portion of the image to be used by this texture brush. If the Image object is created from a metafile, the brush uses the entire image, which is scaled to fit the size of the brush.

Remarks

The width and height of a texture brush are defined by the width and height of the dstRect rectangle. A texture brush is always oriented at (0, 0). The upper-left point, width, and height of the rectangle specify the starting point, width, and height of the portion of the image to be used by a texture brush.

How this constructor uses the dstRect rectangle with nonmetafile images

If the dimensions of the dstRect rectangle are smaller than those of the image on which the brush is based, the brush's image is cropped — it is a portion of the image. If the dimensions of the dstRect rectangle are equal to those of the image, the brush's image is identical to the image. The dstRect rectangle must not include areas outside the dimensions of the image. Doing so will either produce unpredictable behavior or generate a run-time error. For example, suppose you have an image that is 256×256 pixels and you create a TextureBrush object based on this image, passing Rect(0, 156, 200, 100) as the dstRect parameter. The brush will use the lower left portion of the image. The lower-left corner of this portion is also the lower-left corner of the image. Now suppose that you create another TextureBrush object based on the same image, passing Rect(0, 157, 200, 100) as the dstRect parameter. Note that this rectangle has its uppermost coordinate at 157 instead of 156. This rectangle extends one unit beyond the height of the image and will most likely generate an access violation.

How this constructor uses the dstRect rectangle with metafile images

If the dimensions of the dstRect rectangle are different from those of the image, the brush's image is scaled smaller or larger as needed to fit the rectangle. For example, suppose you have a metafile image that is 256×256 pixels and you create a TextureBrush object, passing Rect(0, 156, 200, 100) as the dstRect parameter. The brush's image will include all of the metafile image but will be scaled to fit the brush: It will be squished vertically and stretched horizontally. If the dimensions of the rectangle are equal to those of the image, the brush's image is identical to the image.

How this constructor uses the wrap mode

An area that extends beyond the boundaries of the brush is tiled with repeated copies of the brush. A texture brush may have alternate tiles flipped in a certain direction, as specified by the wrap mode. Flipping has the effect of reversing the brush's image.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetWrapMode, Image, Rect, SetWrapMode, WrapMode
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


TextureBrush::TextureBrush(Image* image, WrapMode wrapMode, RectF& dstRect)

Creates a TextureBrush object based on an image, a wrap mode, and a defining rectangle.

TextureBrush(
  Image* image,
  WrapMode wrapMode,
  const RectF& dstRect
);

Parameters

image
[in] Pointer to an Image object that contains the bitmap of the image to use.
wrapMode
[in] Element of the WrapMode enumeration that specifies how repeated copies of an image are used to tile an area when it is painted with this texture brush.
dstRect
[in] Reference to a rectangle that defines the size of this texture brush and the portion of the image to be used by this texture brush. If the Image object is created from a metafile, the brush uses the entire image, which is scaled to fit the size of the brush.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetWrapMode, Image, Rect, SetWrapMode, WrapMode
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


TextureBrush::TextureBrush(Image* image, WrapMode wrapMode, INT dstX, INT dstY, INT dstWidth, INT dstHeight)

Creates a TextureBrush object based on an image, a wrap mode, and a defining set of coordinates.

TextureBrush(
  Image* image,
  WrapMode wrapMode,
  INT dstX,
  INT dstY,
  INT dstWidth,
  INT dstHeight
);

Parameters

image
[in] Pointer to an Image object that contains the bitmap of the image to use.
wrapMode
[in] Element of the WrapMode enumeration that specifies how repeated copies of an image are used to tile an area when it is painted with this texture brush.
dstX
[in] Leftmost coordinate of the image portion to be used by this brush.
dstY
[in] Uppermost coordinate of the image portion to be used by this brush.
dstWidth
[in] Width of the brush and width of the image portion to be used by the brush.
dstHeight
[in] Height of the brush and height of the image portion to be used by the brush.

Remarks

The dstX, dstY, dstWidth, and dstHeight parameters specify a rectangle. The size of the brush is defined by dstWidth and dstHeight. The dstX and dstY parameters have no affect on the brush's size or position — the brush is always oriented at (0, 0). The dstX, dstY, dstWidth, and dstHeight parameters define the portion of the image to be used by the brush.

For example, suppose you have an image that is stored in an Image object and is 256×512 (width×height) pixels. Then you create a TextureBrush object based on this image as follows:

TextureBrush(&someImage, WrapModeTile, 12, 50, 100, 150).

The brush will have a width of 100 units and a height of 150 units. The brush will use a rectangular portion of the image. This portion begins at the pixel having coordinates (12, 50). The width and height of the portion are 100 and 150, respectively, measured from the starting pixel.

Now suppose you create another TextureBrush object based on the same image and specify a different rectangle:

TextureBrush(&someImage, WrapModeTile, 0, 0, 256, 512).

The brush will have width and height equal to 256 and 512, respectively. The brush will use the entire image instead of a portion of it because the rectangle specifies a starting pixel at coordinates (0, 0) and dimensions identical to those of the image.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetWrapMode, Image, SetWrapMode, WrapMode
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


TextureBrush::TextureBrush(Image* image, WrapMode wrapMode, REAL dstX, REAL dstY, REAL dstWidth, REAL dstHeight)

Creates a TextureBrush object based on an image, a wrap mode, and a defining set of coordinates.

TextureBrush(
  Image* image,
  WrapMode wrapMode,
  REAL dstX,
  REAL dstY,
  REAL dstWidth,
  REAL dstHeight
);

Parameters

image
[in] Pointer to an Image object that contains the bitmap of the image to use.
wrapMode
[in] Element of the WrapMode enumeration that specifies how repeated copies of an image are used to tile an area when it is painted with this texture brush.
dstX
[in] Leftmost coordinate of the image portion to be used by this brush.
dstY
[in] Uppermost coordinate of the image portion to be used by this brush.
dstWidth
[in] Width of the brush and width of the image portion to be used by the brush.
dstHeight
[in] Height of the brush and height of the image portion to be used by the brush.

Remarks

The dstX, dstY, dstWidth, and dstHeight parameters specify a rectangle. The size of the brush is defined by dstWidth and dstHeight. The dstX and dstY parameters have no affect on the brush's size or position — the brush is always oriented at (0, 0). The dstX, dstY, dstWidth, and dstHeight parameters define the portion of the image to be used by the brush.

For example, suppose you have an image that is stored in an Image object and is 256×512 (width×height) pixels. Then you create a TextureBrush object based on this image as follows:

TextureBrush(&someImage, WrapModeTile, 12, 50, 100, 150).

The brush will have a width of 100 units and a height of 150 units. The brush will use a rectangular portion of the image. This portion begins at the pixel having coordinates (12, 50). The width and height of the portion are 100 and 150, respectively, measured from the starting pixel.

Now suppose you create another TextureBrush object based on the same image and specify a different rectangle:

TextureBrush(&someImage, WrapModeTile, 0, 0, 256, 512).

The brush will have width and height equal to 256 and 512, respectively. The brush will use the entire image instead of a portion of it because the rectangle specifies a starting pixel at coordinates (0, 0) and dimensions identical to those of the image.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

GetWrapMode, Image, SetWrapMode, WrapMode

Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


TextureBrush Methods

This topic lists the methods of the TextureBrush class. For a complete class listing, see TextureBrush Class.

  • Clone()
  • GetImage()
  • GetLastStatus()
  • GetTransform(matrix)
  • GetType()
  • GetWrapMode()
  • MultiplyTransform(matrix, order)
  • ResetTransform()
  • RotateTransform(angle, order)
  • ScaleTransform(sx, sy, order)
  • SetTransform(matrix)
  • SetWrapMode(wrapMode)
  • TranslateTransform(dx, dy, order)


TextureBrush::GetImage()

The GetImage method gets a pointer to the Image object that is defined by this texture brush.

Image* GetImage(void) const;

Parameters

This method has no parameters.

Return Values

This method returns a pointer to the Image object that is defined by this texture brush.

Example Code [C++]

The following example creates a texture brush and uses it to fill an ellipse. The code then gets the brush's image and draws it.

VOID Example_GetImage(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a texture brush, and use it to fill an ellipse.
   Image image(L"sample.jpg");
   TextureBrush textureBrush(&image);
   graphics.FillEllipse(&textureBrush, 0, 0, 200, 100);

   // Get the brush's image, and draw that image.
   Image* pImage = textureBrush.GetImage();
   graphics.DrawImage(pImage, 10, 150);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Image
Tasks and Examples
Filling a Shape with an Image Texture
Concepts
Brushes and Filled Shapes


TextureBrush::GetTransform(matrix)

The GetTransform method gets the transformation matrix of this texture brush.

Status GetTransform(
  Matrix* matrix
) const;

Parameters

matrix
[out] Pointer to a Matrix object that receives the transformation matrix.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A TextureBrush object maintains a transformation matrix that can store any affine transformation. When you use a texture brush to fill an area, GDI+ transforms the brush's image according to the brush's transformation matrix and then fills the area. The transformed image exists only during rendering; the image stored in the TextureBrush object is not transformed. For example, suppose you call someTextureBrush.ScaleTransform(3) and then paint an area with someTextureBrush. The width of the brush's image triples when the area is painted, but the image stored in someTextureBrush remains unchanged.

Example Code [C++]

The following example creates a texture brush and sets the transformation of the brush. The code then gets the brush's transformation matrix and proceeds to inspect or use the elements.

VOID Example_GetTransform(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a texture brush, and set its transform.
   Image image(L"marble.jpg");
   TextureBrush textureBrush(&image);
   textureBrush.ScaleTransform(3, 2);

   // Obtain information about the texture brush.
   Matrix matrix;
   REAL elements[6];

   textureBrush.GetTransform(&matrix);
   matrix.GetElements(elements);

   for(INT j = 0; j <=5; ++j)
   {
      // Inspect or use the value in elements[j].
   }
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Matrix, ResetTransform, SetTransform
Tasks and Examples
Filling a Shape with an Image Texture, Transformations
Concepts
Brushes and Filled Shapes, Coordinate Systems and Transformations


TextureBrush::GetWrapMode()

The GetWrapMode method gets the wrap mode currently set for this texture brush.

WrapMode GetWrapMode(void) const;

Parameters

This method has no parameters.

Return Values

This method returns the wrap mode currently set for this texture brush. The value returned is one of the elements of the WrapMode enumeration.

Example Code [C++]

The following example creates a texture brush, sets the wrap mode of the brush, and uses the brush to fill a rectangle. Next, the code gets the wrap mode of the brush and stores the value. The code creates a second texture brush and uses the stored wrap mode to set the wrap mode of the second texture brush. Then, the code uses the second texture brush to fill a rectangle.

VOID Example_GetWrapMode(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a texture brush, and set its wrap mode.
   Image image(L"HouseAndTree.gif");
   TextureBrush textureBrush(&image);
   textureBrush.SetWrapMode(WrapModeTileFlipX);
   graphics.FillRectangle(&textureBrush, 0, 0, 200, 200);

   // Get the brush's wrap mode.
   WrapMode wrapMode = textureBrush.GetWrapMode();

   // Create a second texture brush with the same wrap mode.
   Image image2(L"RainbowR.bmp");
   TextureBrush textureBrush2(&image2);
   textureBrush2.SetWrapMode(wrapMode);
   graphics.FillRectangle(&textureBrush2, 250, 0, 200, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Image, SetWrapMode, WrapMode
Tasks and Examples
Tiling a Shape with an Image
Concepts
Brushes and Filled Shapes


TextureBrush::MultiplyTransform(matrix, order)

The MultiplyTransform method updates this brush's transformation matrix with the product of itself and another matrix.

Status MultiplyTransform(
  Matrix* matrix,
  MatrixOrder order
);

Parameters

matrix
[in] Pointer to the matrix to be multiplied by this brush's current transformation matrix.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of multiplication. MatrixOrderPrepend specifies that the passed matrix is on the left, and MatrixOrderAppend specifies that the passed matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a texture brush and sets the transformation of the brush. The code then uses the transformed brush to fill a rectangle.

VOID Example_MultiplyTransform(HDC hdc)
{
   Graphics graphics(hdc);

   Matrix matrix(3, 0, 0, 1, 0, 0); // Horizontal stretch

   Image image(L"HouseAndTree.Gif");
   TextureBrush textureBrush(&image);
   textureBrush.RotateTransform(30);                            // rotate
   textureBrush.MultiplyTransform(&matrix, MatrixOrderAppend);  // stretch
   graphics.FillRectangle(&textureBrush, 0, 0, 400, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, ResetTransform, RotateTransform, ScaleTransform, SetTransform, TranslateTransform
Tasks and Examples
Filling a Shape with an Image Texture, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


TextureBrush::ResetTransform()

The ResetTransform method resets the transformation matrix of this texture brush to the identity matrix. This means that no transformation takes place.

Status ResetTransform(void);

Parameters

This method has no parameters.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

Setting the transformation matrix to the identity matrix guarantees that no transformation is done. This method is often used to reset the transformation before making any adjustments (scaling, rotating, and so on) to it.

Example Code [C++]

The following example creates a texture brush and sets the transformation of the brush. Next, the code uses the transformed brush to fill a rectangle. Then, the code resets the transformation of the brush and uses the untransformed brush to fill a rectangle.

VOID Example_ResetTransform(HDC hdc)
{
   Graphics graphics(hdc);

   // Create a texture brush, and set its transformation.
   Image image(L"HouseAndTree.Gif");
   TextureBrush textureBrush(&image);
   textureBrush.RotateTransform(30);

   // Fill a rectangle with the transformed texture brush.
   graphics.FillRectangle(&textureBrush, 0, 0, 200, 100);

   textureBrush.ResetTransform();

   // Fill a rectangle with the texture brush (no transformation).
   graphics.FillRectangle(&textureBrush, 250, 0, 200, 100);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetTransform, Image, Matrix, MatrixOrder, MultiplyTransform, RotateTransform, ScaleTransform, SetTransform, TranslateTransform
Tasks and Examples
Filling a Shape with an Image Texture, Transformations
Concepts
Brushes and Filled Shapes, Coordinate Systems and Transformations


TextureBrush::RotateTransform(angle, order)

The RotateTransform method updates this texture brush's current transformation matrix with the product of itself and a rotation matrix.

Status RotateTransform(
  REAL angle,
  MatrixOrder order
);

Parameters

angle
[in] Real number that specifies the angle, in degrees, of rotation.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the rotation matrix is on the left, and MatrixOrderAppend specifies that the rotation matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A single 3×3 matrix can store any sequence of affine transformations. If you have several 3×3 matrices, each of which represents an affine transformation, the product of those matrices is a single 3×3 matrix that represents the entire sequence of transformations. The transformation represented by that product is called a composite transformation. For example, suppose matrix R represents a rotation, and matrix T represents a translation. If matrix M is the product RT, then matrix M represents a composite transformation: first rotate, then translate.

The order of matrix multiplication is important. In general, the matrix product RT is not the same as the matrix product TR. In the example given in the previous paragraph, the composite transformation represented by RT (first rotate, then translate) is not the same as the composite transformation represented by TR (first translate, then rotate).

Example Code [C++]

The following example creates a texture brush and sets the transformation of the brush. The code then uses the transformed brush to fill a rectangle.

VOID Example_RotateTransform(HDC hdc)
{
   Graphics graphics(hdc);

   Image image(L"HouseAndTree.Gif");
   TextureBrush textureBrush(&image);
   textureBrush.ScaleTransform(3, 1);                    // first scale
   textureBrush.RotateTransform(30, MatrixOrderAppend);  // then rotate
   graphics.FillRectangle(&textureBrush, 0, 0, 400, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
Image, Matrix, MatrixOrder, RotateTransform, ScaleTransform, SetTransform, TranslateTransform
Tasks and Examples
Filling Shapes with a Gradient Brush, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


TextureBrush::ScaleTransform(sx, sy, order)

The ScaleTransform method updates this texture brush's current transformation matrix with the product of itself and a scaling matrix.

Status ScaleTransform(
  REAL sx,
  REAL sy,
  MatrixOrder order
);

Parameters

sx
[in] Real number that specifies the amount to scale in the x direction.
sy
[in] Real number that specifies the amount to scale in the y direction.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the scaling matrix is on the left, and MatrixOrderAppend specifies that the scaling matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A single 3×3 matrix can store any sequence of affine transformations. If you have several 3×3 matrices, each of which represents an affine transformation, the product of those matrices is a single 3×3 matrix that represents the entire sequence of transformations. The transformation represented by that product is called a composite transformation. For example, suppose matrix T represents a translation, and matrix S represents a scaling. If matrix M is the product TS, then matrix M represents a composite transformation: first translate, then scale.

The order of matrix multiplication is important. In general, the matrix product RT is not the same as the matrix product TR. In the example given in the previous paragraph, the composite transformation represented by RT (first rotate, then translate) is not the same as the composite transformation represented by TR (first translate, then rotate).

Example Code [C++]

The following example creates a texture brush and sets the transformation of the brush. The code then uses the transformed brush to fill a rectangle.

VOID Example_ScaleTransform(HDC hdc)
{
   Graphics graphics(hdc);

   Image image(L"HouseAndTree.Gif");
   TextureBrush textureBrush(&image);
   textureBrush.RotateTransform(30);                      // first rotate
   textureBrush.ScaleTransform(3, 1, MatrixOrderAppend);  // then scale
   graphics.FillRectangle(&textureBrush, 0, 0, 400, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetTransform, Image, Matrix, MatrixOrder, MultiplyTransform, RotateTransform, SetTransform, TranslateTransform
Tasks and Examples
Filling Shapes with a Gradient Brush, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


TextureBrush::SetTransform(matrix)

The SetTransform method sets the transformation matrix of this texture brush.

Status SetTransform(
  const Matrix* matrix
);

Parameters

matrix
[in] Pointer to a Matrix object that specifies the transformation matrix to use.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

A TextureBrush object maintains a transformation matrix that can store any affine transformation. When you use a texture brush to fill an area, GDI+ transforms the brush's image according to the brush's transformation matrix and then fills the area. The transformed image exists only during rendering; the image stored in the TextureBrush object is not transformed. For example, suppose you call someTextureBrush.ScaleTransform(3) and then paint an area with someTextureBrush. The width of the brush's image triples when the area is painted, but the image stored in someTextureBrush remains unchanged.

Example Code [C++]

The following example creates a texture brush and sets the transformation of the brush. The code then uses the transformed brush to fill an ellipse.

VOID Example_SetTransform(HDC hdc)
{
   Graphics graphics(hdc);

   Matrix matrix(2, 0 , 0, 1, 0, 0);  // Horizontal stretch

   Image image(L"HouseAndTree.gif");
   TextureBrush textureBrush(&image);
   textureBrush.SetTransform(&matrix);
   graphics.FillEllipse(&textureBrush, 0, 0, 400, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, ResetTransform
Tasks and Examples
Filling a Shape with an Image Texture, Transformations
Concepts
Brushes and Filled Shapes, Coordinate Systems and Transformations


TextureBrush::SetWrapMode(wrapMode)

The SetWrapMode method sets the wrap mode of this texture brush.

Status SetWrapMode(
  WrapMode wrapMode
);

Parameters

wrapMode
[in] Element of the WrapMode enumeration that specifies how repeated copies of an image are used to tile an area when it is painted with this texture brush.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Remarks

An area that extends beyond the boundaries of the brush is tiled with repeated copies of the brush. A texture brush may have alternate tiles flipped in a certain direction, as specified by the wrap mode. Flipping has the effect of reversing the brush's image. For example, if the wrap mode is specified as WrapModeTileFlipX, the brush is flipped about a line that is parallel to the y-axis.

The texture brush is always oriented at (0, 0). If the wrap mode is specified as WrapModeClamp, no area outside of the brush is tiled. For example, suppose you create a texture brush, specifying WrapModeClamp as the wrap mode:

TextureBrush(&SomeImage, WrapModeClamp)

Then you paint an area with the brush. If the size of the brush has a height of 50 and the painted area is a rectangle with its upper-left corner at (0, 50), you will see no repeated copies of the brush (no tiling).

The default wrap mode for a texture brush is WrapModeTile, which specifies no flipping of the tile and no clamping.

Example Code [C++]

The following example creates a texture brush, sets the wrap mode of the brush, and uses the brush to fill a rectangle.

VOID Example_SetWrapMode(HDC hdc)
{
   Graphics graphics(hdc);

   Image image(L"HouseAndTree.gif");
   TextureBrush textureBrush(&image);
   textureBrush.SetWrapMode(WrapModeTileFlipX);
   graphics.FillRectangle(&textureBrush, 0, 0, 400, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetWrapMode, TextureBrush, WrapMode
Tasks and Examples
Filling a Shape with an Image Texture, Tiling a Shape with an Image
Concepts
Brushes and Filled Shapes


TextureBrush::TranslateTransform(dx, dy, order)

The TranslateTransform method updates this brush's current transformation matrix with the product of itself and a translation matrix.

Status TranslateTransform(
  REAL dx,
  REAL dy,
  MatrixOrder order
);

Parameters

dx
[in] Real number that specifies the horizontal component of the translation.
dy
[in] Real number that specifies the vertical component of the translation.
order
[in] Optional. Element of the MatrixOrder enumeration that specifies the order of the multiplication. MatrixOrderPrepend specifies that the translation matrix is on the left, and MatrixOrderAppend specifies that the translation matrix is on the right. The default value is MatrixOrderPrepend.

Return Values

If the method succeeds, it returns Ok, which is an element of the Status enumeration.

If the method fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following example creates a texture brush and sets the transformation of the brush. The code then uses the transformed brush to fill a rectangle.

VOID Example_TranslateTransform(HDC hdc)
{
   Graphics graphics(hdc);

   Image image(L"HouseAndTree.Gif");
   TextureBrush textureBrush(&image);
   textureBrush.ScaleTransform(3, 1);
   textureBrush.TranslateTransform(30, 0, MatrixOrderAppend);
   graphics.FillRectangle(&textureBrush, 0, 0, 400, 200);
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusbrush.h; include Gdiplus.h.

See Also

Reference
GetTransform, Matrix, MultiplyTransform, ResetTransform, RotateTransform, ScaleTransform, SetTransform
Tasks and Examples
Filling a Shape with an Image Texture, Transformations
Concepts
Brushes and Filled Shapes, Matrix Representation of Transformations


Functions

GDI+ provides the following functions:

  • GdiplusShutdown()
  • GdiplusStartup(token, input, output)
  • GetImageDecoders(numDecoders, size, decoders)
  • GetImageDecodersSize(numDecoders, size)
  • GetImageEncoders(numEncoders, size, encoders)
  • GetImageEncodersSize(numEncoders, size)


GdiplusShutdown()

The GdiplusShutdown function cleans up resources used by GDI+. Each call to GdiplusStartup should be paired with a call to GdiplusShutdown.

VOID GdiplusShutdown(
  ULONG_PTR token
);

Parameters

token
[in] Token returned by a previous call to GdiplusStartup.

Return Values

This method does not return a value.

Remarks

You must call GdiplusStartup before you create any GDI+ objects, and you must delete all of your GDI+ objects (or have them go out of scope) before you call GdiplusShutdown.

Example Code [C++]

For an example of calling GdiplusStartup and GdiplusShutdown, see GdiplusStartup.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusinit.h; include Gdiplus.h.
Library: Use Gdiplus.lib.

See Also

Reference
GdiplusStartup, GdiplusStartupInput, GdiplusStartupOutput
Tasks and Examples
Getting Started


GdiplusStartup(token, input, output)

The GdiplusStartup function initializes GDI+. Call GdiplusStartup before making any other GDI+ calls, and call GdiplusShutdown when you have finished using GDI+.

Status GdiplusStartup(
  ULONG_PTR* token,
  const GdiplusStartupInput* input,
  GdiplusStartupOutput* output
);

Parameters

token
[out] Pointer to a ULONG_PTR that receives a token. Pass the token to GdiplusShutdown when you have finished using GDI+.
input
[in] Pointer to a GdiplusStartupInput structure that contains the GDI+ version, a pointer to a debug callback function, a Boolean value that specifies whether to suppress the background thread, and a Boolean value that specifies whether to suppress external image codecs.
output
[out] Pointer to a GdiplusStartupOutput structure that receives a pointer to a notification hook function and a pointer to a notification unhook function. If the SuppressBackgroundThread data member of the input parameter is FALSE, then this parameter can be NULL.

Return Values

If the function succeeds, it returns Ok, which is an element of the Status enumeration.

If the function fails, it returns one of the other elements of the Status enumeration.

Remarks

You must call GdiplusStartup before you create any GDI+ objects, and you must delete all of your GDI+ objects (or have them go out of scope) before you call GdiplusShutdown.

You can call GdiplusStartup on one thread and call GdiplusShutdown on another thread as long as you delete all of your GDI+ objects (or have them go out of scope) before you call GdiplusShutdown.

Do not call GdiplusStartup or GdiplusShutdown in DllMain or in any function that is called by DllMain. If you want to create a DLL that uses GDI+, you should use one of the following techniques to initialize GDI+:

  • Require your clients to call GdiplusStartup before they call the functions in your DLL and to call GdiplusShutdown when they have finished using your DLL.
  • Export your own startup function that calls GdiplusStartup and your own shutdown function that calls GdiplusShutdown. Require your clients to call your startup function before they call other functions in your DLL and to call your shutdown function when they have finished using your DLL.
  • Call GdiplusStartup and GdiplusShutdown in each of your functions that make GDI+ calls.

Example Code [C++]

For an example of calling GdiplusStartup and GdiplusShutdown in a Windows application, see Getting Started.

The following console application uses a GDI+ Image object to retrieve the width and height of a JPEG image. The code calls GdiplusStartup before creating the Image object and calls GdiplusShutdown before terminating. Note that the Image object is deleted before the call to GdiplusShutdown.

In the following code, the variable gdiplusStartupInput is initialized by the default constructor of the GdiplusStartupInput structure. The default constructor sets the data members of the structure to the following values:

  • GdiplusVersion = 1
  • DebugEventCallback = NULL
  • SuppressBackgroundThread = FALSE
  • SuppressExternalCodecs = FALSE
#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   Image* image = new Image(L"FakePhoto.jpg");
   printf("The width of the image is %u.\n", image->GetWidth());
   printf("The height of the image is %u.\n", image->GetHeight());

   delete image;
   GdiplusShutdown(gdiplusToken);
   return 0;
}

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusinit.h; include Gdiplus.h.
Library: Use Gdiplus.lib.

See Also

Reference
GdiplusShutdown, GdiplusStartupInput, GdiplusStartupOutput
Tasks and Examples
Getting Started


GetImageDecoders(numDecoders, size, decoders)

The GetImageDecoders function gets an array of ImageCodecInfo objects that contain information about the available image decoders.

Status GetImageDecoders(
  UINT numDecoders,
  UINT size,
  ImageCodecInfo* decoders
);

Parameters

numDecoders
[in] Integer that specifies the number of available image decoders. Call GetImageDecodersSize to determine this number.
size
[in] Integer that specifies the size, in bytes, of the array of ImageCodecInfo objects. Call GetImageDecodersSize to determine this number.
decoders
[out] Pointer to a buffer that receives the array of ImageCodecInfo objects. You must allocate memory for this buffer. Call GetImageDecodersSize to determine the size of the required buffer.

Return Values

If the function succeeds, it returns Ok, which is an element of the Status enumeration.

If the function fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following console application lists the available image decoders:

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR           gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   UINT  num;        // number of image decoders
   UINT  size;       // size, in bytes, of the image decoder array

   ImageCodecInfo* pImageCodecInfo;

   // How many decoders are there?
   // How big (in bytes) is the array of all ImageCodecInfo objects?
   GetImageDecodersSize(&num, &size);

   // Create a buffer large enough to hold the array of ImageCodecInfo
   // objects that will be returned by GetImageDecoders.
   pImageCodecInfo = (ImageCodecInfo*)(malloc(size));

   // GetImageDecoders creates an array of ImageCodecInfo objects
   // and copies that array into a previously allocated buffer.
   // The third argument, imageCodecInfos, is a pointer to that buffer.
   GetImageDecoders(num, size, pImageCodecInfo);

   // Display the graphics file format (MimeType)
   // for each ImageCodecInfo object.
   for(UINT j = 0; j < num; ++j)
   {
      wprintf(L"%s\n", pImageCodecInfo[j].MimeType);
   }

   free(pImageCodecInfo);
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code produces the following output:

image/bmp
image/jpeg
image/gif
image/x-emf
image/x-wmf
image/tiff
image/png
image/x-icon

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimagecodec.h; include Gdiplus.h.
Library: Use Gdiplus.lib.

See Also

Reference
Bitmap, GetImageDecodersSize, GetImageEncoders, GetImageEncodersSize, Image, Metafile
Tasks and Examples
Using Image Encoders and Decoders


GetImageDecodersSize(numDecoders, size)

The GetImageDecodersSize function gets the number of available image decoders and the total size of the array of ImageCodecInfo objects that is returned by the GetImageDecoders function.

Status GetImageDecodersSize(
  UINT* numDecoders,
  UINT* size
);

Parameters

numDecoders
[out] Pointer to a UINT that receives the number of available image decoders.
size
[out] Pointer to a UINT that receives the total size, in bytes, of the array of ImageCodecInfo objects that is returned by the GetImageDecoders function.

Return Values

If the function succeeds, it returns Ok, which is an element of the Status enumeration.

If the function fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

For a code example, see GetImageDecoders.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimagecodec.h; include Gdiplus.h.
Library: Use Gdiplus.lib.

See Also

Reference
Bitmap, GetImageDecoders, GetImageEncoders, GetImageEncodersSize, Image, Metafile
Tasks and Examples
Using Image Encoders and Decoders


GetImageEncoders(numEncoders, size, encoders)

The GetImageEncoders function gets an array of ImageCodecInfo objects that contain information about the available image encoders.

Status GetImageEncoders(
  UINT numEncoders,
  UINT size,
  ImageCodecInfo* encoders
);

Parameters

numEncoders
[in] Integer that specifies the number of available image encoders. Call GetImageEncodersSize to determine this number.
size
[in] Integer that specifies the size, in bytes, of the array of ImageCodecInfo objects. Call GetImageEncodersSize to determine this number.
encoders
[out] Pointer to a buffer that receives the array of ImageCodecInfo objects. You must allocate memory for this buffer. Call GetImageEncodersSize to determine the size of the required buffer.

Return Values

If the function succeeds, it returns Ok, which is an element of the Status enumeration.

If the function fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

The following console application lists the available image encoders:

#include <windows.h>
#include <gdiplus.h>
#include <stdio.h>
using namespace Gdiplus;

INT main()
{
   // Initialize GDI+.
   GdiplusStartupInput gdiplusStartupInput;
   ULONG_PTR           gdiplusToken;
   GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

   UINT  num;        // number of image encoders
   UINT  size;       // size, in bytes, of the image encoder array

   ImageCodecInfo* pImageCodecInfo;

   // How many encoders are there?
   // How big (in bytes) is the array of all ImageCodecInfo obects?
   GetImageEncodersSize(&num, &size);

   // Create a buffer large enough to hold the array of ImageCodecInfo
   // objects that will be returned by GetImageEncoders.
   pImageCodecInfo = (ImageCodecInfo*)(malloc(size));

   // GetImageEncoders creates an array of ImageCodecInfo objects
   // and copies that array into a previously allocated buffer.
   // The third argument, imageCodecInfos, is a pointer to that buffer.
   GetImageEncoders(num, size, pImageCodecInfo);

   // Display the graphics file format (MimeType)
   // for each ImageCodecInfo object.
   for(UINT j = 0; j < num; ++j)
   {
      wprintf(L"%s\n", pImageCodecInfo[j].MimeType);
   }

   free(pImageCodecInfo);
   GdiplusShutdown(gdiplusToken);
   return 0;
}

The preceding code produces the following output:

image/bmp
image/jpeg
image/gif
image/tiff
image/png

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimagecodec.h; include Gdiplus.h.
Library: Use Gdiplus.lib.

See Also

Reference
Bitmap, GetImageDecodersSize, GetImageDecoders, GetImageEncodersSize, Image, Metafile
Tasks and Examples
Using Image Encoders and Decoders


GetImageEncodersSize(numEncoders, size)

The GetImageEncodersSize function gets the number of available image encoders and the total size of the array of ImageCodecInfo objects that is returned by the GetImageEncoders function.

Status GetImageEncodersSize(
  UINT* numEncoders,
  UINT* size
);

Parameters

numEncoders
[out] Pointer to a UINT that receives the number of available image encoders.
size
[out] Pointer to a UINT that receives the total size, in bytes, of the array of ImageCodecInfo objects that is returned by GetImageEncoders.

Return Values

If the function succeeds, it returns Ok, which is an element of the Status enumeration.

If the function fails, it returns one of the other elements of the Status enumeration.

Example Code [C++]

For a code example, see GetImageEncoders.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimagecodec.h; include Gdiplus.h.
Library: Use Gdiplus.lib.

See Also

Reference
Bitmap, GetImageDecoders, GetImageDecodersSize, GetImageEncodersSize, Image, Metafile
Tasks and Examples
Using Image Encoders and Decoders


Constants

GDI+ defines constants in the following categories:

  • Image File Format Constants
  • Image Frame Dimension Constants
  • Image Encoder Constants
  • Image Pixel Format Constants
  • Image Property Tag Type Constants
  • Image Property Tag Constants


Image File Format Constants

The Image::GetRawFormat method returns a globally unique identifier (GUID) that indicates the file format of an image. The following constants, defined in Gdiplusimaging.h, represent the GUIDs that identify those file formats:

ImageFormatBMP
Indicates the BMP (Windows bitmap) format.
ImageFormatEMF
Indicates the EMF (Enhanced Metafile) format.
ImageFormatEXIF
Indicates the Exif (Exchangeable Image File) format.
ImageFormatGIF
Indicates the GIF (Graphics Interchange Format) format.
ImageFormatIcon
Indicates the Icon format.
ImageFormatJPEG
Indicates the JPEG (Joint Photographic Experts Group) format.
ImageFormatMemoryBMP
Indicates that the image was constructed from a memory bitmap.
ImageFormatPNG
Indicates the PNG (Portable Network Graphics) format.
ImageFormatTIFF
Indicates the TIFF (Tag Image File Format) format.
ImageFormatUndefined
Indicates that GDI+ is unable to determine the format.
ImageFormatWMF
Indicates the WMF (Windows Metafile) format.


Image Frame Dimension Constants

The GIF and TIFF image file formats allow you to store multiple frames in a single image file. Multiple frames in a GIF file are used for animation, so the frames are said to be in the time dimension. Multiple frames in a TIFF file are typically used as separate pages, so the frames are said to be in the page dimension.

The following constants, defined in Gdiplusimaging.h, represent globally unique identifiers (GUIDs) that identify the page and time dimensions:

  • FrameDimensionPage
  • FrameDimensionTime


Image Encoder Constants

The Save and SaveAdd methods of the Image class receive an EncoderParameters object that contains an array of EncoderParameter objects. Each EncoderParameter object has a Guid data member that specifies the parameter category. The following constants, defined in Gdiplusimaging.h, represent globally unique identifiers (GUIDs) that specify the various parameter categories:

  • EncoderChrominanceTable
  • EncoderColorDepth
  • EncoderCompression
  • EncoderLuminanceTable
  • EncoderQuality
  • EncoderRenderMethod
  • EncoderSaveFlag
  • EncoderScanMethod
  • EncoderTransformation
  • EncoderVersion


Image Pixel Format Constants

The following constants, defined in Gdipluspixelformats.h, specify various pixel formats used in bitmaps:

PixelFormat1bppIndexed
Specifies that the format is 1 bit per pixel, indexed.
PixelFormat4bppIndexed
Specifies that the format is 4 bits per pixel, indexed.
PixelFormat8bppIndexed
Specifies that the format is 8 bits per pixel, indexed.
PixelFormat16bppARGB1555
Specifies that the format is 16 bits per pixel; 1 bit is used for the alpha component, and 5 bits each are used for the red, green, and blue components.
PixelFormat16bppGrayScale
Specifies that the format is 16 bits per pixel, grayscale.
PixelFormat16bppRGB555
Specifies that the format is 16 bits per pixel; 5 bits each are used for the red, green, and blue components. The remaining bit is not used.
PixelFormat16bppRGB565
Specifies that the format is 16 bits per pixel; 5 bits are used for the red component, 6 bits are used for the green component, and 5 bits are used for the blue component.
PixelFormat24bppRGB
Specifies that the format is 24 bits per pixel; 8 bits each are used for the red, green, and blue components.
PixelFormat32bppARGB
Specifies that the format is 32 bits per pixel; 8 bits each are used for the alpha, red, green, and blue components.
PixelFormat32bppPARGB
Specifies that the format is 32 bits per pixel; 8 bits each are used for the alpha, red, green, and blue components. The red, green, and blue components are premultiplied according to the alpha component.
PixelFormat32bppRGB
Specifies that the format is 32 bits per pixel; 8 bits each are used for the red, green, and blue components. The remaining 8 bits are not used.
PixelFormat48bppRGB
Specifies that the format is 48 bits per pixel; 16 bits each are used for the red, green, and blue components.
PixelFormat64bppARGB
Specifies that the format is 64 bits per pixel; 16 bits each are used for the alpha, red, green, and blue components.
PixelFormat64bppPARGB
Specifies that the format is 64 bits per pixel; 16 bits each are used for the alpha, red, green, and blue components. The red, green, and blue components are premultiplied according to the alpha component.

Remarks

PixelFormat48bppRGB, PixelFormat64bppARGB, and PixelFormat64bppPARGB use 16 bits per color component (channel). GDI+ version 1.0 can read 16-bits-per-channel images, but such images are converted to an 8-bits-per-channel format for processing, displaying, and saving.


Image Property Tag Type Constants

You can store and retrieve image metadata with the help of a PropertyItem object. The type data member of a PropertyItem object specifies the data type of the values stored in the value data member of that same PropertyItem object.

The following constants, defined in Gdiplusimaging.h, can be assigned to the type data member of a PropertyItem object:

PropertyTagTypeASCII
Specifies that the value data member is a null-terminated ASCII string. If you set the type data member of a PropertyItem object to PropertyTagTypeASCII, you should set the length data member to the length of the string including the NULL terminator. For example, the string "HELLO" would have a length of 6.
PropertyTagTypeByte
Specifies that the value data member is an array of bytes.
PropertyTagTypeLong
Specifies that the value data member is an array of unsigned long (32-bit) integers.
PropertyTagTypeRational
Specifies that the value data member is an array of pairs of unsigned long integers. Each pair represents a fraction; the first integer is the numerator and the second integer is the denominator.
PropertyTagTypeShort
Specifies that the value data member is an array of unsigned short (16-bit) integers.
PropertyTagTypeSLONG
Specifies that the value data member is an array of signed long (32-bit) integers.
PropertyTagTypeSRational
Specifies that the value data member is an array of pairs of signed long integers. Each pair represents a fraction; the first integer is the numerator and the second integer is the denominator.
PropertyTagTypeUndefined
Specifies that the value data member is an array of bytes that can hold values of any data type.

See Also

Reference
Image Property Tag Constants, Image File Format Specifications
Tasks and Examples
Reading and Writing Metadata


Image Property Tag Constants

Several image file formats allow you to store metadata along with an image. Metadata is information about an image, for example, title, width, camera model, and artist. GDI+ provides a uniform way of storing and retrieving metadata from image files in the TIFF, JPEG, PNG, and Exif formats.

In GDI+, a piece of metadata is called a property item, and an individual property item is identified by a numerical constant called a property tag. You can store and retrieve metadata by calling the SetPropertyItem and GetPropertyItem methods of the Image class, and you don't have to be concerned with the details of how a particular file format stores that metadata.

The following topics list and describe the property items supported by GDI+. The descriptions are brief and general so that they apply to a variety of file formats. For a detailed description of how a property item is used in a particular file format, see the specification for that file format. For links to several file format specifications, see Image File Format Specifications.

  • Property Tags in Numerical Order
  • Property Tags in Alphabetical Order
  • Property Item Descriptions

See Also

Reference
Image Property Tag Type Constants
Tasks and Examples
Reading and Writing Metadata


Property Tags in Numerical Order

The following table lists the GDI+ image property tags in numerical order.

Property tag | Value
PropertyTagGpsVer | 0x0000
PropertyTagGpsLatitudeRef | 0x0001
PropertyTagGpsLatitude | 0x0002
PropertyTagGpsLongitudeRef | 0x0003
PropertyTagGpsLongitude | 0x0004
PropertyTagGpsAltitudeRef | 0x0005
PropertyTagGpsAltitude | 0x0006
PropertyTagGpsGpsTime | 0x0007
PropertyTagGpsGpsSatellites | 0x0008
PropertyTagGpsGpsStatus | 0x0009
PropertyTagGpsGpsMeasureMode | 0x000A
PropertyTagGpsGpsDop | 0x000B
PropertyTagGpsSpeedRef | 0x000C
PropertyTagGpsSpeed | 0x000D
PropertyTagGpsTrackRef | 0x000E
PropertyTagGpsTrack | 0x000F
PropertyTagGpsImgDirRef | 0x0010
PropertyTagGpsImgDir | 0x0011
PropertyTagGpsMapDatum | 0x0012
PropertyTagGpsDestLatRef | 0x0013
PropertyTagGpsDestLat | 0x0014
PropertyTagGpsDestLongRef | 0x0015
PropertyTagGpsDestLong | 0x0016
PropertyTagGpsDestBearRef | 0x0017
PropertyTagGpsDestBear | 0x0018
PropertyTagGpsDestDistRef | 0x0019
PropertyTagGpsDestDist | 0x001A
PropertyTagNewSubfileType | 0x00FE
PropertyTagSubfileType | 0x00FF
PropertyTagImageWidth | 0x0100
PropertyTagImageHeight | 0x0101
PropertyTagBitsPerSample | 0x0102
PropertyTagCompression | 0x0103
PropertyTagPhotometricInterp | 0x0106
PropertyTagThreshHolding | 0x0107
PropertyTagCellWidth | 0x0108
PropertyTagCellHeight | 0x0109
PropertyTagFillOrder | 0x010A
PropertyTagDocumentName | 0x010D
PropertyTagImageDescription | 0x010E
PropertyTagEquipMake | 0x010F
PropertyTagEquipModel | 0x0110
PropertyTagStripOffsets | 0x0111
PropertyTagOrientation | 0x0112
PropertyTagSamplesPerPixel | 0x0115
PropertyTagRowsPerStrip | 0x0116
PropertyTagStripBytesCount | 0x0117
PropertyTagMinSampleValue | 0x0118
PropertyTagMaxSampleValue | 0x0119
PropertyTagXResolution | 0x011A
PropertyTagYResolution | 0x011B
PropertyTagPlanarConfig | 0x011C
PropertyTagPageName | 0x011D
PropertyTagXPosition | 0x011E
PropertyTagYPosition | 0x011F
PropertyTagFreeOffset | 0x0120
PropertyTagFreeByteCounts | 0x0121
PropertyTagGrayResponseUnit | 0x0122
PropertyTagGrayResponseCurve | 0x0123
PropertyTagT4Option | 0x0124
PropertyTagT6Option | 0x0125
PropertyTagResolutionUnit | 0x0128
PropertyTagPageNumber | 0x0129
PropertyTagTransferFunction | 0x012D
PropertyTagSoftwareUsed | 0x0131
PropertyTagDateTime | 0x0132
PropertyTagArtist | 0x013B
PropertyTagHostComputer | 0x013C
PropertyTagPredictor | 0x013D
PropertyTagWhitePoint | 0x013E
PropertyTagPrimaryChromaticities | 0x013F
PropertyTagColorMap | 0x0140
PropertyTagHalftoneHints | 0x0141
PropertyTagTileWidth | 0x0142
PropertyTagTileLength | 0x0143
PropertyTagTileOffset | 0x0144
PropertyTagTileByteCounts | 0x0145
PropertyTagInkSet | 0x014C
PropertyTagInkNames | 0x014D
PropertyTagNumberOfInks | 0x014E
PropertyTagDotRange | 0x0150
PropertyTagTargetPrinter | 0x0151
PropertyTagExtraSamples | 0x0152
PropertyTagSampleFormat | 0x0153
PropertyTagSMinSampleValue | 0x0154
PropertyTagSMaxSampleValue | 0x0155
PropertyTagTransferRange | 0x0156
PropertyTagJPEGProc | 0x0200
PropertyTagJPEGInterFormat | 0x0201
PropertyTagJPEGInterLength | 0x0202
PropertyTagJPEGRestartInterval | 0x0203
PropertyTagJPEGLosslessPredictors | 0x0205
PropertyTagJPEGPointTransforms | 0x0206
PropertyTagJPEGQTables | 0x0207
PropertyTagJPEGDCTables | 0x0208
PropertyTagJPEGACTables | 0x0209
PropertyTagYCbCrCoefficients | 0x0211
PropertyTagYCbCrSubsampling | 0x0212
PropertyTagYCbCrPositioning | 0x0213
PropertyTagREFBlackWhite | 0x0214
PropertyTagGamma | 0x0301
PropertyTagICCProfileDescriptor | 0x0302
PropertyTagSRGBRenderingIntent | 0x0303
PropertyTagImageTitle | 0x0320
PropertyTagResolutionXUnit | 0x5001
PropertyTagResolutionYUnit | 0x5002
PropertyTagResolutionXLengthUnit | 0x5003
PropertyTagResolutionYLengthUnit | 0x5004
PropertyTagPrintFlags | 0x5005
PropertyTagPrintFlagsVersion | 0x5006
PropertyTagPrintFlagsCrop | 0x5007
PropertyTagPrintFlagsBleedWidth | 0x5008
PropertyTagPrintFlagsBleedWidthScale | 0x5009
PropertyTagHalftoneLPI | 0x500A
PropertyTagHalftoneLPIUnit | 0x500B
PropertyTagHalftoneDegree | 0x500C
PropertyTagHalftoneShape | 0x500D
PropertyTagHalftoneMisc | 0x500E
PropertyTagHalftoneScreen | 0x500F
PropertyTagJPEGQuality | 0x5010
PropertyTagGridSize | 0x5011
PropertyTagThumbnailFormat | 0x5012
PropertyTagThumbnailWidth | 0x5013
PropertyTagThumbnailHeight | 0x5014
PropertyTagThumbnailColorDepth | 0x5015
PropertyTagThumbnailPlanes | 0x5016
PropertyTagThumbnailRawBytes | 0x5017
PropertyTagThumbnailSize | 0x5018
PropertyTagThumbnailCompressedSize | 0x5019
PropertyTagColorTransferFunction | 0x501A
PropertyTagThumbnailData | 0x501B
PropertyTagThumbnailImageWidth | 0x5020
PropertyTagThumbnailImageHeight | 0x5021
PropertyTagThumbnailBitsPerSample | 0x5022
PropertyTagThumbnailCompression | 0x5023
PropertyTagThumbnailPhotometricInterp | 0x5024
PropertyTagThumbnailImageDescription | 0x5025
PropertyTagThumbnailEquipMake | 0x5026
PropertyTagThumbnailEquipModel | 0x5027
PropertyTagThumbnailStripOffsets | 0x5028
PropertyTagThumbnailOrientation | 0x5029
PropertyTagThumbnailSamplesPerPixel | 0x502A
PropertyTagThumbnailRowsPerStrip | 0x502B
PropertyTagThumbnailStripBytesCount | 0x502C
PropertyTagThumbnailResolutionX | 0x502D
PropertyTagThumbnailResolutionY | 0x502E
PropertyTagThumbnailPlanarConfig | 0x502F
PropertyTagThumbnailResolutionUnit | 0x5030
PropertyTagThumbnailTransferFunction | 0x5031
PropertyTagThumbnailSoftwareUsed | 0x5032
PropertyTagThumbnailDateTime | 0x5033
PropertyTagThumbnailArtist | 0x5034
PropertyTagThumbnailWhitePoint | 0x5035
PropertyTagThumbnailPrimaryChromaticities | 0x5036
PropertyTagThumbnailYCbCrCoefficients | 0x5037
PropertyTagThumbnailYCbCrSubsampling | 0x5038
PropertyTagThumbnailYCbCrPositioning | 0x5039
PropertyTagThumbnailRefBlackWhite | 0x503A
PropertyTagThumbnailCopyRight | 0x503B
PropertyTagLuminanceTable | 0x5090
PropertyTagChrominanceTable | 0x5091
PropertyTagFrameDelay | 0x5100
PropertyTagLoopCount | 0x5101
PropertyTagPixelUnit | 0x5110
PropertyTagPixelPerUnitX | 0x5111
PropertyTagPixelPerUnitY | 0x5112
PropertyTagPaletteHistogram | 0x5113
PropertyTagCopyright | 0x8298
PropertyTagExifExposureTime | 0x829A
PropertyTagExifFNumber | 0x829D
PropertyTagExifIFD | 0x8769
PropertyTagICCProfile | 0x8773
PropertyTagExifExposureProg | 0x8822
PropertyTagExifSpectralSense | 0x8824
PropertyTagGpsIFD | 0x8825
PropertyTagExifISOSpeed | 0x8827
PropertyTagExifOECF | 0x8828
PropertyTagExifVer | 0x9000
PropertyTagExifDTOrig | 0x9003
PropertyTagExifDTDigitized | 0x9004
PropertyTagExifCompConfig | 0x9101
PropertyTagExifCompBPP | 0x9102
PropertyTagExifShutterSpeed | 0x9201
PropertyTagExifAperture | 0x9202
PropertyTagExifBrightness | 0x9203
PropertyTagExifExposureBias | 0x9204
PropertyTagExifMaxAperture | 0x9205
PropertyTagExifSubjectDist | 0x9206
PropertyTagExifMeteringMode | 0x9207
PropertyTagExifLightSource | 0x9208
PropertyTagExifFlash | 0x9209
PropertyTagExifFocalLength | 0x920A
PropertyTagExifMakerNote | 0x927C
PropertyTagExifUserComment | 0x9286
PropertyTagExifDTSubsec | 0x9290
PropertyTagExifDTOrigSS | 0x9291
PropertyTagExifDTDigSS | 0x9292
PropertyTagExifFPXVer | 0xA000
PropertyTagExifColorSpace | 0xA001
PropertyTagExifPixXDim | 0xA002
PropertyTagExifPixYDim | 0xA003
PropertyTagExifRelatedWav | 0xA004
PropertyTagExifInterop | 0xA005
PropertyTagExifFlashEnergy | 0xA20B
PropertyTagExifSpatialFR | 0xA20C
PropertyTagExifFocalXRes | 0xA20E
PropertyTagExifFocalYRes | 0xA20F
PropertyTagExifFocalResUnit | 0xA210
PropertyTagExifSubjectLoc | 0xA214
PropertyTagExifExposureIndex | 0xA215
PropertyTagExifSensingMethod | 0xA217
PropertyTagExifFileSource | 0xA300
PropertyTagExifSceneType | 0xA301
PropertyTagExifCfaPattern | 0xA302

See Also

Reference
Image Property Tag Constants, Image Property Tag Type Constants, Property Item Descriptions, Property Tags in Alphabetical Order
Tasks and Examples
Reading and Writing Metadata


Property Tags in Alphabetical Order

The following table lists the GDI+ image property tags in alphabetical order.

Property tag | Value
PropertyTagArtist | 0x013B
PropertyTagBitsPerSample | 0x0102
PropertyTagCellHeight | 0x0109
PropertyTagCellWidth | 0x0108
PropertyTagChrominanceTable | 0x5091
PropertyTagColorMap | 0x0140
PropertyTagColorTransferFunction | 0x501A
PropertyTagCompression | 0x0103
PropertyTagCopyright | 0x8298
PropertyTagDateTime | 0x0132
PropertyTagDocumentName | 0x010D
PropertyTagDotRange | 0x0150
PropertyTagEquipMake | 0x010F
PropertyTagEquipModel | 0x0110
PropertyTagExifAperture | 0x9202
PropertyTagExifBrightness | 0x9203
PropertyTagExifCfaPattern | 0xA302
PropertyTagExifColorSpace | 0xA001
PropertyTagExifCompBPP | 0x9102
PropertyTagExifCompConfig | 0x9101
PropertyTagExifDTDigitized | 0x9004
PropertyTagExifDTDigSS | 0x9292
PropertyTagExifDTOrig | 0x9003
PropertyTagExifDTOrigSS | 0x9291
PropertyTagExifDTSubsec | 0x9290
PropertyTagExifExposureBias | 0x9204
PropertyTagExifExposureIndex | 0xA215
PropertyTagExifExposureProg | 0x8822
PropertyTagExifExposureTime | 0x829A
PropertyTagExifFileSource | 0xA300
PropertyTagExifFlash | 0x9209
PropertyTagExifFlashEnergy | 0xA20B
PropertyTagExifFNumber | 0x829D
PropertyTagExifFocalLength | 0x920A
PropertyTagExifFocalResUnit | 0xA210
PropertyTagExifFocalXRes | 0xA20E
PropertyTagExifFocalYRes | 0xA20F
PropertyTagExifFPXVer | 0xA000
PropertyTagExifIFD | 0x8769
PropertyTagExifInterop | 0xA005
PropertyTagExifISOSpeed | 0x8827
PropertyTagExifLightSource | 0x9208
PropertyTagExifMakerNote | 0x927C
PropertyTagExifMaxAperture | 0x9205
PropertyTagExifMeteringMode | 0x9207
PropertyTagExifOECF | 0x8828
PropertyTagExifPixXDim | 0xA002
PropertyTagExifPixYDim | 0xA003
PropertyTagExifRelatedWav | 0xA004
PropertyTagExifSceneType | 0xA301
PropertyTagExifSensingMethod | 0xA217
PropertyTagExifShutterSpeed | 0x9201
PropertyTagExifSpatialFR | 0xA20C
PropertyTagExifSpectralSense | 0x8824
PropertyTagExifSubjectDist | 0x9206
PropertyTagExifSubjectLoc | 0xA214
PropertyTagExifUserComment | 0x9286
PropertyTagExifVer | 0x9000
PropertyTagExtraSamples | 0x0152
PropertyTagFillOrder | 0x010A
PropertyTagFrameDelay | 0x5100
PropertyTagFreeByteCounts | 0x0121
PropertyTagFreeOffset | 0x0120
PropertyTagGamma | 0x0301
PropertyTagGpsAltitude | 0x0006
PropertyTagGpsAltitudeRef | 0x0005
PropertyTagGpsDestBear | 0x0018
PropertyTagGpsDestBearRef | 0x0017
PropertyTagGpsDestDist | 0x001A
PropertyTagGpsDestDistRef | 0x0019
PropertyTagGpsDestLat | 0x0014
PropertyTagGpsDestLatRef | 0x0013
PropertyTagGpsDestLong | 0x0016
PropertyTagGpsDestLongRef | 0x0015
PropertyTagGpsGpsDop | 0x000B
PropertyTagGpsGpsMeasureMode | 0x000A
PropertyTagGpsGpsSatellites | 0x0008
PropertyTagGpsGpsStatus | 0x0009
PropertyTagGpsGpsTime | 0x0007
PropertyTagGpsIFD | 0x8825
PropertyTagGpsImgDir | 0x0011
PropertyTagGpsImgDirRef | 0x0010
PropertyTagGpsLatitude | 0x0002
PropertyTagGpsLatitudeRef | 0x0001
PropertyTagGpsLongitude | 0x0004
PropertyTagGpsLongitudeRef | 0x0003
PropertyTagGpsMapDatum | 0x0012
PropertyTagGpsSpeed | 0x000D
PropertyTagGpsSpeedRef | 0x000C
PropertyTagGpsTrack | 0x000F
PropertyTagGpsTrackRef | 0x000E
PropertyTagGpsVer | 0x0000
PropertyTagGrayResponseCurve | 0x0123
PropertyTagGrayResponseUnit | 0x0122
PropertyTagGridSize | 0x5011
PropertyTagHalftoneDegree | 0x500C
PropertyTagHalftoneHints | 0x0141
PropertyTagHalftoneLPI | 0x500A
PropertyTagHalftoneLPIUnit | 0x500B
PropertyTagHalftoneMisc | 0x500E
PropertyTagHalftoneScreen | 0x500F
PropertyTagHalftoneShape | 0x500D
PropertyTagHostComputer | 0x013C
PropertyTagICCProfile | 0x8773
PropertyTagICCProfileDescriptor | 0x0302
PropertyTagImageDescription | 0x010E
PropertyTagImageHeight | 0x0101
PropertyTagImageTitle | 0x0320
PropertyTagImageWidth | 0x0100
PropertyTagInkNames | 0x014D
PropertyTagInkSet | 0x014C
PropertyTagJPEGACTables | 0x0209
PropertyTagJPEGDCTables | 0x0208
PropertyTagJPEGInterFormat | 0x0201
PropertyTagJPEGInterLength | 0x0202
PropertyTagJPEGLosslessPredictors | 0x0205
PropertyTagJPEGPointTransforms | 0x0206
PropertyTagJPEGProc | 0x0200
PropertyTagJPEGQTables | 0x0207
PropertyTagJPEGQuality | 0x5010
PropertyTagJPEGRestartInterval | 0x0203
PropertyTagLoopCount | 0x5101
PropertyTagLuminanceTable | 0x5090
PropertyTagMaxSampleValue | 0x0119
PropertyTagMinSampleValue | 0x0118
PropertyTagNewSubfileType | 0x00FE
PropertyTagNumberOfInks | 0x014E
PropertyTagOrientation | 0x0112
PropertyTagPageName | 0x011D
PropertyTagPageNumber | 0x0129
PropertyTagPaletteHistogram | 0x5113
PropertyTagPhotometricInterp | 0x0106
PropertyTagPixelPerUnitX | 0x5111
PropertyTagPixelPerUnitY | 0x5112
PropertyTagPixelUnit | 0x5110
PropertyTagPlanarConfig | 0x011C
PropertyTagPredictor | 0x013D
PropertyTagPrimaryChromaticities | 0x013F
PropertyTagPrintFlags | 0x5005
PropertyTagPrintFlagsBleedWidth | 0x5008
PropertyTagPrintFlagsBleedWidthScale | 0x5009
PropertyTagPrintFlagsCrop | 0x5007
PropertyTagPrintFlagsVersion | 0x5006
PropertyTagREFBlackWhite | 0x0214
PropertyTagResolutionUnit | 0x0128
PropertyTagResolutionXLengthUnit | 0x5003
PropertyTagResolutionXUnit | 0x5001
PropertyTagResolutionYLengthUnit | 0x5004
PropertyTagResolutionYUnit | 0x5002
PropertyTagRowsPerStrip | 0x0116
PropertyTagSampleFormat | 0x0153
PropertyTagSamplesPerPixel | 0x0115
PropertyTagSMaxSampleValue | 0x0155
PropertyTagSMinSampleValue | 0x0154
PropertyTagSoftwareUsed | 0x0131
PropertyTagSRGBRenderingIntent | 0x0303
PropertyTagStripBytesCount | 0x0117
PropertyTagStripOffsets | 0x0111
PropertyTagSubfileType | 0x00FF
PropertyTagT4Option | 0x0124
PropertyTagT6Option | 0x0125
PropertyTagTargetPrinter | 0x0151
PropertyTagThreshHolding | 0x0107
PropertyTagThumbnailArtist | 0x5034
PropertyTagThumbnailBitsPerSample | 0x5022
PropertyTagThumbnailColorDepth | 0x5015
PropertyTagThumbnailCompressedSize | 0x5019
PropertyTagThumbnailCompression | 0x5023
PropertyTagThumbnailCopyRight | 0x503B
PropertyTagThumbnailData | 0x501B
PropertyTagThumbnailDateTime | 0x5033
PropertyTagThumbnailEquipMake | 0x5026
PropertyTagThumbnailEquipModel | 0x5027
PropertyTagThumbnailFormat | 0x5012
PropertyTagThumbnailHeight | 0x5014
PropertyTagThumbnailImageDescription | 0x5025
PropertyTagThumbnailImageHeight | 0x5021
PropertyTagThumbnailImageWidth | 0x5020
PropertyTagThumbnailOrientation | 0x5029
PropertyTagThumbnailPhotometricInterp | 0x5024
PropertyTagThumbnailPlanarConfig | 0x502F
PropertyTagThumbnailPlanes | 0x5016
PropertyTagThumbnailPrimaryChromaticities | 0x5036
PropertyTagThumbnailRawBytes | 0x5017
PropertyTagThumbnailRefBlackWhite | 0x503A
PropertyTagThumbnailResolutionUnit | 0x5030
PropertyTagThumbnailResolutionX | 0x502D
PropertyTagThumbnailResolutionY | 0x502E
PropertyTagThumbnailRowsPerStrip | 0x502B
PropertyTagThumbnailSamplesPerPixel | 0x502A
PropertyTagThumbnailSize | 0x5018
PropertyTagThumbnailSoftwareUsed | 0x5032
PropertyTagThumbnailStripBytesCount | 0x502C
PropertyTagThumbnailStripOffsets | 0x5028
PropertyTagThumbnailTransferFunction | 0x5031
PropertyTagThumbnailWhitePoint | 0x5035
PropertyTagThumbnailWidth | 0x5013
PropertyTagThumbnailYCbCrCoefficients | 0x5037
PropertyTagThumbnailYCbCrPositioning | 0x5039
PropertyTagThumbnailYCbCrSubsampling | 0x5038
PropertyTagTileByteCounts | 0x0145
PropertyTagTileLength | 0x0143
PropertyTagTileOffset | 0x0144
PropertyTagTileWidth | 0x0142
PropertyTagTransferFunction | 0x012D
PropertyTagTransferRange | 0x0156
PropertyTagWhitePoint | 0x013E
PropertyTagXPosition | 0x011E
PropertyTagXResolution | 0x011A
PropertyTagYCbCrCoefficients | 0x0211
PropertyTagYCbCrPositioning | 0x0213
PropertyTagYCbCrSubsampling | 0x0212
PropertyTagYPosition | 0x011F
PropertyTagYResolution | 0x011B

See Also

Reference
Image Property Tag Constants, Image Property Tag Type Constants, Property Item Descriptions, Property Tags in Numerical Order
Tasks and Examples
Reading and Writing Metadata


Property Item Descriptions

The following list gives descriptions of the property items supported by GDI+. The descriptions are brief and general so that they apply to a variety of image file formats. For a detailed description of how a property item is used by a particular file format, see the specification for that file format. For links to several file specifications and other documents that describe metadata in detail, see Image File Format Specifications.

The Exchangeable Image File (Exif) Format is a Japan Electronic Industry Development Association (JEIDA) standard, revised June 1998 as version 2.1. Portions of the Exif specification are used with permission of JEIDA.

PropertyTagGpsVer

Version of the GPS IFD, given as 2.0.0.0. This tag is mandatory when the PropertyTagGpsIFD tag is present. When the version is 2.0.0.0, the tag value is 0x02000000.

Tag | 0x0000
Type | PropertyTagTypeByte
Count | 4

PropertyTagGpsLatitudeRef

Null-terminated character string that specifies whether the latitude is north or south latitude. N specifies north latitude, and S specifies south latitude.

Tag | 0x0001
Type | PropertyTagTypeASCII
Count | 2 (one character plus the NULL terminator)

PropertyTagGpsLatitude

Latitude. Latitude is expressed as three rational values giving the degrees, minutes, and seconds, respectively. When degrees, minutes and seconds are expressed, the format is dd/1, mm/1, ss/1. When degrees and minutes are used and, for example, fractions of minutes are given up to two decimal places, the format is dd/1, mmmm/100, 0/1.

Tag | 0x0002
Type | PropertyTagTypeRational
Count | 3

PropertyTagGpsLongitudeRef

Null-terminated character string that specifies whether the longitude is east or west longitude. E specifies east longitude, and W specifies west longitude.

Tag | 0x0003
Type | PropertyTagTypeASCII
Count | 2 (one character plus the NULL terminator)

PropertyTagGpsLongitude

Longitude. Longitude is expressed as three rational values giving the degrees, minutes, and seconds, respectively. When degrees, minutes and seconds are expressed, the format is ddd/1, mm/1, ss/1. When degrees and minutes are used and, for example, fractions of minutes are given up to two decimal places, the format is ddd/1, mmmm/100, 0/1.

Tag | 0x0004
Type | PropertyTagTypeRational
Count | 3

PropertyTagGpsAltitudeRef

Reference altitude, in meters.

Tag | 0x0005
Type | PropertyTagTypeByte
Count | 1

PropertyTagGpsAltitude

Altitude, in meters, based on the reference altitude specified by PropertyTagGpsAltitudeRef.

Tag | 0x0006
Type | PropertyTagTypeRational
Count | 1

PropertyTagGpsGpsTime

Time as UTC (Coordinated Universal Time). The value is expressed as three rational numbers that give the hour, minute, and second.

Tag | 0x0007
Type | PropertyTagTypeRational
Count | 3

PropertyTagGpsGpsSatellites

Null-terminated character string that specifies the GPS satellites used for measurements. This tag can be used to specify the ID number, angle of elevation, azimuth, SNR, and other information about each satellite. The format is not specified. If the GPS receiver is incapable of taking measurements, the value of the tag must be set to NULL.

Tag | 0x0008
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagGpsGpsStatus

Null-terminated character string that specifies the status of the GPS receiver when the image is recorded. A means measurement is in progress, and V means the measurement is Interoperability.

Tag | 0x0009
Type | PropertyTagTypeASCII
Count | 2 (one character plus the NULL terminator)

PropertyTagGpsGpsMeasureMode

Null-terminated character string that specifies the GPS measurement mode. 2 specifies two-dimensional measurement, and 3 specifies three-dimensional measurement.

Tag | 0x000A
Type | PropertyTagTypeASCII
Count | 2 (one character plus the NULL terminator)

PropertyTagGpsGpsDop

GPS DOP (data degree of precision). An HDOP value is written during two-dimensional measurement, and a PDOP value is written during three-dimensional measurement.

Tag | 0x000B
Type | PropertyTagTypeRational
Count | 1

PropertyTagGpsSpeedRef

Null-terminated character string that specifies the unit used to express the GPS receiver speed of movement. K, M, and N represent kilometers per hour, miles per hour, and knots, respectively.

Tag | 0x000C
Type | PropertyTagTypeASCII
Count | 2 (one character plus the NULL terminator)

PropertyTagGpsSpeed

Speed of the GPS receiver movement.

Tag | 0x000D
Type | PropertyTagTypeRational
Count | 1

PropertyTagGpsTrackRef

Null-terminated character string that specifies the reference for giving the direction of GPS receiver movement. T specifies true direction, and M specifies magnetic direction.

Tag | 0x000E
Type | PropertyTagTypeASCII
Count | 2 (one character plus the NULL terminator)

PropertyTagGpsTrack

Direction of GPS receiver movement. The range of values is from 0.00 to 359.99.

Tag | 0x000F
Type | PropertyTagTypeRational
Count | 1

PropertyTagGpsImgDirRef

Null-terminated character string that specifies the reference for the direction of the image when it is captured. T specifies true direction, and M specifies magnetic direction.

Tag | 0x0010
Type | PropertyTagTypeASCII
Count | 2 (one character plus the NULL terminator)

PropertyTagGpsImgDir

Direction of the image when it was captured. The range of values is from 0.00 to 359.99.

Tag | 0x0011
Type | PropertyTagTypeRational
Count | 1

PropertyTagGpsMapDatum

Null-terminated character string that specifies geodetic survey data used by the GPS receiver. If the survey data is restricted to Japan, the value of this tag is TOKYO or WGS-84.

Tag | 0x0012
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagGpsDestLatRef

Null-terminated character string that specifies whether the latitude of the destination point is north or south latitude. N specifies north latitude, and S specifies south latitude.

Tag | 0x0013
Type | PropertyTagTypeASCII
Count | 2 (one character plus the NULL terminator)

PropertyTagGpsDestLat

Latitude of the destination point. The latitude is expressed as three rational values giving the degrees, minutes, and seconds, respectively. When degrees, minutes, and seconds are expressed, the format is dd/1, mm/1, ss/1. When degrees and minutes are used and, for example, fractions of minutes are given up to two decimal places, the format is dd/1, mmmm/100, 0/1.

Tag | 0x0014
Type | PropertyTagTypeRational
Count | 3

PropertyTagGpsDestLongRef

Null-terminated character string that specifies whether the longitude of the destination point is east or west longitude. E specifies east longitude, and W specifies west longitude.

Tag | 0x0015
Type | PropertyTagTypeASCII
Count | 2 (one character plus the NULL terminator)

PropertyTagGpsDestLong

Longitude of the destination point. The longitude is expressed as three rational values giving the degrees, minutes, and seconds, respectively. When degrees, minutes, and seconds are expressed, the format is ddd/1, mm/1, ss/1. When degrees and minutes are used and, for example, fractions of minutes are given up to two decimal places, the format is ddd/1, mmmm/100, 0/1.

Tag | 0x0016
Type | PropertyTagTypeRational
Count | 3

PropertyTagGpsDestBearRef

Null-terminated character string that specifies the reference used for giving the bearing to the destination point. T specifies true direction, and M specifies magnetic direction.

Tag | 0x0017
Type | PropertyTagTypeASCII
Count | 2 (one character plus the NULL terminator)

PropertyTagGpsDestBear

Bearing to the destination point. The range of values is from 0.00 to 359.99.

Tag | 0x0018
Type | PropertyTagTypeRational
Count | 1

PropertyTagGpsDestDistRef

Null-terminated character string that specifies the unit used to express the distance to the destination point. K, M, and N represent kilometers, miles, and knots, respectively.

Tag | 0x0019
Type | PropertyTagTypeASCII
Count | 2 (one character plus the NULL terminator)

PropertyTagGpsDestDist

Distance to the destination point.

Tag | 0x001A
Type | PropertyTagTypeRational
Count | 1

PropertyTagNewSubfileType

Type of data in a subfile.

Tag | 0x00FE
Type | PropertyTagTypeLong
Count | 1

PropertyTagSubfileType

Type of data in a subfile.

Tag | 0x00FF
Type | PropertyTagTypeShort
Count | 1

PropertyTagImageWidth

Number of pixels per row.

Tag | 0x0100
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | 1

PropertyTagImageHeight

Number of pixel rows.

Tag | 0x0101
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | 1

PropertyTagBitsPerSample

Number of bits per color component. See also PropertyTagSamplesPerPixel.

Tag | 0x0102
Type | PropertyTagTypeShort
Count | Number of samples (components) per pixel

PropertyTagCompression

Compression scheme used for the image data.

Tag | 0x0103
Type | PropertyTagTypeShort
Count | 1

PropertyTagPhotometricInterp

How pixel data will be interpreted.

Tag | 0x0106
Type | PropertyTagTypeShort
Count | 1

PropertyTagThreshHolding

Technique used to convert from gray pixels to black and white pixels.

Tag | 0x0107
Type | PropertyTagTypeShort
Count | 1

PropertyTagCellWidth

Width of the dithering or halftoning matrix.

Tag | 0x0108
Type | PropertyTagTypeShort
Count | 1

PropertyTagCellHeight

Height of the dithering or halftoning matrix.

Tag | 0x0109
Type | PropertyTagTypeShort
Count | 1

PropertyTagFillOrder

Logical order of bits in a byte.

Tag | 0x010A
Type | PropertyTagTypeShort
Count | 1

PropertyTagDocumentName

Null-terminated character string that specifies the name of the document from which the image was scanned.

Tag | 0x010D
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagImageDescription

Null-terminated character string that specifies the title of the image.

Tag | 0x010E
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagEquipMake

Null-terminated character string that specifies the manufacturer of the equipment used to record the image.

Tag | 0x010F
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagEquipModel

Null-terminated character string that specifies the model name or model number of the equipment used to record the image.

Tag | 0x0110
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagStripOffsets

For each strip, the byte offset of that strip. See also PropertyTagRowsPerStrip and PropertyTagStripBytesCount.

Tag | 0x0111
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | Number of strips

PropertyTagOrientation

Image orientation viewed in terms of rows and columns.

Tag | 0x0112
Type | PropertyTagTypeShort
Count | 1
1 – The 0th row is at the visual top of the image, and the 0th column is the visual left side. 2 – The 0th row is at the visual top of the image, and the 0th column is the visual right side. 3 – The 0th row is at the visual bottom of the image, and the 0th column is the visual right side. 4 – The 0th row is at the visual bottom of the image, and the 0th column is the visual left side. 5 – The 0th row is the visual left side of the image, and the 0th column is the visual top. 6 – The 0th row is the visual right side of the image, and the 0th column is the visual top. 7 – The 0th row is the visual right side of the image, and the 0th column is the visual bottom. 8 – The 0th row is the visual left side of the image, and the 0th column is the visual bottom.

PropertyTagSamplesPerPixel

Number of color components per pixel.

Tag | 0x0115
Type | PropertyTagTypeShort
Count | 1

PropertyTagRowsPerStrip

Number of rows per strip. See also PropertyTagStripBytesCount and PropertyTagStripOffsets.

Tag | 0x0116
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | 1

PropertyTagStripBytesCount

For each strip, the total number of bytes in that strip.

Tag | 0x0117
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | Number of strips

PropertyTagMinSampleValue

For each color component, the minimum value assigned to that component. See also PropertyTagSamplesPerPixel.

Tag | 0x0118
Type | PropertyTagTypeShort
Count | Number of samples (components) per pixel

PropertyTagMaxSampleValue

For each color component, the maximum value assigned to that component. See also PropertyTagSamplesPerPixel.

Tag | 0x0119
Type | PropertyTagTypeShort
Count | Number of samples (components) per pixel

PropertyTagXResolution

Number of pixels per unit in the image width (x) direction. The unit is specified by PropertyTagResolutionUnit.

Tag | 0x011A
Type | PropertyTagTypeRational
Count | 1

PropertyTagYResolution

Number of pixels per unit in the image height (y) direction. The unit is specified by PropertyTagResolutionUnit.

Tag | 0x011B
Type | PropertyTagTypeRational
Count | 1

PropertyTagPlanarConfig

Whether pixel components are recorded in chunky or planar format.

Tag | 0x011C
Type | PropertyTagTypeShort
Count | 1

PropertyTagPageName

Null-terminated character string that specifies the name of the page from which the image was scanned.

Tag | 0x011D
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagXPosition

Offset from the left side of the page to the left side of the image. The unit of measure is specified by PropertyTagResolutionUnit.

Tag | 0x011E
Type | PropertyTagTypeRational
Count | 1

PropertyTagYPosition

Offset from the top of the page to the top of the image. The unit of measure is specified by PropertyTagResolutionUnit.

Tag | 0x011F
Type | PropertyTagTypeRational
Count | 1

PropertyTagFreeOffset

For each string of contiguous unused bytes, the byte offset of that string.

Tag | 0x0120
Type | PropertyTagTypeLong

PropertyTagFreeByteCounts

For each string of contiguous unused bytes, the number of bytes in that string.

Tag | 0x0121
Type | PropertyTagTypeLong
Count | Number of strings of contiguous unused bytes.

PropertyTagGrayResponseUnit

Precision of the number specified by PropertyTagGrayResponseCurve. 1 specifies tenths, 2 specifies hundredths, 3 specifies thousandths, and so on.

Tag | 0x0122
Type | PropertyTagTypeShort
Count | 1

PropertyTagGrayResponseCurve

For each possible pixel value in a grayscale image, the optical density of that pixel value.

Tag | 0x0123
Type | PropertyTagTypeShort
Count | Number of possible pixel values

PropertyTagT4Option

Set of flags that relate to T4 encoding.

Tag | 0x0124
Type | PropertyTagTypeLong
Count | 1

PropertyTagT6Option

Set of flags that relate to T6 encoding.

Tag | 0x0125
Type | PropertyTagTypeLong
Count | 1

PropertyTagResolutionUnit

Unit of measure for the horizontal resolution and the vertical resolution.

Tag | 0x0128
Type | PropertyTagTypeShort
Count | 1
2 – inch 3 – centimeter

PropertyTagPageNumber

Page number of the page from which the image was scanned.

Tag | 0x0129
Type | PropertyTagTypeShort
Count | 1

PropertyTagTransferFunction

Tables that specify transfer functions for the image.

Tag | 0x012D
Type | PropertyTagTypeShort
Count | Total number of 16-bit words required for the tables

PropertyTagSoftwareUsed

Null-terminated character string that specifies the name and version of the software or firmware of the device used to generate the image.

Tag | 0x0131
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagDateTime

Date and time the image was created.

Tag | 0x0132
Type | PropertyTagTypeASCII
Count | 20

PropertyTagArtist

Null-terminated character string that specifies the name of the person who created the image.

Tag | 0x013B
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagHostComputer

Null-terminated character string that specifies the computer and/or operating system used to create the image.

Tag | 0x013C
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagPredictor

Type of prediction scheme that was applied to the image data before the encoding scheme was applied.

Tag | 0x013D
Type | PropertyTagTypeShort
Count | 1

PropertyTagWhitePoint

Chromaticity of the white point of the image.

Tag | 0x013E
Type | PropertyTagTypeRational
Count | 2

PropertyTagPrimaryChromaticities

For each of the three primary colors in the image, the chromaticity of that color.

Tag | 0x013F
Type | PropertyTagTypeRational
Count | 6

PropertyTagColorMap

Color palette (lookup table) for a palette-indexed image.

Tag | 0x0140
Type | PropertyTagTypeShort
Count | Number of 16-bit words required for the palette

PropertyTagHalftoneHints

Information used by the halftone function

Tag | 0x0141
Type | PropertyTagTypeShort
Count | 2

PropertyTagTileWidth

Number of pixel columns in each tile.

Tag | 0x0142
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | 1

PropertyTagTileLength

Number of pixel rows in each tile.

Tag | 0x0143
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | 1

PropertyTagTileOffset

For each tile, the byte offset of that tile.

Tag | 0x0144
Type | PropertyTagTypeLong
Count | Number of tiles

PropertyTagTileByteCounts

For each tile, the number of bytes in that tile.

Tag | 0x0145
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | Number of tiles

PropertyTagInkSet

Set of inks used in a separated image.

Tag | 0x014C
Type | PropertyTagTypeShort
Count | 1

PropertyTagInkNames

Sequence of concatenated, null-terminated, character strings that specify the names of the inks used in a separated image.

Tag | 0x014D
Type | PropertyTagTypeASCII
Count | Total length of the sequence of strings including the NULL terminators

PropertyTagNumberOfInks

Number of inks.

Tag | 0x014E
Type | PropertyTagTypeShort
Count | 1

PropertyTagDotRange

Color component values that correspond to a 0 percent dot and a 100 percent dot.

Tag | 0x0150
Type | PropertyTagTypeByte or PropertyTagTypeShort
Count | 2 or 2×PropertyTagSamplesPerPixel

PropertyTagTargetPrinter

Null-terminated character string that describes the intended printing environment.

Tag | 0x0151
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagExtraSamples

Number of extra color components. For example, one extra component might hold an alpha value.

Tag | 0x0152
Type | PropertyTagTypeShort
Count | 1

PropertyTagSampleFormat

For each color component, the numerical format (unsigned, signed, floating point) of that component. See also PropertyTagSamplesPerPixel.

Tag | 0x0153
Type | PropertyTagTypeShort
Count | Number of samples (components) per pixel

PropertyTagSMinSampleValue

For each color component, the minimum value of that component. See also PropertyTagSamplesPerPixel.

Tag | 0x0154
Type | The type that best matches the pixel component data
Count | Number of samples (components) per pixel

PropertyTagSMaxSampleValue

For each color component, the maximum value of that component. See also PropertyTagSamplesPerPixel.

Tag | 0x0155
Type | The type that best matches the pixel component data
Count | Number of samples (components) per pixel

PropertyTagTransferRange

Table of values that extends the range of the transfer function.

Tag | 0x0156
Type | PropertyTagTypeShort
Count | 6

PropertyTagJPEGProc

JPEG compression process.

Tag | 0x0200
Type | PropertyTagTypeShort
Count | 1

PropertyTagJPEGInterFormat

Offset to the start of a JPEG bitstream.

Tag | 0x0201
Type | PropertyTagTypeLong
Count | 1

PropertyTagJPEGInterLength

Length, in bytes, of the JPEG bitstream.

Tag | 0x0202
Type | PropertyTagTypeLong
Count | 1

PropertyTagJPEGRestartInterval

Length of the restart interval.

Tag | 0x0203
Type | PropertyTagTypeShort
Count | 1

PropertyTagJPEGLosslessPredictors

For each color component, a lossless predictor-selection value for that component. See also PropertyTagSamplesPerPixel.

Tag | 0x0205
Type | PropertyTagTypeShort
Count | Number of samples (components) per pixel

PropertyTagJPEGPointTransforms

For each color component, a point transformation value for that component. See also PropertyTagSamplesPerPixel.

Tag | 0x0206
Type | PropertyTagTypeShort
Count | Number of samples (components) per pixel

PropertyTagJPEGQTables

For each color component, the offset to the quantization table for that component. See also PropertyTagSamplesPerPixel.

Tag | 0x0207
Type | PropertyTagTypeLong
Count | Number of samples (components) per pixel

PropertyTagJPEGDCTables

For each color component, the offset to the DC Huffman table (or lossles Huffman table) for that component. See also PropertyTagSamplesPerPixel.

Tag | 0x0208
Type | PropertyTagTypeLong
Count | Number of samples (components) per pixel

PropertyTagJPEGACTables

For each color component, the offset to the AC Huffman table for that component. See also PropertyTagSamplesPerPixel.

Tag | 0x0209
Type | PropertyTagTypeLong
Count | Number of samples (components) per pixel

PropertyTagYCbCrCoefficients

Coefficients for transformation from RGB to YCbCr image data.

Tag | 0x0211
Type | PropertyTagTypeRational
Count | 3

PropertyTagYCbCrSubsampling

Sampling ratio of chrominance components in relation to the luminance component.

Tag | 0x0212
Type | PropertyTagTypeShort
Count | 2

PropertyTagYCbCrPositioning

Position of chrominance components in relation to the luminance component.

Tag | 0x0213
Type | PropertyTagTypeShort
Count | 1

PropertyTagREFBlackWhite

Reference black point value and reference white point value.

Tag | 0x0214
Type | PropertyTagTypeRational
Count | 6

PropertyTagGamma

Gamma value attached to the image. The gamma value is stored as a rational number (pair of LONGs) with a numerator of 100000. For example, a gamma value of 2.2 is stored as the pair (100000, 45455).

Tag | 0x0301
Type | PropertyTagTypeRational
Count | 1

PropertyTagICCProfileDescriptor

Null-terminated character string that identifies an ICC profile.

Tag | 0x0302
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagSRGBRenderingIntent

How the image should be displayed as defined by the International Color Consortium (ICC). If a GDI+ Image object is constructed with the useEmbeddedColorManagement parameter set to TRUE, then GDI+ will render the image according to the specified rendering intent. The intent can be set to perceptual, relative colorimetric, saturation, or absolute colorimetric:

  • Perceptual intent, which is suitable for photographs, gives good adaptation to the display device gamut at the expense of colorimetric accuracy.
  • Relative colorimetric intent is suitable for images (for example, logos) that require color appearance matching that is relative to the display device white point.
  • Saturation intent, which is suitable for charts and graphs, preserves saturation at the expense of hue and lightness.
  • Absolute colorimetric intent is suitable for proofs (previews of images destined for a different display device) that require preservation of absolute colorimetry.
Tag | 0x0303
Type | BYTE
Count | 1
0 – perceptual 1 – relative colorimetric 2 – saturation 3 – absolute colorimetric

PropertyTagImageTitle

Null-terminated character string that specifies the title of the image.

Tag | 0x0320
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagResolutionXUnit

Units in which to display horizontal resolution.

Tag | 0x5001
Type | PropertyTagTypeShort
Count | 1
1 – pixels per inch 2 – pixels per centimeter

PropertyTagResolutionYUnit

Units in which to display vertical resolution.

Tag | 0x5002
Type | PropertyTagTypeShort
Count | 1
1 – pixels per inch 2 – pixels per centimeter

PropertyTagResolutionXLengthUnit

Units in which to display the image width.

Tag | 0x5003
Type | PropertyTagTypeShort
Count | 1
1 – inches 2 – centimeters 3 – points 4 – picas 5 – columns

PropertyTagResolutionYLengthUnit

Units in which to display the image height.

Tag | 0x5004
Type | PropertyTagTypeShort
Count | 1
1 – inches 2 – centimeters 3 – points 4 – picas 5 – columns

PropertyTagPrintFlags

Sequence of one-byte Boolean values that specify printing options.

Tag | 0x5005
Type | PropertyTagTypeASCII
Count | Number of flags

PropertyTagPrintFlagsVersion

Print flags version.

Tag | 0x5006
Type | PropertyTagTypeShort
Count | 1

PropertyTagPrintFlagsCrop

Print flags center crop marks.

Tag | 0x5007
Type | PropertyTagTypeByte
Count | 1

PropertyTagPrintFlagsBleedWidth

Print flags bleed width.

Tag | 0x5008
Type | PropertyTagTypeLong
Count | 1

PropertyTagPrintFlagsBleedWidthScale

Print flags bleed width scale.

Tag | 0x5009
Type | PropertyTagTypeShort
Count | 1

PropertyTagHalftoneLPI

Ink's screen frequency, in lines per inch.

Tag | 0x500A
Type | PropertyTagTypeRational
Count | 1

PropertyTagHalftoneLPIUnit

Units for the screen frequency.

Tag | 0x500B
Type | PropertyTagTypeShort
Count | 1
1 – lines per inch 2 – lines per centimeter

PropertyTagHalftoneDegree

Angle for screen.

Tag | 0x500C
Type | PropertyTagTypeRational
Count | 1

PropertyTagHalftoneShape

Shape of the halftone dots.

Tag | 0x500D
Type | PropertyTagTypeShort
Count | 1
0 – round 1 – ellipse 2 – line 3 – square 4 – cross 6 – diamond

PropertyTagHalftoneMisc

Miscellaneous halftone information.

Tag | 0x500E
Type | PropertyTagTypeLong
Count | 1

PropertyTagHalftoneScreen

Boolean value that specifies whether to use the printer's default screens.

Tag | 0x500F
Type | PropertyTagTypeByte
Count | 1
1 – use printer's default screens 2 – other

PropertyTagJPEGQuality

Private tag used by the Adobe Photoshop format. Not for public use.

Tag | 0x5010
Type | PropertyTagTypeShort
Count | Any

PropertyTagGridSize

Block of information about grids and guides.

Tag | 0x5011
Type | PropertyTagTypeUndefined
Count | Any

PropertyTagThumbnailFormat

Format of the thumbnail image.

Tag | 0x5012
Type | PropertyTagTypeLong
Count | 1
0 – raw RGB 1 – JPEG

PropertyTagThumbnailWidth

Width, in pixels, of the thumbnail image.

Tag | 0x5013
Type | PropertyTagTypeLong
Count | 1

PropertyTagThumbnailHeight

Height, in pixels, of the thumbnail image.

Tag | 0x5014
Type | PropertyTagTypeLong
Count | 1

PropertyTagThumbnailColorDepth

Bits per pixel for the thumbnail image.

Tag | 0x5015
Type | PropertyTagTypeShort
Count | 1

PropertyTagThumbnailPlanes

Number of color planes for the thumbnail image.

Tag | 0x5016
Type | PropertyTagTypeShort
Count | 1

PropertyTagThumbnailRawBytes

Byte offset between rows of pixel data.

Tag | 0x5017
Type | PropertyTagTypeLong
Count | 1

PropertyTagThumbnailSize

Total size, in bytes, of the thumbnail image.

Tag | 0x5018
Type | PropertyTagTypeLong
Count | 1

PropertyTagThumbnailCompressedSize

Compressed size, in bytes, of the thumbnail image.

Tag | 0x5019
Type | PropertyTagTypeLong
Count | 1

PropertyTagColorTransferFunction

Table of values that specify color transfer functions.

Tag | 0x501A
Type | PropertyTagTypeUndefined
Count | Any

PropertyTagThumbnailData

Raw thumbnail bits in JPEG or RGB format. Depends on PropertyTagThumbnailFormat.

Tag | 0x501B
Type | PropertyTagTypeByte
Count | Variable

PropertyTagThumbnailImageWidth

Number of pixels per row in the thumbnail image.

Tag | 0x5020
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | 1

PropertyTagThumbnailImageHeight

Number of pixel rows in the thumbnail image.

Tag | 0x5021
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | 1

PropertyTagThumbnailBitsPerSample

Number of bits per color component in the thumbnail image. See also PropertyTagThumbnailSamplesPerPixel.

Tag | 0x5022
Type | PropertyTagTypeShort
Count | Number of samples (components) per pixel in the thumbnail image

PropertyTagThumbnailCompression

Compression scheme used for thumbnail image data.

Tag | 0x5023
Type | PropertyTagTypeShort
Count | 1

PropertyTagThumbnailPhotometricInterp

How thumbnail pixel data will be interpreted.

Tag | 0x5024
Type | PropertyTagTypeShort
Count | 1

PropertyTagThumbnailImageDescription

Null-terminated character string that specifies the title of the image.

Tag | 0x5025
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagThumbnailEquipMake

Null-terminated character string that specifies the manufacturer of the equipment used to record the thumbnail image.

Tag | 0x5026
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagThumbnailEquipModel

Null-terminated character string that specifies the model name or model number of the equipment used to record the thumbnail image.

Tag | 0x5027
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagThumbnailStripOffsets

For each strip in the thumbnail image, the byte offset of that strip. See also PropertyTagThumbnailRowsPerStrip and PropertyTagThumbnailStripBytesCount.

Tag | 0x5028
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | Number of strips

PropertyTagThumbnailOrientation

Thumbnail image orientation in terms of rows and columns. See also PropertyTagOrientation.

Tag | 0x5029
Type | PropertyTagTypeShort
Count | 1

PropertyTagThumbnailSamplesPerPixel

Number of color components per pixel in the thumbnail image.

Tag | 0x502A
Type | PropertyTagTypeShort
Count | 1

PropertyTagThumbnailRowsPerStrip

Number of rows per strip in the thumbnail image. See also PropertyTagThumbnailStripBytesCount and PropertyTagThumbnailStripOffsets.

Tag | 0x502B
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | 1

PropertyTagThumbnailStripBytesCount

For each thumbnail image strip, the total number of bytes in that strip.

Tag | 0x502C
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | Number of strips in the thumbnail image

PropertyTagThumbnailResolutionX

Tag 0x502D

PropertyTagThumbnailResolutionY

Tag 0x502E

PropertyTagThumbnailPlanarConfig

Whether pixel components in the thumbnail image are recorded in chunky or planar format. See also PropertyTagPlanarConfig.

Tag | 0x502F
Type | PropertyTagTypeShort
Count | 1

PropertyTagThumbnailResolutionUnit

Unit of measure for the horizontal resolution and the vertical resolution of the thumbnail image. See also PropertyTagResolutionUnit.

Tag | 0x5030
Type | PropertyTagTypeShort
Count | 1

PropertyTagThumbnailTransferFunction

Tables that specify transfer functions for the thumbnail image. See also PropertyTagTransferFunction.

Tag | 0x5031
Type | PropertyTagTypeShort
Count | Total number of 16-bit words required for the tables

PropertyTagThumbnailSoftwareUsed

Null-terminated character string that specifies the name and version of the software or firmware of the device used to generate the thumbnail image.

Tag | 0x5032
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagThumbnailDateTime

Date and time the thumbnail image was created. See also PropertyTagDateTime.

Tag | 0x5033
Type | PropertyTagTypeASCII
Count | 20

PropertyTagThumbnailArtist

Null-terminated character string that specifies the name of the person who created the thumbnail image.

Tag | 0x5034
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagThumbnailWhitePoint

Chromaticity of the white point of the thumbnail image. See also PropertyTagWhitePoint.

Tag | 0x5035
Type | PropertyTagTypeRational
Count | 2

PropertyTagThumbnailPrimaryChromaticities

For each of the three primary colors in the thumbnail image, the chromaticity of that color. See also PropertyTagPrimaryChromaticities.

Tag | 0x5036
Type | PropertyTagTypeRational
Count | 6

PropertyTagThumbnailYCbCrCoefficients

Coefficients for transformation from RGB to YCbCr data for the thumbnail image. See also PropertyTagYCbCrCoefficients.

Tag | 0x5037
Type | PropertyTagTypeRational
Count | 3

PropertyTagThumbnailYCbCrSubsampling

Sampling ratio of chrominance components in relation to the luminance component for the thumbnail image. See also PropertyTagYCbCrSubsampling.

Tag | 0x5038
Type | PropertyTagTypeShort
Count | 2

PropertyTagThumbnailYCbCrPositioning

Position of chrominance components in relation to the luminance component for the thumbnail image. See also PropertyTagYCbCrPositioning.

Tag | 0x5039
Type | PropertyTagTypeShort
Count | 1

PropertyTagThumbnailRefBlackWhite

Reference black point value and reference white point value for the thumbnail image. See also PropertyTagREFBlackWhite.

Tag | 0x503A
Type | PropertyTagTypeRational
Count | 6

PropertyTagThumbnailCopyRight

Null-terminated character string that contains copyright information for the thumbnail image.

Tag | 0x503B
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagLuminanceTable

Luminance table. The luminance table and the chrominance table are used to control JPEG quality. A valid luminance or chrominance table has 64 entries of type PropertyTagTypeShort. If an image has either a luminance table or a chrominance table, then it must have both tables.

Tag | 0x5090
Type | PropertyTagTypeShort
Count | 64

PropertyTagChrominanceTable

Chrominance table. The luminance table and the chrominance table are used to control JPEG quality. A valid luminance or chrominance table has 64 entries of type PropertyTagTypeShort. If an image has either a luminance table or a chrominance table, then it must have both tables.

Tag | 0x5091
Type | PropertyTagTypeShort
Count | 64

PropertyTagFrameDelay

Time delay, in hundredths of a second, between two frames in an animated GIF image.

Tag | 0x5100
Type | PropertyTagTypeLong
Count | Number of frames in the image

PropertyTagLoopCount

For an animated GIF image, the number of times to display the animation. A value of 0 specifies that the animation should be displayed infinitely.

Tag | 0x5101
Type | PropertyTagTypeShort
Count | 1

PropertyTagPixelUnit

Unit for PropertyTagPixelPerUnitX and PropertyTagPixelPerUnitY.

Tag | 0x5110
Type | PropertyTagTypeByte
Count | 1
0 – unknown 1 – meters

PropertyTagPixelPerUnitX

Pixels per unit in the x direction.

Tag | 0x5111
Type | PropertyTagTypeLong
Count | 1

PropertyTagPixelPerUnitY

Pixels per unit in the y direction.

Tag | 0x5112
Type | PropertyTagTypeLong
Count | 1

PropertyTagPaletteHistogram

Palette histogram.

Tag | 0x5113
Type | PropertyTagTypeByte
Count | Length of the histogram

PropertyTagCopyright

Null-terminated character string that contains copyright information.

Tag | 0x8298
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagExifExposureTime

Exposure time, measured in seconds.

Tag | 0x829A
Type | PropertyTagTypeRational
Count | 1

PropertyTagExifFNumber

F number.

Tag | 0x829D
Type | RATIONAL
Count | 1

PropertyTagExifIFD

Private tag used by GDI+. Not for public use. GDI+ uses this tag to locate Exif-specific information.

Tag | 0x8769
Type | PropertyTagTypeLong
Count | 1

PropertyTagICCProfile

ICC profile embedded in the image.

Tag | 0x8773
Type | PropertyTagTypeByte
Count | Length of the profile

PropertyTagExifExposureProg

Class of the program used by the camera to set exposure when the picture is taken.

Tag | 0x8822
Type | SHORT
Count | 1
Default | 0
0 – not defined 1 – manual 2 – normal program 3 – aperture priority 4 – shutter priority 5 – creative program (biased toward depth of field) 6 – action program (biased toward fast shutter speed) 7 – portrait mode (for close-up photos with the background out of focus) 8 – landscape mode (for landscape photos with the background in focus) 9 to 255 – reserved

PropertyTagExifSpectralSense

Null-terminated character string that specifies the spectral sensitivity of each channel of the camera used. The string is compatible with the standard developed by the ASTM Technical Committee.

Tag | 0x8824
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagGpsIFD

Offset to a block of Global Positioning System (GPS) property items. Property items whose tags have the prefix PropertyTagGps are stored in the GPS block. The GPS property items are defined in the Exif specification. GDI+ uses this tag to locate GPS information, but GDI+ does not expose this tag for public use.

Tag | 0x8825
Type | PropertyTagTypeLong
Count | 1

PropertyTagExifISOSpeed

ISO speed and ISO latitude of the camera or input device as specified in ISO 12232.

Tag | 0x8827
Type | PropertyTagTypeShort
Count | Any

PropertyTagExifOECF

Optoelectronic conversion function (OECF) specified in ISO 14524. The OECF is the relationship between the camera optical input and the image values.

Tag | 0x8828
Type | PropertyTagTypeUndefined
Count | Any

PropertyTagExifVer

Version of the Exif standard supported. Nonexistence of this field is taken to mean nonconformance to the standard. Conformance to the standard is indicated by recording 0210 as a 4-byte ASCII string. Because the type is PropertyTagTypeUndefined, there is no NULL terminator.

Tag | 0x9000
Type | PropertyTagTypeUndefined
Count | 4
Default | 0210

PropertyTagExifDTOrig

Date and time when the original image data was generated. For a DSC, the date and time when the picture was taken. The format is YYYY:MM:DD HH:MM:SS with time shown in 24-hour format and the date and time separated by one blank character (0x2000). The character string length is 20 bytes including the NULL terminator. When the field is empty, it is treated as unknown.

Tag | 0x9003
Type | PropertyTagTypeASCII
Count | 20

PropertyTagExifDTDigitized

Date and time when the image was stored as digital data. If, for example, an image was captured by DSC and at the same time the file was recorded, then DateTimeOriginal and DateTimeDigitized will have the same contents.

The format is YYYY:MM:DD HH:MM:SS with time shown in 24-hour format and the date and time separated by one blank character (0x2000). The character string length is 20 bytes including the NULL terminator. When the field is empty, it is treated as unknown.

Tag | 0x9004
Type | PropertyTagTypeASCII
Count | 20

PropertyTagExifCompConfig

Information specific to compressed data. The channels of each component are arranged in order from the 1st component to the 4th. For uncompressed data, the data arrangement is given in the PropertyTagPhotometricInterp tag.

However, because PropertyTagPhotometricInterp can only express the order of Y, Cb, and Cr, this tag is provided for cases when compressed data uses components other than Y, Cb, and Cr and to support other sequences.

Tag | 0x9101
Type | PropertyTagTypeUndefined
Count | 4
Default | 4 5 6 0 (if RGB uncompressed) 1 2 3 0 (other cases)
0 – does not exist 1 – Y 2 – Cb 3 – Cr 4 – R 5 – G. 6 – B Other – reserved

PropertyTagExifCompBPP

Information specific to compressed data. The compression mode used for a compressed image is indicated in unit bits per pixel.

Tag | 0x9102
Type | PropertyTagTypeRational
Count | 1

PropertyTagExifShutterSpeed

Shutter speed. The unit is the Additive System of Photographic Exposure (APEX) value.

Tag | 0x9201
Type | PropertyTagTypeSRational
Count | 1

PropertyTagExifAperture

Lens aperture. The unit is the APEX value.

Tag | 0x9202
Type | PropertyTagTypeRational
Count | 1

PropertyTagExifBrightness

Brightness value. The unit is the APEX value. Ordinarily it is given in the range of –99.99 to 99.99.

Tag | 0x9203
Type | PropertyTagTypeSRational
Count | 1

PropertyTagExifExposureBias

Exposure bias. The unit is the APEX value. Ordinarily it is given in the range of –99.99 to 99.99.

Tag | 0x9204
Type | PropertyTagTypeSRational
Count | 1

PropertyTagExifMaxAperture

Smallest F number of the lens. The unit is the APEX value. Ordinarily it is given in the range of 00.00 to 99.99, but it is not limited to this range.

Tag | 0x9205
Type | PropertyTagTypeRational
Count | 1

PropertyTagExifSubjectDist

Distance to the subject, measured in meters.

Tag | 0x9206
Type | PropertyTagTypeRational
Count | 1

PropertyTagExifMeteringMode

Metering mode.

Tag | 0x9207
Type | PropertyTagTypeShort
Count | 1
Default | 0
0 – unknown 1 – Average 2 – CenterWeightedAverage 3 – Spot 4 – MultiSpot 5 – Pattern 6 – Partial 7 to 254 – reserved 255 – other

PropertyTagExifLightSource

Type of light source.

Tag | 0x9208
Type | PropertyTagTypeShort
Count | 1
Default | 0
0 – unknown 1 – Daylight 2 – Fluorescent 3 – Tungsten 17 – Standard light A 18 – Standard light B 19 – Standard light C 20 – D55 21 – D65 22 – D75 23 to 254 – reserved 255 – other

PropertyTagExifFlash

Flash status. This tag is recorded when an image is taken using a strobe light (flash). Bit 0 indicates the flash firing status, and bits 1 and 2 indicate the flash return status.

Tag | 0x9209
Type | PropertyTagTypeShort
Count | 1
Values for bit 0 that indicate whether the flash fired: 0b – flash did not fire 1b – flash fired
Values for bits 1 and 2 that indicate the status of returned light: 00b – no strobe return detection function 01b – reserved 10b – strobe return light not detected 11b – strobe return light detected
Resulting flash tag values: 0x0000 – flash did not fire 0x0001 – flash fired 0x0005 – strobe return light not detected

PropertyTagExifFocalLength

Actual focal length, in millimeters, of the lens. Conversion is not made to the focal length of a 35 millimeter film camera.

Tag | 0x920A
Type | PropertyTagTypeRational
Count | 1

PropertyTagExifMakerNote

Note tag. A tag used by manufacturers of Exif writers to record information. The contents are up to the manufacturer.

Tag | 0x927C
Type | PropertyTagTypeUndefined
Count | Any

PropertyTagExifUserComment

Comment tag. A tag used by Exif users to write keywords or comments about the image besides those in PropertyTagImageDescription and without the character-code limitations of the PropertyTagImageDescription tag.

Tag | 0x9286
Type | PropertyTagTypeUndefined
Count | Any

The character code used in the PropertyTagExifUserComment tag is identified based on an ID code in a fixed 8-byte area at the start of the tag data area. The unused portion of the area is padded with NULL (0). ID codes are assigned by means of registration. Because the type is not ASCII, it is not necessary to use a NULL terminator.

PropertyTagExifDTSubsec

Null-terminated character string that specifies a fraction of a second for the PropertyTagDateTime tag.

Tag | 0x9290
Type | PropertyTagTypeASCII
Count | Length of the string including the NULL terminator

PropertyTagExifDTOrigSS

Null-terminated character string that specifies a fraction of a second for the PropertyTagExifDTOrig tag.

Tag | 0x9291
Type | PropertyTagTypeASCII
N | Length of the string including the NULL terminator

PropertyTagExifDTDigSS

Null-terminated character string that specifies a fraction of a second for the PropertyTagExifDTDigitized tag.

Tag | 0x9292
Type | ASCII
N | Length of the string including the NULL terminator

PropertyTagExifFPXVer

FlashPix format version supported by an FPXR file. If the FPXR function supports FlashPix format version 1.0, this is indicated similarly to PropertyTagExifVer by recording 0100 as a 4-byte ASCII string. Because the type is PropertyTagTypeUndefined, there is no NULL terminator.

Tag | 0xA000
Type | PropertyTagTypeUndefined
Count | 4
Default | 0100
0100 – FlashPix format version 1.0 Other – reserved

PropertyTagExifColorSpace

Color space specifier. Normally sRGB (=1) is used to define the color space based on the PC monitor conditions and environment. If a color space other than sRGB is used, Uncalibrated (=0xFFFF) is set. Image data recorded as Uncalibrated can be treated as sRGB when it is converted to FlashPix.

Tag | 0xA001
Type | PropertyTagTypeShort
Count | 1
0x1 – sRGB 0xFFFF – uncalibrated Other – reserved

PropertyTagExifPixXDim

Information specific to compressed data. When a compressed file is recorded, the valid width of the meaningful image must be recorded in this tag, whether or not there is padding data or a restart marker. This tag should not exist in an uncompressed file.

Tag | 0xA002
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | 1

PropertyTagExifPixYDim

Information specific to compressed data. When a compressed file is recorded, the valid height of the meaningful image must be recorded in this tag whether or not there is padding data or a restart marker. This tag should not exist in an uncompressed file. Because data padding is unnecessary in the vertical direction, the number of lines recorded in this valid image height tag will be the same as that recorded in the SOF.

Tag | 0xA003
Type | PropertyTagTypeShort or PropertyTagTypeLong
Count | 1

PropertyTagExifRelatedWav

The name of an audio file related to the image data. The only relational information recorded is the Exif audio file name and extension (an ASCII string that consists of 8 characters plus a period (.), plus 3 characters). The path is not recorded. When you use this tag, audio files must be recorded in conformance with the Exif audio format. Writers can also store audio data within APP2 as FlashPix extension stream data.

Tag | 0xA004
Type | PropertyTagTypeASCII
Count | 13

PropertyTagExifInterop

Offset to a block of property items that contain interoperability information.

Tag | 0xA005
Type | PropertyTagTypeLong
Count | 1

PropertyTagExifFlashEnergy

Strobe energy, in Beam Candle Power Seconds (BCPS), at the time the image was captured.

Tag | 0xA20B
Type | PropertyTagTypeRational
Count | 1

PropertyTagExifSpatialFR

Camera or input device spatial frequency table and SFR values in the image width, image height, and diagonal direction, as specified in ISO 12233.

Tag | 0xA20C
Type | PropertyTagTypeUndefined
Count | Any

PropertyTagExifFocalXRes

Number of pixels in the image width (x) direction per unit on the camera focal plane. The unit is specified in PropertyTagExifFocalResUnit.

Tag | 0xA20E
Type | PropertyTagTypeRational
Count | 1

PropertyTagExifFocalYRes

Number of pixels in the image height (y) direction per unit on the camera focal plane. The unit is specified in PropertyTagExifFocalResUnit.

Tag | 0xA20F
Type | PropertyTagTypeRational
Count | 1

PropertyTagExifFocalResUnit

Unit of measure for PropertyTagExifFocalXRes and PropertyTagExifFocalYRes.

Tag | 0xA210
Type | PropertyTagTypeShort
Count | 1
2 – inch 3 – centimeter

PropertyTagExifSubjectLoc

Location of the main subject in the scene. The value of this tag represents the pixel at the center of the main subject relative to the left edge. The first value indicates the column number, and the second value indicates the row number.

Tag | 0xA214
Type | PropertyTagTypeShort
Count | 2

PropertyTagExifExposureIndex

Exposure index selected on the camera or input device at the time the image was captured.

Tag | 0xA215
Type | PropertyTagTypeRational
Count | 1

PropertyTagExifSensingMethod

Image sensor type on the camera or input device.

Tag | 0xA217
Type | PropertyTagTypeShort
Count | 1
1 – not defined 2 – one-chip color area sensor 3 – two-chip color area sensor 4 – three-chip color area sensor 5 – color sequential area sensor 7 – trilinear sensor 8 – color sequential linear sensor Other – reserved

PropertyTagExifFileSource

The image source. If a DSC recorded the image, the value of this tag is 3.

Tag | 0xA300
Type | PropertyTagTypeUndefined
Count | 1

PropertyTagExifSceneType

The type of scene. If a DSC recorded the image, the value of this tag must be set to 1, indicating that the image was directly photographed.

Tag | 0xA301
Type | PropertyTagTypeUndefined
Count | 1

PropertyTagExifCfaPattern

The color filter array (CFA) geometric pattern of the image sensor when a one-chip color area sensor is used. It does not apply to all sensing methods.

Tag | 0xA302
Type | PropertyTagTypeUndefined
Count | Any

See Also

Reference
Image File Format Specifications, Image Property Tag Constants, Image Property Tag Type Constants, Property Tags in Alphabetical Order, Property Tags in Numerical Order
Tasks and Examples
Reading and Writing Metadata


Image File Format Specifications

The following table lists several documents that give detailed descriptions of how metadata is stored in image files.

Document | Location
TIFF Specification | http://partners.adobe.com/asn/developer/pdfs/tn/TIFF6.pdf
Exif Specification | http://www.pima.net/standards/it10/PIMA15740/exif.htm
PNG Specification | http://www.w3.org/TR/REC-png.html
ISO/IEC 10918-1 (JPEG) | http://www.ansi.org/public/std_info.html
ICC.1:1998-09 | http://www.color.org/profiles.html
Photoshop File Formats Specification | http://partners.adobe.com/asn/developer/gapsdk/download/ps6ffspecsv2.pdf

See Also

Reference
Image Property Tag Constants, Image Property Tag Type Constants, Property Item Descriptions, Property Tags in Alphabetical Order, Property Tags in Numerical Order
Tasks and Examples
Reading and Writing Metadata


Enumerations

GDI+ defines the following enumerations:

  • BrushType
  • ColorAdjustType
  • ColorChannelFlags
  • ColorMatrixFlags
  • CombineMode
  • CompositingMode
  • CompositingQuality
  • CoordinateSpace
  • DashCap
  • DashStyle
  • DriverStringOptions
  • EmfPlusRecordType
  • EmfType
  • EncoderParameterValueType
  • EncoderValue
  • FillMode
  • FlushIntention
  • FontStyle
  • HatchStyle
  • HotkeyPrefix
  • ImageCodecFlags
  • ImageFlags
  • ImageLockMode
  • ImageType
  • InterpolationMode
  • LinearGradientMode
  • LineCap
  • LineJoin
  • MatrixOrder
  • MetafileFrameUnit
  • MetafileType
  • PaletteFlags
  • PathPointType
  • PenAlignment
  • PenType
  • PixelOffsetMode
  • RotateFlipType
  • SmoothingMode
  • Status
  • StringAlignment
  • StringDigitSubstitute
  • StringFormatFlags
  • StringTrimming
  • TextRenderingHint
  • Unit
  • WarpMode
  • WrapMode


BrushType

The BrushType enumeration indicates the type of brush. There are five types of brushes.

enum BrushType{
  BrushTypeSolidColor     = 0,
  BrushTypeHatchFill      = 1,
  BrushTypeTextureFill    = 2,
  BrushTypePathGradient   = 3,
  BrushTypeLinearGradient = 4
};

Elements

BrushTypeSolidColor
Indicates a brush of type SolidBrush. A solid brush paints a single, constant color that can be opaque or transparent.
BrushTypeHatchFill
Indicates a brush of type HatchBrush. A hatch brush paints a background and paints, over that background, a pattern of lines, dots, dashes, squares, crosshatch, or some variation of these. The hatch brush consists of two colors: one for the background and one for the pattern over the background. The color of the background is called the background color, and the color of the pattern is called the foreground color.
BrushTypeTextureFill
Indicates a brush of type TextureBrush. A texture brush paints an image. The image or texture is either a portion of a specified image or a scaled version of a specified image. The type of image (metafile or nonmetafile) determines whether the texture is a portion of the image or a scaled version of the image.
BrushTypePathGradient
Indicates a brush of type PathGradientBrush. A path gradient brush paints a color gradient in which the color changes from a center point outward to a boundary that is defined by a closed curve or path. The color gradient has one color at the center point and one or multiple colors at the boundary.
BrushTypeLinearGradient
Indicates a brush of type LinearGradientBrush. A linear gradient brush paints a color gradient in which the color changes evenly from the starting boundary line of the linear gradient brush to the ending boundary line of the linear gradient brush. The boundary lines of a linear gradient brush are two parallel straight lines. The color gradient is perpendicular to the boundary lines of the linear gradient brush, changing gradually across the stroke from the starting boundary line to the ending boundary line. The color gradient has one color at the starting boundary line and another color at the ending boundary line.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
HatchBrush, LinearGradientBrush, PathGradientBrush, SolidBrush, TextureBrush
Tasks and Examples
Using a Brush to Fill Shapes
Concepts
Brushes and Filled Shapes


ColorAdjustType

The ColorAdjustType enumeration specifies which GDI+ objects use color-adjustment information. You can adjust the colors in a rendered image by passing the address of an ImageAttributes object to the Graphics::DrawImage method. An ImageAttributes object maintains color and grayscale settings for five adjustment categories: default, bitmap, brush, pen, and text. Several of the methods of the ImageAttributes class receive an element of the ColorAdjustType enumeration to specify the adjustment category.

enum ColorAdjustType{
  ColorAdjustTypeDefault,
  ColorAdjustTypeBitmap,
  ColorAdjustTypeBrush,
  ColorAdjustTypePen,
  ColorAdjustTypeText,
  ColorAdjustTypeCount,
  ColorAdjustTypeAny
};

Elements

ColorAdjustTypeDefault
Specifies that color or grayscale adjustment applies to all categories that do not have adjustment settings of their own.
ColorAdjustTypeBitmap
Specifies that color or grayscale adjustment applies to bitmapped images.
ColorAdjustTypeBrush
Specifies that color or grayscale adjustment applies to brush operations in metafiles.
ColorAdjustTypePen
Specifies that color or grayscale adjustment applies to pen operations in metafiles.
ColorAdjustTypeText
Specifies that color or grayscale adjustment applies to text drawn in metafiles.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolormatrix.h; include Gdiplus.h.


ColorChannelFlags

The ColorChannelFlags enumeration specifies individual channels in the CMYK (cyan, magenta, yellow, black) color space. This enumeration is used by the ImageAttributes::SetOutputChannel method.

enum ColorChannelFlags{
  ColorChannelFlagsC = 0,
  ColorChannelFlagsM,
  ColorChannelFlagsY,
  ColorChannelFlagsK,
  ColorChannelFlagsLast
};

Elements

ColorChannelFlagsC
Specifies the cyan color channel.
ColorChannelFlagsM
Specifies the magenta color channel.
ColorChannelFlagsY
Specifies the yellow color channel.
ColorChannelFlagsK
Specifies the black color channel.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolor.h; include Gdiplus.h.


ColorMatrixFlags

The ColorMatrixFlags enumeration specifies the types of images and colors that will be affected by the color and grayscale adjustment settings of an ImageAttributes object.

enum ColorMatrixFlags{
  ColorMatrixFlagsDefault   = 0,
  ColorMatrixFlagsSkipGrays = 1,
  ColorMatrixFlagsAltGray   = 2
};

Elements

ColorMatrixFlagsDefault
Specifies that all color values (including grays) are adjusted by the same color-adjustment matrix.
ColorMatrixFlagsSkipGrays
Specifies that colors are adjusted but gray shades are not adjusted. A gray shade is any color that has the same value for its red, green, and blue components.
ColorMatrixFlagsAltGray
Specifies that colors are adjusted by one matrix and gray shades are adjusted by another matrix.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolormatrix.h; include Gdiplus.h.

See Also

Reference
ClearColorMatrices, ClearColorMatrix, SetColorMatrices, SetColorMatrix


CombineMode

The CombineMode enumeration specifies how a new region is combined with an existing region.

enum CombineMode{
  CombineModeReplace,
  CombineModeIntersect,
  CombineModeUnion,
  CombineModeXor,
  CombineModeExclude,
  CombineModeComplement
};

Elements

CombineModeReplace
Specifies that the existing region is replaced by the new region.
CombineModeIntersect
Specifies that the existing region is replaced by the intersection of itself and the new region.
CombineModeUnion
Specifies that the existing region is replaced by the union of itself and the new region.
CombineModeXor
Specifies that the existing region is replaced by the result of performing an XOR on the two regions. A point is in the XOR of two regions if it is in one region or the other but not in both regions.
CombineModeExclude
Specifies that the existing region is replaced by the portion of itself that is outside of the new region.
CombineModeComplement
Specifies that the existing region is replaced by the portion of the new region that is outside of the existing region.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


CompositingMode

The CompositingMode enumeration specifies how rendered colors are combined with background colors. This enumeration is used by the GetCompositingMode and SetCompositingMode methods of the Graphics class.

enum CompositingMode{
  CompositingModeSourceOver,
  CompositingModeSourceCopy
};

Elements

CompositingModeSourceOver
Specifies that when a color is rendered, it is blended with the background color. The blend is determined by the alpha component of the color being rendered.
CompositingModeSourceCopy
Specifies that when a color is rendered, it overwrites the background color. This mode cannot be used along with TextRenderingHintClearTypeGridFit.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
GetCompositingMode, SetCompositingMode, TextRenderingHint


CompositingQuality

The CompositingQuality enumeration specifies whether gamma correction is applied when colors are blended with background colors. This enumeration is used by the GetCompositingQuality and SetCompositingQuality methods of the Graphics class.

enum CompositingQuality{
  CompositingQualityInvalid  = QualityModeInvalid,
  CompositingQualityDefault  = QualityModeDefault,
  CompositingQualityHighSpeed   = QualityModeLow,
  CompositingQualityHighQuality = QualityModeHigh,
  CompositingQualityGammaCorrected,
  CompositingQualityAssumeLinear
};

Elements

CompositingQualityDefault
Specifies that gamma correction is not applied.
CompositingQualityHighSpeed
Specifies that gamma correction is not applied.
CompositingQualityHighQuality
Specifies that gamma correction is applied.
CompositingQualityGammaCorrected
Specifies that gamma correction is applied.
CompositingQualityAssumeLinear
Specifies that gamma correction is not applied.

Remarks

When you specify that gamma correction should not be applied, the image data to be rendered (blended with the background) is assumed to be in a linear color space with a gamma value of 1.0. As a result, no gamma adjustment is applied to the image data before or after blending the image with the background.

When you specify that gamma correction should be applied, the image data to be rendered (blended with the background) is assumed to be in the sRGB color space with a gamma value of 2.2. To ensure accurate blending, the input image data is transformed into a linear (gamma = 1.0) space before the colors are blended and transformed back into sRGB (gamma = 2.2) space afterwards. This mode results in a more accurate blend at the expense of additional processing time.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
GetCompositingQuality, SetCompositingQuality


CoordinateSpace

The CoordinateSpace enumeration specifies coordinate spaces. This enumeration is used by the Graphics::TransformPoints method, which converts points from one coordinate space to another. For more information about coordinate spaces, see Types of Coordinate Systems.

enum CoordinateSpace{
  CoordinateSpaceWorld,
  CoordinateSpacePage,
  CoordinateSpaceDevice
};

Elements

CoordinateSpaceWorld
Specifies the world coordinate space.
CoordinateSpacePage
Specifies the page coordinate space.
CoordinateSpaceDevice
Specifies the device coordinate space.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
TransformPoints


DashCap

The DashCap enumeration specifies the type of graphic shape to use on both ends of each dash in a dashed line.

enum DashCap{
  DashCapFlat = 0,
  DashCapRound = 2,
  DashCapTriangle = 3
};

Elements

DashCapFlat
Specifies a square cap that squares off both ends of each dash.
DashCapRound
Specifies a circular cap that rounds off both ends of each dash.
DashCapTriangle
Specifies a triangular cap that points both ends of each dash.

Remarks

If you set the alignment of a Pen object to PenAlignmentInset, you cannot use that pen to draw triangular dash caps.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


DashStyle

The DashStyle enumeration specifies the line style of a line drawn with a GDI+ pen. The line can be drawn by using one of several predefined styles or a custom style.

enum DashStyle{
  DashStyleSolid = 0,
  DashStyleDash = 1,
  DashStyleDot = 2,
  DashStyleDashDot = 3,
  DashStyleDashDotDot = 4,
  DashStyleCustom = 5
};

Elements

DashStyleSolid
Specifies a solid line.
DashStyleDash
Specifies a dashed line.
DashStyleDot
Specifies a dotted line.
DashStyleDashDot
Specifies an alternating dash-dot line.
DashStyleDashDotDot
Specifies an alternating dash-dot-dot line.
DashStyleCustom
Specifies a user-defined, custom dashed line.

Remarks

A custom dashed line is created by calling the Pen::SetDashPattern method which takes an array of values for the dash lengths and the space lengths.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


DriverStringOptions

The DriverStringOptions enumeration specifies the spacing, orientation, and quality of the rendering for driver strings.

enum DriverStringOptions{
  DriverStringOptionsCmapLookup      = 1,
  DriverStringOptionsVertical        = 2,
  DriverStringOptionsRealizedAdvance = 4,
  DriverStringOptionsLimitSubpixel   = 8
};

Elements

DriverStringOptionsCmapLookup
Specifies that the positions of the glyphs are taken from a character map lookup table. If this flag is not set, the positions are taken from an array of coordinates.
DriverStringOptionsVertical
Specifies that the string is displayed vertically.
DriverStringOptionsRealizedAdvance
Specifies that the glyph positions are calculated from the position of the first glyph. If this flag is not set, the glyph positions are obtained from an array of coordinates.
DriverStringOptionsLimitSubpixel
Specifies that less memory should be used for cache of antialiased glyphs. This also produces lower quality. If this flag is set, more memory is used, but the quality is higher.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
DrawDriverString, MeasureDriverString
Concepts
Antialiasing with Text


EmfPlusRecordType

The EmfPlusRecordType enumeration identifies metafile record types used in WMF, EMF, and EMF+ files.

enum EmfPlusRecordType{
  WmfRecordTypeSetBkColor              = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETBKCOLOR),
  WmfRecordTypeSetBkMode               = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETBKMODE),
  WmfRecordTypeSetMapMode              = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETMAPMODE),
  WmfRecordTypeSetROP2                 = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETROP2),
  WmfRecordTypeSetRelAbs               = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETRELABS),
  WmfRecordTypeSetPolyFillMode         = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETPOLYFILLMODE),
  WmfRecordTypeSetStretchBltMode       = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETSTRETCHBLTMODE),
  WmfRecordTypeSetTextCharExtra        = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETTEXTCHAREXTRA),
  WmfRecordTypeSetTextColor            = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETTEXTCOLOR),
  WmfRecordTypeSetTextJustification    = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETTEXTJUSTIFICATION),
  WmfRecordTypeSetWindowOrg            = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETWINDOWORG),
  WmfRecordTypeSetWindowExt            = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETWINDOWEXT),
  WmfRecordTypeSetViewportOrg          = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETVIEWPORTORG),
  WmfRecordTypeSetViewportExt          = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETVIEWPORTEXT),
  WmfRecordTypeOffsetWindowOrg         = GDIP_WMF_RECORD_TO_EMFPLUS(META_OFFSETWINDOWORG),
  WmfRecordTypeScaleWindowExt          = GDIP_WMF_RECORD_TO_EMFPLUS(META_SCALEWINDOWEXT),
  WmfRecordTypeOffsetViewportOrg       = GDIP_WMF_RECORD_TO_EMFPLUS(META_OFFSETVIEWPORTORG),
  WmfRecordTypeScaleViewportExt        = GDIP_WMF_RECORD_TO_EMFPLUS(META_SCALEVIEWPORTEXT),
  WmfRecordTypeLineTo                  = GDIP_WMF_RECORD_TO_EMFPLUS(META_LINETO),
  WmfRecordTypeMoveTo                  = GDIP_WMF_RECORD_TO_EMFPLUS(META_MOVETO),
  WmfRecordTypeExcludeClipRect         = GDIP_WMF_RECORD_TO_EMFPLUS(META_EXCLUDECLIPRECT),
  WmfRecordTypeIntersectClipRect       = GDIP_WMF_RECORD_TO_EMFPLUS(META_INTERSECTCLIPRECT),
  WmfRecordTypeArc                     = GDIP_WMF_RECORD_TO_EMFPLUS(META_ARC),
  WmfRecordTypeEllipse                 = GDIP_WMF_RECORD_TO_EMFPLUS(META_ELLIPSE),
  WmfRecordTypeFloodFill               = GDIP_WMF_RECORD_TO_EMFPLUS(META_FLOODFILL),
  WmfRecordTypePie                     = GDIP_WMF_RECORD_TO_EMFPLUS(META_PIE),
  WmfRecordTypeRectangle               = GDIP_WMF_RECORD_TO_EMFPLUS(META_RECTANGLE),
  WmfRecordTypeRoundRect               = GDIP_WMF_RECORD_TO_EMFPLUS(META_ROUNDRECT),
  WmfRecordTypePatBlt                  = GDIP_WMF_RECORD_TO_EMFPLUS(META_PATBLT),
  WmfRecordTypeSaveDC                  = GDIP_WMF_RECORD_TO_EMFPLUS(META_SAVEDC),
  WmfRecordTypeSetPixel                = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETPIXEL),
  WmfRecordTypeOffsetClipRgn           = GDIP_WMF_RECORD_TO_EMFPLUS(META_OFFSETCLIPRGN),
  WmfRecordTypeTextOut                 = GDIP_WMF_RECORD_TO_EMFPLUS(META_TEXTOUT),
  WmfRecordTypeBitBlt                  = GDIP_WMF_RECORD_TO_EMFPLUS(META_BITBLT),
  WmfRecordTypeStretchBlt              = GDIP_WMF_RECORD_TO_EMFPLUS(META_STRETCHBLT),
  WmfRecordTypePolygon                 = GDIP_WMF_RECORD_TO_EMFPLUS(META_POLYGON),
  WmfRecordTypePolyline                = GDIP_WMF_RECORD_TO_EMFPLUS(META_POLYLINE),
  WmfRecordTypeEscape                  = GDIP_WMF_RECORD_TO_EMFPLUS(META_ESCAPE),
  WmfRecordTypeRestoreDC               = GDIP_WMF_RECORD_TO_EMFPLUS(META_RESTOREDC),
  WmfRecordTypeFillRegion              = GDIP_WMF_RECORD_TO_EMFPLUS(META_FILLREGION),
  WmfRecordTypeFrameRegion             = GDIP_WMF_RECORD_TO_EMFPLUS(META_FRAMEREGION),
  WmfRecordTypeInvertRegion            = GDIP_WMF_RECORD_TO_EMFPLUS(META_INVERTREGION),
  WmfRecordTypePaintRegion             = GDIP_WMF_RECORD_TO_EMFPLUS(META_PAINTREGION),
  WmfRecordTypeSelectClipRegion        = GDIP_WMF_RECORD_TO_EMFPLUS(META_SELECTCLIPREGION),
  WmfRecordTypeSelectObject            = GDIP_WMF_RECORD_TO_EMFPLUS(META_SELECTOBJECT),
  WmfRecordTypeSetTextAlign            = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETTEXTALIGN),
  WmfRecordTypeDrawText                = GDIP_WMF_RECORD_TO_EMFPLUS(0x062F),  // META_DRAWTEXT
  WmfRecordTypeChord                   = GDIP_WMF_RECORD_TO_EMFPLUS(META_CHORD),
  WmfRecordTypeSetMapperFlags          = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETMAPPERFLAGS),
  WmfRecordTypeExtTextOut              = GDIP_WMF_RECORD_TO_EMFPLUS(META_EXTTEXTOUT),
  WmfRecordTypeSetDIBToDev             = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETDIBTODEV),
  WmfRecordTypeSelectPalette           = GDIP_WMF_RECORD_TO_EMFPLUS(META_SELECTPALETTE),
  WmfRecordTypeRealizePalette          = GDIP_WMF_RECORD_TO_EMFPLUS(META_REALIZEPALETTE),
  WmfRecordTypeAnimatePalette          = GDIP_WMF_RECORD_TO_EMFPLUS(META_ANIMATEPALETTE),
  WmfRecordTypeSetPalEntries           = GDIP_WMF_RECORD_TO_EMFPLUS(META_SETPALENTRIES),
  WmfRecordTypePolyPolygon             = GDIP_WMF_RECORD_TO_EMFPLUS(META_POLYPOLYGON),
  WmfRecordTypeResizePalette           = GDIP_WMF_RECORD_TO_EMFPLUS(META_RESIZEPALETTE),
  WmfRecordTypeDIBBitBlt               = GDIP_WMF_RECORD_TO_EMFPLUS(META_DIBBITBLT),
  WmfRecordTypeDIBStretchBlt           = GDIP_WMF_RECORD_TO_EMFPLUS(META_DIBSTRETCHBLT),
  WmfRecordTypeDIBCreatePatternBrush   = GDIP_WMF_RECORD_TO_EMFPLUS(META_DIBCREATEPATTERNBRUSH),
  WmfRecordTypeStretchDIB              = GDIP_WMF_RECORD_TO_EMFPLUS(META_STRETCHDIB),
  WmfRecordTypeExtFloodFill            = GDIP_WMF_RECORD_TO_EMFPLUS(META_EXTFLOODFILL),
  WmfRecordTypeSetLayout               = GDIP_WMF_RECORD_TO_EMFPLUS(0x0149),  // META_SETLAYOUT
  WmfRecordTypeResetDC                 = GDIP_WMF_RECORD_TO_EMFPLUS(0x014C),  // META_RESETDC
  WmfRecordTypeStartDoc                = GDIP_WMF_RECORD_TO_EMFPLUS(0x014D),  // META_STARTDOC
  WmfRecordTypeStartPage               = GDIP_WMF_RECORD_TO_EMFPLUS(0x004F),  // META_STARTPAGE
  WmfRecordTypeEndPage                 = GDIP_WMF_RECORD_TO_EMFPLUS(0x0050),  // META_ENDPAGE
  WmfRecordTypeAbortDoc                = GDIP_WMF_RECORD_TO_EMFPLUS(0x0052),  // META_ABORTDOC
  WmfRecordTypeEndDoc                  = GDIP_WMF_RECORD_TO_EMFPLUS(0x005E),  // META_ENDDOC
  WmfRecordTypeDeleteObject            = GDIP_WMF_RECORD_TO_EMFPLUS(META_DELETEOBJECT),
  WmfRecordTypeCreatePalette           = GDIP_WMF_RECORD_TO_EMFPLUS(META_CREATEPALETTE),
  WmfRecordTypeCreateBrush             = GDIP_WMF_RECORD_TO_EMFPLUS(0x00F8),  // META_CREATEBRUSH
  WmfRecordTypeCreatePatternBrush      = GDIP_WMF_RECORD_TO_EMFPLUS(META_CREATEPATTERNBRUSH),
  WmfRecordTypeCreatePenIndirect       = GDIP_WMF_RECORD_TO_EMFPLUS(META_CREATEPENINDIRECT),
  WmfRecordTypeCreateFontIndirect      = GDIP_WMF_RECORD_TO_EMFPLUS(META_CREATEFONTINDIRECT),
  WmfRecordTypeCreateBrushIndirect     = GDIP_WMF_RECORD_TO_EMFPLUS(META_CREATEBRUSHINDIRECT),
  WmfRecordTypeCreateBitmapIndirect    = GDIP_WMF_RECORD_TO_EMFPLUS(0x02FD),  // META_CREATEBITMAPINDIRECT
  WmfRecordTypeCreateBitmap            = GDIP_WMF_RECORD_TO_EMFPLUS(0x06FE),  // META_CREATEBITMAP
  WmfRecordTypeCreateRegion            = GDIP_WMF_RECORD_TO_EMFPLUS(META_CREATEREGION),
  EmfRecordTypeHeader                  = EMR_HEADER,
  EmfRecordTypePolyBezier              = EMR_POLYBEZIER,
  EmfRecordTypePolygon                 = EMR_POLYGON,
  EmfRecordTypePolyline                = EMR_POLYLINE,
  EmfRecordTypePolyBezierTo            = EMR_POLYBEZIERTO,
  EmfRecordTypePolyLineTo              = EMR_POLYLINETO,
  EmfRecordTypePolyPolyline            = EMR_POLYPOLYLINE,
  EmfRecordTypePolyPolygon             = EMR_POLYPOLYGON,
  EmfRecordTypeSetWindowExtEx          = EMR_SETWINDOWEXTEX,
  EmfRecordTypeSetWindowOrgEx          = EMR_SETWINDOWORGEX,
  EmfRecordTypeSetViewportExtEx        = EMR_SETVIEWPORTEXTEX,
  EmfRecordTypeSetViewportOrgEx        = EMR_SETVIEWPORTORGEX,
  EmfRecordTypeSetBrushOrgEx           = EMR_SETBRUSHORGEX,
  EmfRecordTypeEOF                     = EMR_EOF,
  EmfRecordTypeSetPixelV               = EMR_SETPIXELV,
  EmfRecordTypeSetMapperFlags          = EMR_SETMAPPERFLAGS,
  EmfRecordTypeSetMapMode              = EMR_SETMAPMODE,
  EmfRecordTypeSetBkMode               = EMR_SETBKMODE,
  EmfRecordTypeSetPolyFillMode         = EMR_SETPOLYFILLMODE,
  EmfRecordTypeSetROP2                 = EMR_SETROP2,
  EmfRecordTypeSetStretchBltMode       = EMR_SETSTRETCHBLTMODE,
  EmfRecordTypeSetTextAlign            = EMR_SETTEXTALIGN,
  EmfRecordTypeSetColorAdjustment      =   EMR_SETCOLORADJUSTMENT,
  EmfRecordTypeSetTextColor            = EMR_SETTEXTCOLOR,
  EmfRecordTypeSetBkColor              = EMR_SETBKCOLOR,
  EmfRecordTypeOffsetClipRgn           = EMR_OFFSETCLIPRGN,
  EmfRecordTypeMoveToEx                = EMR_MOVETOEX,
  EmfRecordTypeSetMetaRgn              = EMR_SETMETARGN,
  EmfRecordTypeExcludeClipRect         = EMR_EXCLUDECLIPRECT,
  EmfRecordTypeIntersectClipRect       = EMR_INTERSECTCLIPRECT,
  EmfRecordTypeScaleViewportExtEx      = EMR_SCALEVIEWPORTEXTEX,
  EmfRecordTypeScaleWindowExtEx        = EMR_SCALEWINDOWEXTEX,
  EmfRecordTypeSaveDC                  = EMR_SAVEDC,
  EmfRecordTypeRestoreDC               = EMR_RESTOREDC,
  EmfRecordTypeSetWorldTransform       = EMR_SETWORLDTRANSFORM,
  EmfRecordTypeModifyWorldTransform    = EMR_MODIFYWORLDTRANSFORM,
  EmfRecordTypeSelectObject            = EMR_SELECTOBJECT,
  EmfRecordTypeCreatePen               = EMR_CREATEPEN,
  EmfRecordTypeCreateBrushIndirect     = EMR_CREATEBRUSHINDIRECT,
  EmfRecordTypeDeleteObject            = EMR_DELETEOBJECT,
  EmfRecordTypeAngleArc                = EMR_ANGLEARC,
  EmfRecordTypeEllipse                 = EMR_ELLIPSE,
  EmfRecordTypeRectangle               = EMR_RECTANGLE,
  EmfRecordTypeRoundRect               = EMR_ROUNDRECT,
  EmfRecordTypeArc                     = EMR_ARC,
  EmfRecordTypeChord                   = EMR_CHORD,
  EmfRecordTypePie                     = EMR_PIE,
  EmfRecordTypeSelectPalette           = EMR_SELECTPALETTE,
  EmfRecordTypeCreatePalette           = EMR_CREATEPALETTE,
  EmfRecordTypeSetPaletteEntries       = EMR_SETPALETTEENTRIES,
  EmfRecordTypeResizePalette           = EMR_RESIZEPALETTE,
  EmfRecordTypeRealizePalette          = EMR_REALIZEPALETTE,
  EmfRecordTypeExtFloodFill            = EMR_EXTFLOODFILL,
  EmfRecordTypeLineTo                  = EMR_LINETO,
  EmfRecordTypeArcTo                   = EMR_ARCTO,
  EmfRecordTypePolyDraw                = EMR_POLYDRAW,
  EmfRecordTypeSetArcDirection         = EMR_SETARCDIRECTION,
  EmfRecordTypeSetMiterLimit           = EMR_SETMITERLIMIT,
  EmfRecordTypeBeginPath               = EMR_BEGINPATH,
  EmfRecordTypeEndPath                 = EMR_ENDPATH,
  EmfRecordTypeCloseFigure             = EMR_CLOSEFIGURE,
  EmfRecordTypeFillPath                = EMR_FILLPATH,
  EmfRecordTypeStrokeAndFillPath       = EMR_STROKEANDFILLPATH,
  EmfRecordTypeStrokePath              = EMR_STROKEPATH,
  EmfRecordTypeFlattenPath             = EMR_FLATTENPATH,
  EmfRecordTypeWidenPath               = EMR_WIDENPATH,
  EmfRecordTypeSelectClipPath          = EMR_SELECTCLIPPATH,
  EmfRecordTypeAbortPath               = EMR_ABORTPATH,
  EmfRecordTypeReserved_069            = 69,
  EmfRecordTypeGdiComment              = EMR_GDICOMMENT,
  EmfRecordTypeFillRgn                 = EMR_FILLRGN,
  EmfRecordTypeFrameRgn                = EMR_FRAMERGN,
  EmfRecordTypeInvertRgn               = EMR_INVERTRGN,
  EmfRecordTypePaintRgn                = EMR_PAINTRGN,
  EmfRecordTypeExtSelectClipRgn        = EMR_EXTSELECTCLIPRGN,
  EmfRecordTypeBitBlt                  = EMR_BITBLT,
  EmfRecordTypeStretchBlt              = EMR_STRETCHBLT,
  EmfRecordTypeMaskBlt                 = EMR_MASKBLT,
  EmfRecordTypePlgBlt                  = EMR_PLGBLT,
  EmfRecordTypeSetDIBitsToDevice       = EMR_SETDIBITSTODEVICE,
  EmfRecordTypeStretchDIBits           = EMR_STRETCHDIBITS,
  EmfRecordTypeExtCreateFontIndirect   = EMR_EXTCREATEFONTINDIRECTW,
  EmfRecordTypeExtTextOutA             = EMR_EXTTEXTOUTA,
  EmfRecordTypeExtTextOutW             = EMR_EXTTEXTOUTW,
  EmfRecordTypePolyBezier16            = EMR_POLYBEZIER16,
  EmfRecordTypePolygon16               = EMR_POLYGON16,
  EmfRecordTypePolyline16              = EMR_POLYLINE16,
  EmfRecordTypePolyBezierTo16          = EMR_POLYBEZIERTO16,
  EmfRecordTypePolylineTo16            = EMR_POLYLINETO16,
  EmfRecordTypePolyPolyline16          = EMR_POLYPOLYLINE16,
  EmfRecordTypePolyPolygon16           = EMR_POLYPOLYGON16,
  EmfRecordTypePolyDraw16              = EMR_POLYDRAW16,
  EmfRecordTypeCreateMonoBrush         = EMR_CREATEMONOBRUSH,
  EmfRecordTypeCreateDIBPatternBrushPt = EMR_CREATEDIBPATTERNBRUSHPT,
  EmfRecordTypeExtCreatePen            = EMR_EXTCREATEPEN,
  EmfRecordTypePolyTextOutA            = EMR_POLYTEXTOUTA,
  EmfRecordTypePolyTextOutW            = EMR_POLYTEXTOUTW,
  EmfRecordTypeSetICMMode              = 98,
  EmfRecordTypeCreateColorSpace        = 99,
  EmfRecordTypeSetColorSpace           = 100,
  EmfRecordTypeDeleteColorSpace        = 101,
  EmfRecordTypeGLSRecord               = 102,
  EmfRecordTypeGLSBoundedRecord        = 103,
  EmfRecordTypePixelFormat             = 104,
  EmfRecordTypeDrawEscape              = 105,
  EmfRecordTypeExtEscape               = 106,
  EmfRecordTypeStartDoc                = 107,
  EmfRecordTypeSmallTextOut            = 108,
  EmfRecordTypeForceUFIMapping         = 109,
  EmfRecordTypeNamedEscape             = 110,
  EmfRecordTypeColorCorrectPalette     = 111,
  EmfRecordTypeSetICMProfileA          = 112,
  EmfRecordTypeSetICMProfileW          = 113,
  EmfRecordTypeAlphaBlend              = 114,
  EmfRecordTypeSetLayout               = 115,
  EmfRecordTypeTransparentBlt          = 116,
  EmfRecordTypeReserved_117            = 117,
  EmfRecordTypeGradientFill            = 118,
  EmfRecordTypeSetLinkedUFIs           = 119,
  EmfRecordTypeSetTextJustification    = 120,
  EmfRecordTypeColorMatchToTargetW     = 121,
  EmfRecordTypeCreateColorSpaceW       = 122,
  EmfRecordTypeMax                     = 122,
  EmfRecordTypeMin                     = 1,
  EmfPlusRecordTypeInvalid = GDIP_EMFPLUS_RECORD_BASE,
  EmfPlusRecordTypeHeader,
  EmfPlusRecordTypeEndOfFile,
  EmfPlusRecordTypeComment,
  EmfPlusRecordTypeGetDC,
  EmfPlusRecordTypeMultiFormatStart,
  EmfPlusRecordTypeMultiFormatSection,
  EmfPlusRecordTypeMultiFormatEnd,
  EmfPlusRecordTypeObject,
  EmfPlusRecordTypeClear,
  EmfPlusRecordTypeFillRects,
  EmfPlusRecordTypeDrawRects,
  EmfPlusRecordTypeFillPolygon,
  EmfPlusRecordTypeDrawLines,
  EmfPlusRecordTypeFillEllipse,
  EmfPlusRecordTypeDrawEllipse,
  EmfPlusRecordTypeFillPie,
  EmfPlusRecordTypeDrawPie,
  EmfPlusRecordTypeDrawArc,
  EmfPlusRecordTypeFillRegion,
  EmfPlusRecordTypeFillPath,
  EmfPlusRecordTypeDrawPath,
  EmfPlusRecordTypeFillClosedCurve,
  EmfPlusRecordTypeDrawClosedCurve,
  EmfPlusRecordTypeDrawCurve,
  EmfPlusRecordTypeDrawBeziers,
  EmfPlusRecordTypeDrawImage,
  EmfPlusRecordTypeDrawImagePoints,
  EmfPlusRecordTypeDrawString,
  EmfPlusRecordTypeSetRenderingOrigin,
  EmfPlusRecordTypeSetAntiAliasMode,
  EmfPlusRecordTypeSetTextRenderingHint,
  EmfPlusRecordTypeSetTextContrast,
  EmfPlusRecordTypeSetGammaValue,
  EmfPlusRecordTypeSetInterpolationMode,
  EmfPlusRecordTypeSetPixelOffsetMode,
  EmfPlusRecordTypeSetCompositingMode,
  EmfPlusRecordTypeSetCompositingQuality,
  EmfPlusRecordTypeSave,
  EmfPlusRecordTypeRestore,
  EmfPlusRecordTypeBeginContainer,
  EmfPlusRecordTypeBeginContainerNoParams,
  EmfPlusRecordTypeEndContainer,
  EmfPlusRecordTypeSetWorldTransform,
  EmfPlusRecordTypeResetWorldTransform,
  EmfPlusRecordTypeMultiplyWorldTransform,
  EmfPlusRecordTypeTranslateWorldTransform,
  EmfPlusRecordTypeScaleWorldTransform,
  EmfPlusRecordTypeRotateWorldTransform,
  EmfPlusRecordTypeSetPageTransform,
  EmfPlusRecordTypeResetClip,
  EmfPlusRecordTypeSetClipRect,
  EmfPlusRecordTypeSetClipPath,
  EmfPlusRecordTypeSetClipRegion,
  EmfPlusRecordTypeOffsetClip,
  EmfPlusRecordTypeDrawDriverString,
  EmfPlusRecordTotal,
  EmfPlusRecordTypeMax = EmfPlusRecordTotal-1,
  EmfPlusRecordTypeMin = EmfPlusRecordTypeHeader
};

Elements

The elements of the EmfPlusRecordType enumeration come in three groups:

  • Elements in the first group have the prefix WmfRecordType and identity Windows Metafile (WMF) records.
  • Elements in the second group have the prefix EmfRecordType and identify Enhanced Metafile (EMF) records.
  • Elements in the third group have the prefix EmfPlusRecordType and identify EMF+ records.

WMF and EMF records can be displayed by GDI+ and by GDI. EMF+ records can be displayed by GDI+ but not by GDI.

Elements that have the WmfRecordType prefix are analogous to constants (defined in Wingdi.h) that have the prefix META_. For example, the element WmfRecordTypeSetBkColor is analogous to the constant META_SETBKCOLOR. For more information about WMF files, see Windows-Format Metafiles.

Elements that have the EmfRecordType prefix are analogous to constants (defined in Wingdi.h) that have the prefix EMR_. For example, the element EmfRecordTypePolygon is analogous to the constant EMR_POLYGON. For more information about EMR constants see EMR.

Elements that have the EmfPlusRecordType prefix are specific to GDI+. Most of those elements correspond to methods of the Graphics class. The remaining elements identify the header, the end of the file, and other sections of the metafile.

The following table lists the elements that correspond to methods of the Graphics class.

Enumeration element | Graphics class method
EmfPlusRecordTypeComment | AddMetafileComment
EmfPlusRecordTypeBeginContainer | BeginContainer(Rect& dstrect, Rect& srcrect, Unit unit) BeginContainer(RectF& dstrect, RectF& srcrect, Unit unit)
EmfPlusRecordTypeBeginContainerNoParams | BeginContainer()
EmfPlusRecordTypeClear | Clear
EmfPlusRecordTypeDrawArc | DrawArc
EmfPlusRecordTypeDrawBeziers | DrawBeziers
EmfPlusRecordTypeDrawClosedCurve | DrawClosedCurve
EmfPlusRecordTypeDrawCurve | DrawCurve
EmfPlusRecordTypeDrawDriverString | DrawDriverString
EmfPlusRecordTypeDrawEllipse | DrawEllipse
EmfPlusRecordTypeDrawImage | DrawImage (all methods that do not receive an array of destination points)
EmfPlusRecordTypeDrawImagePoints | DrawImage (all methods that receive an array of destination points)
EmfPlusRecordTypeDrawLines | DrawLines
EmfPlusRecordTypeDrawPath | DrawPath
EmfPlusRecordTypeDrawPie | DrawPie
EmfPlusRecordTypeDrawRects | DrawRectangles
EmfPlusRecordTypeDrawString | DrawString
EmfPlusRecordTypeEndContainer | EndContainer
EmfPlusRecordTypeFillClosedCurve | FillClosedCurve
EmfPlusRecordTypeFillEllipse | FillEllipse
EmfPlusRecordTypeFillPath | FillPath
EmfPlusRecordTypeFillPie | FillPie
EmfPlusRecordTypeFillPolygon | FillPolygon
EmfPlusRecordTypeFillRects | FillRectangles
EmfPlusRecordTypeFillRegion | FillRegion
EmfPlusRecordTypeGetHDC | GetHDC
EmfPlusRecordTypeMultiplyWorldTransform | MultiplyTransform
EmfPlusRecordTypeOffsetClip | TranslateClip
EmfPlusRecordTypeResetClip | ResetClip
EmfPlusRecordTypeResetWorldTransform | ResetTransform
EmfPlusRecordTypeRestore | Restore
EmfPlusRecordTypeRotateWorldTransform | RotateTransform
EmfPlusRecordTypeSave | Save
EmfPlusRecordTypeScaleWorldTransform | ScaleTransform
EmfPlusRecordTypeSetAntiAliasMode | SetSmoothingMode
EmfPlusRecordTypeSetClipPath | SetClip(path, combineMode)
EmfPlusRecordTypeSetClipRect | SetClip(Rect& rect, CombineMode combineMode) SetClip(RectF& rect, CombineMode combineMode)
EmfPlusRecordTypeSetClipRegion | SetClip(region, combineMode)
EmfPlusRecordTypeSetCompositingMode | SetCompositingMode
EmfPlusRecordTypeSetCompositingQuality | SetCompositingQuality
EmfPlusRecordTypeSetInterpolationMode | SetInterpolationMode
EmfPlusRecordTypeSetPageTransform | SetPageScale and SetPageUnit
EmfPlusRecordTypeSetPixelOffsetMode | SetPixelOffsetMode
EmfPlusRecordTypeSetRenderingOrigin | SetRenderingOrigin
EmfPlusRecordTypeSetTextContrast | SetTextContrast
EmfPlusRecordTypeSetTextRenderingHint | SetTextRenderingHint
EmfPlusRecordTypeSetWorldTransform | SetTransform
EmfPlusRecordTypeTranslateWorldTransform | TranslateTransform

The following table lists identifiers for EMF+ records that do not correspond directly to methods of the Graphics class.

EmfPlusRecordTypeHeader | Identifies a record that is the EMF+ header.
EmfPlusRecordTypeEndOfFile | Identifies a record that marks the last EMF+ record of a metafile.
EmfPlusRecordTypeMultiFormatStart | Identifies the start of a multiple-format block.
EmfPlusRecordTypeMultiFormatSection | Identifies a section in a multiple-format block. Multiple-format records allow the same set of records to be represented in several formats.
EmfPlusRecordTypeMultiFormatEnd | Identifies the end of a multiple-format block.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


EmfType

The EmfType enumeration specifies the nature of the records that are placed in an Enhanced Metafile (EMF) file. This enumeration is used by several constructors in the Metafile class.

enum EmfType{
  EmfTypeEmfOnly     = MetafileTypeEmf,
  EmfTypeEmfPlusOnly = MetafileTypeEmfPlusOnly,
  EmfTypeEmfPlusDual = MetafileTypeEmfPlusDual
};

Elements

EmfTypeEmfOnly
Specifies that all of the records in the metafile are EMF records, which can be displayed by GDI or GDI+.
EmfTypeEmfPlusOnly
Specifies that all of the records in the metafile are EMF+ records, which can be displayed by GDI+ but not by GDI.
EmfTypeEmfPlusDual
Specifies that all EMF+ records in the metafile are associated with an alternate EMF record. Metafiles of type EmfTypeEmfPlusDual can be displayed by GDI or by GDI+.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
Metafile Constructors


EncoderParameterValueType

The EncoderParameterValueType enumeration specifies data types for image codec (encoder/decoder) parameters. An element of this enumeration is assigned to the Type data member of an EncoderParameter object.

enum EncoderParameterValueType{
  EncoderParameterValueTypeByte = 1,
  EncoderParameterValueTypeASCII = 2,
  EncoderParameterValueTypeShort = 3,
  EncoderParameterValueTypeLong = 4,
  EncoderParameterValueTypeRational = 5,
  EncoderParameterValueTypeLongRange = 6,
  EncoderParameterValueTypeUndefined = 7,
  EncoderParameterValueTypeRationalRange = 8
};

Elements

EncoderParameterValueTypeByte
Specifies that the parameter is an 8-bit unsigned integer.
EncoderParameterValueTypeASCII
Specifies that the parameter is a null-terminated character string.
EncoderParameterValueTypeShort
Specifies that the parameter is a 16-bit unsigned integer.
EncoderParameterValueTypeLong
Specifies that the parameter is a 32-bit unsigned integer.
EncoderParameterValueTypeRational
Specifies that the parameter is an array of two, 32-bit unsigned integers. The pair of integers represents a fraction. The first integer in the pair is the numerator, and the second integer in the pair is the denominator.
EncoderParameterValueTypeLongRange
Specifies that the parameter is an array of two, 32-bit unsigned integers. The pair of integers represents a range of numbers. The first integer is the smallest number in the range, and the second integer is the largest number in the range.
EncoderParameterValueTypeUndefined
Specifies that the parameter is an array of bytes that can hold values of any type.
EncoderParameterValueTypeRationalRange
Specifies that the parameter is an array of four, 32-bit unsigned integers. The first two integers represent one fraction, and the second two integers represent a second fraction. The two fractions represent a range of rational numbers. The first fraction is the smallest rational number in the range, and the second fraction is the largest rational number in the range.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
EncoderParameter


EncoderValue

The EncoderValue enumeration specifies values that can be passed as arguments to image encoders. For more information about image encoders, see Using Image Encoders and Decoders .

enum EncoderValue{
  EncoderValueColorTypeCMYK,
  EncoderValueColorTypeYCCK,
  EncoderValueCompressionLZW,
  EncoderValueCompressionCCITT3,
  EncoderValueCompressionCCITT4,
  EncoderValueCompressionRle,
  EncoderValueCompressionNone,
  EncoderValueScanMethodInterlaced,
  EncoderValueScanMethodNonInterlaced,
  EncoderValueVersionGif87,
  EncoderValueVersionGif89,
  EncoderValueRenderProgressive,
  EncoderValueRenderNonProgressive,
  EncoderValueTransformRotate90,
  EncoderValueTransformRotate180,
  EncoderValueTransformRotate270,
  EncoderValueTransformFlipHorizontal,
  EncoderValueTransformFlipVertical,
  EncoderValueMultiFrame,
  EncoderValueLastFrame,
  EncoderValueFlush,
  EncoderValueFrameDimensionTime,
  EncoderValueFrameDimensionResolution,
  EncoderValueFrameDimensionPage
};

Elements

EncoderValueColorTypeCMYK
Not used in GDI+ version 1.0.
EncoderValueColorTypeYCCK
Not used in GDI+ version 1.0.
EncoderValueCompressionLZW
For a TIFF image, specifies the LZW compression method.
EncoderValueCompressionCCITT3
For a TIFF image, specifies the CCITT3 compression method.
EncoderValueCompressionCCITT4
For a TIFF image, specifies the CCITT4 compression method.
EncoderValueCompressionRle
For a TIFF image, specifies the RLE compression method.
EncoderValueCompressionNone
For a TIFF image, specifies no compression.
EncoderValueScanMethodInterlaced
Not used in GDI+ version 1.0.
EncoderValueScanMethodNonInterlaced
Not used in GDI+ version 1.0.
EncoderValueVersionGif87
Not used in GDI+ version 1.0.
EncoderValueVersionGif89
Not used in GDI+ version 1.0.
EncoderValueRenderProgressive
Not used in GDI+ version 1.0.
EncoderValueRenderNonProgressive
Not used in GDI+ version 1.0.
EncoderValueTransformRotate90
For a JPEG image, specifies lossless 90-degree clockwise rotation.
EncoderValueTransformRotate180
For a JPEG image, specifies lossless 180-degree rotation.
EncoderValueTransformRotate270
For a JPEG image, specifies lossless 270-degree clockwise rotation.
EncoderValueTransformFlipHorizontal
For a JPEG image, specifies a lossless horizontal flip.
EncoderValueTransformFlipVertical
For a JPEG image, specifies a lossless vertical flip.
EncoderValueMultiFrame
Specifies multiple-frame encoding.
EncoderValueLastFrame
Specifies the last frame of a multiple-frame image.
EncoderValueFlush
Specifies that the encoder object is to be closed.
EncoderValueFrameDimensionTime
Not used in GDI+ version 1.0.
EncoderValueFrameDimensionResolution
Not used in GDI+ version 1.0.
EncoderValueFrameDimensionPage
For a TIFF image, specifies the page frame dimension

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


FillMode

The FillMode enumeration specifies how to fill areas that are formed when a path or curve intersects itself. This enumeration is used by several methods of the Graphics class, including FillClosedCurve and FillPolygon, and by the constructors of the GraphicsPath class.

enum FillMode{
  FillModeAlternate,
  FillModeWinding
};

Elements

FillModeAlternate
Specifies that areas are filled according to the even-odd parity rule. According to this rule, you can determine whether a test point is inside or outside a closed curve as follows: Draw a line from the test point to a point that is distant from the curve. If that line crosses the curve an odd number of times, the test point is inside the curve; otherwise, the test point is outside the curve.
FillModeWinding
Specifies that areas are filled according to the nonzero winding rule. According to this rule, you can determine whether a test point is inside or outside a closed curve as follows: Draw a line from a test point to a point that is distant from the curve. Count the number of times the curve crosses the test line from left to right, and count the number of times the curve crosses the test line from right to left. If those two numbers are the same, the test point is outside the curve; otherwise, the test point is inside the curve.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
FillClosedCurve Methods, FillPolygon Methods, Graphics, GraphicsPath Constructors


FlushIntention

The FlushIntention enumeration specifies when to flush the queue of graphics operations.

enum FlushIntention{
  FlushIntentionFlush = 0,
  FlushIntentionSync = 1
};

Elements

FlushIntentionFlush
When passed to the Graphics::Flush method, specifies that pending rendering operations are executed as soon as possible. The Flush method is not synchronized with the completion of the rendering operations and might return before the rendering operations are completed.
FlushIntentionSync
When passed to the Graphics::Flush method, specifies that pending rendering operations are executed as soon as possible. The Flush method is synchronized with the completion of the rendering operations; that is, it will not return until after the rendering operations are completed.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


FontStyle

The FontStyle enumeration specifies the style of the typeface of a font. Styles can be combined.

enum FontStyle{
  FontStyleRegular    = 0,
  FontStyleBold       = 1,
  FontStyleItalic     = 2,
  FontStyleBoldItalic = 3,
  FontStyleUnderline  = 4,
  FontStyleStrikeout  = 8
};

Elements

FontStyleRegular
Specifies normal weight or thickness of the typeface.
FontStyleBold
Specifies bold typeface. Bold is a heavier weight or thickness.
FontStyleItalic
Specifies italic typeface, which produces a noticeable slant to the vertical stems of the characters.
FontStyleBoldItalic
Specifies the typeface as both bold and italic.
FontStyleUnderline
Specifies underline, which displays a line underneath the baseline of the characters.
FontStyleStrikeout
Specifies strikeout, which displays a horizontal line drawn through the middle of the characters.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


HatchStyle

The HatchStyle enumeration specifies the hatch pattern used by a brush of type HatchBrush. The hatch pattern consists of a solid background color and lines drawn over the background.

enum HatchStyle{
  HatchStyleHorizontal = 0,
  HatchStyleVertical = 1,
  HatchStyleForwardDiagonal = 2,
  HatchStyleBackwardDiagonal = 3,
  HatchStyleCross = 4,
  HatchStyleDiagonalCross = 5,
  HatchStyle05Percent = 6,
  HatchStyle10Percent = 7,
  HatchStyle20Percent = 8,
  HatchStyle25Percent = 9,
  HatchStyle30Percent = 10,
  HatchStyle40Percent = 11,
  HatchStyle50Percent = 12,
  HatchStyle60Percent = 13,
  HatchStyle70Percent = 14,
  HatchStyle75Percent = 15,
  HatchStyle80Percent = 16,
  HatchStyle90Percent = 17,
  HatchStyleLightDownwardDiagonal = 18,
  HatchStyleLightUpwardDiagonal = 19,
  HatchStyleDarkDownwardDiagonal = 20,
  HatchStyleDarkUpwardDiagonal = 21,
  HatchStyleWideDownwardDiagonal = 22,
  HatchStyleWideUpwardDiagonal = 23,
  HatchStyleLightVertical = 24,
  HatchStyleLightHorizontal = 25,
  HatchStyleNarrowVertical = 26,
  HatchStyleNarrowHorizontal = 27,
  HatchStyleDarkVertical = 28,
  HatchStyleDarkHorizontal = 29,
  HatchStyleDashedDownwardDiagonal = 30,
  HatchStyleDashedUpwardDiagonal = 31,
  HatchStyleDashedHorizontal = 32,
  HatchStyleDashedVertical = 33,
  HatchStyleSmallConfetti = 34,
  HatchStyleLargeConfetti = 35,
  HatchStyleZigZag = 36,
  HatchStyleWave = 37,
  HatchStyleDiagonalBrick = 38,
  HatchStyleHorizontalBrick = 39,
  HatchStyleWeave = 40,
  HatchStylePlaid = 41,
  HatchStyleDivot = 42,
  HatchStyleDottedGrid = 43,
  HatchStyleDottedDiamond = 44,
  HatchStyleShingle = 45,
  HatchStyleTrellis = 46,
  HatchStyleSphere = 47,
  HatchStyleSmallGrid = 48,
  HatchStyleSmallCheckerBoard = 49,
  HatchStyleLargeCheckerBoard = 50,
  HatchStyleOutlinedDiamond = 51,
  HatchStyleSolidDiamond = 52,
  HatchStyleTotal,
  HatchStyleLargeGrid = HatchStyleCross,
  HatchStyleMin = HatchStyleHorizontal,
  HatchStyleMax = HatchStyleTotal - 1
};

Elements

HatchStyleHorizontal
Specifies horizontal lines.

HatchStyleVertical
Specifies vertical lines.

HatchStyleForwardDiagonal
Specifies diagonal lines that slant to the right from top points to bottom points. The lines are antialiased.

HatchStyleBackwardDiagonal
Specifies diagonal lines that slant to the left from top points to bottom points. The lines are antialiased.

HatchStyleCross
Specifies horizontal and vertical lines that cross at 90-degree angles.

HatchStyleDiagonalCross
Specifies forward diagonal and backward diagonal lines that cross at 90-degree angles. The lines are antialiased.

HatchStyle05Percent
Specifies a 5-percent hatch. The ratio of foreground color to background color is 5:100.

HatchStyle10Percent
Specifies a 10-percent hatch. The ratio of foreground color to background color is 10:100.

HatchStyle20Percent
Specifies a 20-percent hatch. The ratio of foreground color to background color is 20:100.

HatchStyle25Percent
Specifies a 25-percent hatch. The ratio of foreground color to background color is 25:100.

HatchStyle30Percent
Specifies a 30-percent hatch. The ratio of foreground color to background color is 30:100.

HatchStyle40Percent
Specifies a 40-percent hatch. The ratio of foreground color to background color is 40:100.

HatchStyle50Percent
Specifies a 50-percent hatch. The ratio of foreground color to background color is 50:100.

HatchStyle60Percent
Specifies a 60-percent hatch. The ratio of foreground color to background color is 60:100.

HatchStyle70Percent
Specifies a 70-percent hatch. The ratio of foreground color to background color is 70:100.

HatchStyle75Percent
Specifies a 75-percent hatch. The ratio of foreground color to background color is 75:100.

HatchStyle80Percent
Specifies an 80-percent hatch. The ratio of foreground color to background color is 80:100.

HatchStyle90Percent
Specifies a 90-percent hatch. The ratio of foreground color to background color is 90:100.

HatchStyleLightDownwardDiagonal
Specifies diagonal lines that slant to the right from top points to bottom points and are spaced 50 percent closer together than HatchStyleForwardDiagonal but are not antialiased.

HatchStyleLightUpwardDiagonal
Specifies diagonal lines that slant to the left from top points to bottom points and are spaced 50 percent closer together than HatchStyleBackwardDiagonal but are not antialiased.

HatchStyleDarkDownwardDiagonal
Specifies diagonal lines that slant to the right from top points to bottom points, are spaced 50 percent closer together than HatchStyleForwardDiagonal, and are twice the width of HatchStyleForwardDiagonal but are not antialiased.

HatchStyleDarkUpwardDiagonal
Specifies diagonal lines that slant to the left from top points to bottom points, are spaced 50 percent closer together than HatchStyleBackwardDiagonal, and are twice the width of HatchStyleBackwardDiagonal but are not antialiased.

HatchStyleWideDownwardDiagonal
Specifies diagonal lines that slant to the right from top points to bottom points, have the same spacing as HatchStyleForwardDiagonal, and are triple the width of HatchStyleForwardDiagonal but are not antialiased.

HatchStyleWideUpwardDiagonal
Specifies diagonal lines that slant to the left from top points to bottom points, have the same spacing as HatchStyleBackwardDiagonal, and are triple the width of HatchStyleBackwardDiagonal but are not antialiased.

HatchStyleLightVertical
Specifies vertical lines that are spaced 50 percent closer together than HatchStyleVertical.

HatchStyleLightHorizontal
Specifies horizontal lines that are spaced 50 percent closer together than HatchStyleHorizontal.

HatchStyleNarrowVertical
Specifies vertical lines that are spaced 75 percent closer together than HatchStyleVertical (or 25 percent closer together than HatchStyleLightVertical).

HatchStyleNarrowHorizontal
Specifies horizontal lines that are spaced 75 percent closer together than HatchStyleHorizontal ( or 25 percent closer together than HatchStyleLightHorizontal).

HatchStyleDarkVertical
Specifies vertical lines that are spaced 50 percent closer together than HatchStyleVerical and are twice the width of HatchStyleVertical.

HatchStyleDarkHorizontal
Specifies horizontal lines that are spaced 50 percent closer together than HatchStyleHorizontal and are twice the width of HatchStyleHorizontal.

HatchStyleDashedDownwardDiagonal
Specifies horizontal lines that are composed of forward diagonals.

HatchStyleDashedUpwardDiagonal
Specifies horizontal lines that are composed of backward diagonals.

HatchStyleDashedHorizontal
Specifies horizontal dashed lines.

HatchStyleDashedVertical
Specifies vertical dashed lines.

HatchStyleSmallConfetti
Specifies a hatch that has the appearance of confetti.

HatchStyleLargeConfetti
Specifies a hatch that has the appearance of confetti composed of larger pieces than HatchStyleSmallConfetti.

HatchStyleZigZag
Specifies horizontal lines of zigzags.

HatchStyleWave
Specifies horizontal lines of tildes.

HatchStyleDiagonalBrick
Specifies a hatch that has the appearance of a wall of bricks laid in a backward diagonal direction.

HatchStyleHorizontalBrick
Specifies a hatch that has the appearance of a wall of bricks laid horizontally.

HatchStyleWeave
Specifies a hatch that has the appearance of a woven material.

HatchStylePlaid
Specifies a hatch that has the appearance of a plaid material.

HatchStyleDivot
Specifies a hatch that has the appearance of divots.

HatchStyleDottedGrid
Specifies horizontal and vertical dotted lines that cross at 90-degree angles.

HatchStyleDottedDiamond
Specifies forward diagonal and backward diagonal dotted lines that cross at 90-degree angles.

HatchStyleShingle
Specifies a hatch that has the appearance of shingles laid in a forward diagonal direction.

HatchStyleTrellis
Specifies a hatch that has the appearance of a trellis.

HatchStyleSphere
Specifies a hatch that has the appearance of a checkerboard of spheres.

HatchStyleSmallGrid
Specifies horizontal and vertical lines that cross at 90-degree angles and are spaced 50 percent closer together than HatchStyleCross.

HatchStyleSmallCheckerBoard
Specifies a hatch that has the appearance of a checkerboard.

HatchStyleLargeCheckerBoard
Specifies a hatch that has the appearance of a checkerboard with squares that are twice the size of HatchStyleSmallCheckerBoard.

HatchStyleOutlinedDiamond
Specifies forward diagonal and backward diagonal lines that cross at 90-degree angles but are not antialiased.

HatchStyleSolidDiamond
Specifies a hatch that has the appearance of a checkerboard placed diagonally.

HatchStyleTotal
Specifies no hatch thereby allowing the brush to be transparent.
HatchStyleLargeGrid
Specifies HatchStyleCross.
HatchStyleMin
Specifies HatchStyleHorizonal.
HatchStyleMax
Specifies HatchStyleSolidDiamond.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


HotkeyPrefix

The HotkeyPrefix enumeration specifies how to display hot keys. There are three options: do nothing, display hot keys underlined, and hide the hot key underlines.

enum HotkeyPrefix{
  HotkeyPrefixNone = 0,
  HotkeyPrefixShow = 1,
  HotkeyPrefixHide = 2
};

Elements

HotkeyPrefixNone
Specifies that no hot key processing occurs.
HotkeyPrefixShow
Specifies that Unicode text is scanned for ampersands (&), which are interpreted as hot key markers in the same way as menu and dialog resources are processed in the Windows user interface. All pairs of ampersands are replaced by a single ampersand. All single ampersands are removed and the first character that follows the first single ampersand is displayed underlined.
HotkeyPrefixHide
Specifies that Unicode text is scanned for ampersands (&), which are substituted and removed as in HotkeyPrefixShow but no underline is shown. This option can be used when accessibility hot key underlines are not required.

Remarks

Hot keys are keys that are programmed to provide keyboard shortcuts to functionality and are activated by pressing the ALT key. The keys are application dependent and are identified by an underscored letter, typically in a menu. An example would be the File menu with the letter F underscored. This makes the F key a hot key to launch the File menu.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


ImageCodecFlags

The ImageCodecFlags enumeration indicates attributes of an image codec.

enum ImageCodecFlags{
  ImageCodecFlagsEncoder = 0x00000001,
  ImageCodecFlagsDecoder = 0x00000002,
  ImageCodecFlagsSupportBitmap  = 0x00000004,
  ImageCodecFlagsSupportVector  = 0x00000008,
  ImageCodecFlagsSeekableEncode = 0x00000010,
  ImageCodecFlagsBlockingDecode = 0x00000020,
  ImageCodecFlagsBuiltin = 0x00010000,
  ImageCodecFlagsSystem  = 0x00020000,
  ImageCodecFlagsUser    = 0x00040000
};

Elements

ImageCodecFlagsEncoder
Indicates that the codec supports encoding (saving).
ImageCodecFlagsDecoder
Indicates that the codec supports decoding (reading).
ImageCodecFlagsSupportBitmap
Indicates that the codec supports raster images (bitmaps).
ImageCodecFlagsSupportVector
Indicates that the codec supports vector images (metafiles).
ImageCodecFlagsSeekableEncode
Indicates that an encoder requires a seekable output stream.
ImageCodecFlagsBlockingDecode
Indicates that a decoder has blocking behavior during the decoding process.
ImageCodecFlagsBuiltin
Indicates that the codec is built in to GDI+.
ImageCodecFlagsSystem
Not used in GDI+ version 1.0.
ImageCodecFlagsUser
Not used in GDI+ version 1.0.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimaging.h; include Gdiplus.h.


ImageFlags

The ImageFlags enumeration specifies the attributes of the pixel data contained in an Image object. The Image::GetFlags method returns an element of this enumeration.

enum ImageFlags{
  ImageFlagsNone       = 0,
  ImageFlagsScalable   = 0x0001,
  ImageFlagsHasAlpha   = 0x0002,
  ImageFlagsHasTranslucent    = 0x0004,
  ImageFlagsPartiallyScalable = 0x0008,
  ImageFlagsColorSpaceRGB     = 0x0010,
  ImageFlagsColorSpaceCMYK    = 0x0020,
  ImageFlagsColorSpaceGRAY    = 0x0040,
  ImageFlagsColorSpaceYCBCR   = 0x0080,
  ImageFlagsColorSpaceYCCK    = 0x0100,
  ImageFlagsHasRealDPI        = 0x1000,
  ImageFlagsHasRealPixelSize  = 0x2000,
  ImageFlagsReadOnly   = 0x00010000,
  ImageFlagsCaching    = 0x00020000
};

Elements

ImageFlagsNone
Specifies no format information.
ImageFlagsScalable
Specifies that the image can be scaled.
ImageFlagsHasAlpha
Specifies that the pixel data contains alpha values.
ImageFlagsHasTranslucent
Specifies that the pixel data has alpha values other than 0 (transparent) and 255 (opaque).
ImageFlagsPartiallyScalable
Specifies that the pixel data is partially scalable with some limitations.
ImageFlagsColorSpaceRGB
Specifies that the image is stored using an RGB color space.
ImageFlagsColorSpaceCMYK
Specifies that the image is stored using a CMYK color space.
ImageFlagsColorSpaceGRAY
Specifies that the image is a grayscale image.
ImageFlagsColorSpaceYCBCR
Specifies that the image is stored using a YCBCR color space.
ImageFlagsColorSpaceYCCK
Specifies that the image is stored using a YCCK color space.
ImageFlagsHasRealDPI
Specifies that dots per inch information is stored in the image.
ImageFlagsHasRealPixelSize
Specifies that the pixel size is stored in the image.
ImageFlagsReadOnly
Specifies that the pixel data is read-only.
ImageFlagsCaching
Specifies that the pixel data can be cached for faster access.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimaging.h; include Gdiplus.h.

See Also

Reference
GetFlags


ImageLockMode

The ImageLockMode enumeration specifies flags that are passed to the flags parameter of the Bitmap::LockBits method. The LockBits method locks a portion of an image so that you can read or write the pixel data.

enum ImageLockMode{
  ImageLockModeRead  = 0x0001,
  ImageLockModeWrite = 0x0002,
  ImageLockModeUserInputBuf = 0x0004
};

Elements

ImageLockModeRead
Specifies that a portion of the image is locked for reading.
ImageLockModeWrite
Specifies that a portion of the image is locked for writing.
ImageLockModeUserInputBuf
Specifies that the buffer used for reading or writing pixel data is allocated by the user. If this flag is set, then the lockedBitmapData parameter of the Bitmap::LockBits method serves as an input parameter (and possibly as an output parameter). If this flag is cleared, then the lockedBitmapData parameter serves only as an output parameter.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimaging.h; include Gdiplus.h.

See Also

Reference
LockBits


ImageType

The ImageType enumeration indicates whether an image is a bitmap or a metafile. The Image::GetType method returns an element of this enumeration.

enum ImageType{
  ImageTypeUnknown  = 0,
  ImageTypeBitmap   = 1,
  ImageTypeMetafile = 2
};

Elements

ImageTypeUnknown
Indicates that the image type is not known.
ImageTypeBitmap
Indicates a bitmap image.
ImageTypeMetafile
Indicates a metafile image.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
GetType


InterpolationMode

The InterpolationMode enumeration specifies the algorithm that is used when images are scaled or rotated. This enumeration is used by the GetInterpolationMode and SetInterpolationMode methods of the Graphics class.

enum InterpolationMode{
  InterpolationModeInvalid = QualityModeInvalid,
  InterpolationModeDefault = QualityModeDefault,
  InterpolationModeLowQuality = QualityModeLow,
  InterpolationModeHighQuality = QualityModeHigh,
  InterpolationModeBilinear,
  InterpolationModeBicubic,
  InterpolationModeNearestNeighbor,
  InterpolationModeHighQualityBilinear,
  InterpolationModeHighQualityBicubic
};

Elements

InterpolationModeDefault
Specifies the default interpolation mode.
InterpolationModeLowQuality
Specifies a low-quality mode.
InterpolationModeHighQuality
Specifies a high-quality mode.
InterpolationModeBilinear
Specifies bilinear interpolation. No prefiltering is done. This mode is not suitable for shrinking an image below 50 percent of its original size.
InterpolationModeBicubic
Specifies bicubic interpolation. No prefiltering is done. This mode is not suitable for shrinking an image below 25 percent of its original size.
InterpolationModeNearestNeighbor
Specifies nearest-neighbor interpolation.
InterpolationModeHighQualityBilinear
Specifies high-quality, bilinear interpolation. Prefiltering is performed to ensure high-quality shrinking.
InterpolationModeHighQualityBicubic
Specifies high-quality, bicubic interpolation. Prefiltering is performed to ensure high-quality shrinking. This mode produces the highest quality transformed images.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
GetInterpolationMode, SetInterpolationMode


LinearGradientMode

The LinearGradientMode enumeration specifies the direction in which the change of color occurs for a linear gradient brush.

enum LinearGradientMode{
  LinearGradientModeHorizontal = 0,
  LinearGradientModeVertical   = 1,
  LinearGradientModeForwardDiagonal  = 2,
  LinearGradientModeBackwardDiagonal = 3
};

Elements

LinearGradientModeHorizontal
Specifies the color to change in a horizontal direction from the left of the display to the right of the display.
LinearGradientModeVertical
Specifies the color to change in a vertical direction from the top of the display to the bottom of the display.
LinearGradientModeForwardDiagonal
Specifies the color to change in a forward diagonal direction from the upper-left corner to the lower-right corner of the display.
LinearGradientModeBackwardDiagonal
Specifies the color to change in a backward diagonal direction from the upper-right corner to the lower-left corner of the display.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


LineCap

The LineCap enumeration specifies the type of graphic shape to use on the end of a line drawn with a GDI+ pen. The cap can be a square, circle, triangle, arrowhead, custom, or masked (hidden). End caps can also "anchor" the line by centering the cap at the end of the line.

enum LineCap{
  LineCapFlat     = 0,
  LineCapSquare   = 1,
  LineCapRound    = 2,
  LineCapTriangle = 3,
  LineCapNoAnchor = 0x10,
  LineCapSquareAnchor  = 0x11,
  LineCapRoundAnchor   = 0x12,
  LineCapDiamondAnchor = 0x13,
  LineCapArrowAnchor   = 0x14,
  LineCapCustom        = 0xff
};

Elements

LineCapFlat
Specifies that the line ends at the last point. The end is squared off.
LineCapSquare
Specifies a square cap. The center of the square is the last point in the line. The height and width of the square are the line width.
LineCapRound
Specifies a circular cap. The center of the circle is the last point in the line. The diameter of the circle is the line width.
LineCapTriangle
Specifies a triangular cap. The base of the triangle is the last point in the line. The base of the triangle is the line width.
LineCapNoAnchor
Specifies that the line ends are not anchored.
LineCapSquareAnchor
Specifies that the line ends are anchored with a square. The center of the square is the last point in the line. The height and width of the square are the line width.
LineCapRoundAnchor
Specifies that the line ends are anchored with a circle. The center of the circle is at the last point in the line. The circle is wider than the line.
LineCapDiamondAnchor
Specifies that the line ends are anchored with a diamond (a square turned at 45 degrees). The center of the diamond is at the last point in the line. The diamond is wider than the line.
LineCapArrowAnchor
Specifies that the line ends are anchored with arrowheads. The arrowhead point is located at the last point in the line. The arrowhead is wider than the line.
LineCapCustom
Specifies that the line ends are made from a CustomLineCap.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


LineJoin

The LineJoin enumeration specifies how to join two lines that are drawn by the same pen and whose ends meet. At the intersection of the two line ends, a line join makes the join look more continuous.

enum LineJoin{
  LineJoinMiter = 0,
  LineJoinBevel = 1,
  LineJoinRound = 2,
  LineJoinMiterClipped =3
};

Elements

LineJoinMiter
Specifies a mitered join. This produces a sharp corner or a clipped corner, depending on whether the length of the miter exceeds the miter limit.
LineJoinBevel
Specifies a beveled join. This produces a diagonal corner.
LineJoinRound
Specifies a circular join. This produces a smooth, circular arc between the lines.
LineJoinMiterClipped
Specifies a mitered join. This produces a sharp corner or a beveled corner, depending on whether the length of the miter exceeds the miter limit.

Remarks

The miter length is the distance from the intersection of the line walls on the inside of the join to the intersection of the line walls outside of the join. The miter length can be large when the angle between two lines is small. The miter limit is the maximum allowed ratio of miter length to stroke width. The default value is 10.0f.

When using LineJoinMiter and the actual ratio exceeds the miter limit, the corner is clipped perpendicular to the miter at a distance from the inner corner that is the product of the miter limit and the pen width.

When using LineJoinMiterClipped and the miter limit is exceeded, the join is drawn as if its type were LineJoinBevel; that is, when the line walls on the inside of the join meet, then a joining line is drawn between the line walls on the outside of the join.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
SetLineJoin, SetMiterLimit


MatrixOrder

The MatrixOrder enumeration specifies the order of multiplication when a new matrix is multiplied by an existing matrix.

enum MatrixOrder{
  MatrixOrderPrepend = 0,
  MatrixOrderAppend  = 1
};

Elements

MatrixOrderPrepend
Specifies that the new matrix is on the left and the existing matrix is on the right.
MatrixOrderAppend
Specifies that the existing matrix is on the left and the new matrix is on the right.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


MetafileFrameUnit

The MetafileFrameUnit enumeration specifies the unit of measure for a metafile frame rectangle.

enum MetafileFrameUnit{
  MetafileFrameUnitPixel = UnitPixel,
  MetafileFrameUnitPoint = UnitPoint,
  MetafileFrameUnitInch  = UnitInch,
  MetafileFrameUnitDocument   = UnitDocument,
  MetafileFrameUnitMillimeter = UnitMillimeter,
  MetafileFrameUnitGdi
};

Elements

MetafileFrameUnitPixel
Specifies that a unit is 1 pixel.
MetafileFrameUnitPoint
Specifies that a unit is 1 point.
MetafileFrameUnitInch
Specifies that a unit is 1 inch.
MetafileFrameUnitDocument
Specifies that a unit is 1/300 inch.
MetafileFrameUnitMillimeter
Specifies that a unit is 1 millimeter.
MetafileFrameUnitGdi
Specifies that a unit is 0.01 millimeter. This element is provided for compatibility with GDI.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


MetafileType

The MetafileType enumeration specifies types of metafiles. The MetafileHeader::GetType method returns an element of this enumeration.

enum MetafileType{
  MetafileTypeInvalid,
  MetafileTypeWmf,
  MetafileTypeWmfPlaceable,
  MetafileTypeEmf,
  MetafileTypeEmfPlusOnly,
  MetafileTypeEmfPlusDual
};

Elements

MetafileTypeInvalid
Specifies a metafile format that is not recognized in GDI+.
MetafileTypeWmf
Specifies a WMF (Windows Metafile) file. Such a file contains only GDI records.
MetafileTypeWmfPlaceable
Specifies a WMF (Windows Metafile) file that has a placeable metafile header in front of it.
MetafileTypeEmf
Specifies an Enhanced Metafile (EMF) file. Such a file contains only GDI records.
MetafileTypeEmfPlusOnly
Specifies an EMF+ file. Such a file contains only GDI+ records and must be displayed by using GDI+. Displaying the records using GDI may cause unpredictable results.
MetafileTypeEmfPlusDual
Specifies an EMF+ Dual file. Such a file contains GDI+ records along with alternative GDI records and can be displayed by using either GDI or GDI+. Displaying the records using GDI may cause some quality degradation.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
GetType


PaletteFlags

The PaletteFlags enumeration indicates attributes of the color data in a palette.

enum PaletteFlags{
  PaletteFlagsHasAlpha  = 0x0001,
  PaletteFlagsGrayScale = 0x0002,
  PaletteFlagsHalftone  = 0x0004
};

Elements

PaletteFlagsHasAlpha
Indicates that one or more of the palette entries contains alpha (transparency) information.
PaletteFlagsGrayScale
Indicates that the palette contains only grayscale entries.
PaletteFlagsHalftone
Indicates that the palette is the Windows halftone palette.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspixelformats.h; include Gdiplus.h.


PathPointType

The PathPointType enumeration indicates point types and flags for the data points in a path. Bits 0 through 2 indicate the type of a point, and bits 3 through 7 hold a set of flags that specify attributes of a point. This enumeration is used by the GraphicsPath, GraphicsPathIterator, and PathData classes.

enum PathPointType{
  PathPointTypeStart        = 0,
  PathPointTypeLine         = 1,
  PathPointTypeBezier       = 3,
  PathPointTypePathTypeMask = 0x07,
  PathPointTypeDashMode     = 0x10,
  PathPointTypePathMarker   = 0x20,
  PathPointTypeCloseSubpath = 0x80,
  PathPointTypeBezier3 = 3,
};

Elements

PathPointTypeStart
Indicates that the point is the start of a figure.
PathPointTypeLine
Indicates that the point is one of the two endpoints of a line.
PathPointTypeBezier
Indicates that the point is an endpoint or control point of a cubic Bézier spline.
PathPointTypePathTypeMask
Masks all bits except for the three low-order bits, which indicate the point type.
PathPointTypePathMarker
Specifies that the point is a marker.
PathPointTypeCloseSubpath
Specifies that the point is the last point in a closed subpath (figure).
PathPointTypeBezier3
Indicates that the point is an endpoint or control point of a cubic Bézier spline.

Remarks

A GraphicsPath object has an array of points and an array of types. Each element in the array of types is a byte that specifies the point type and a set of flags for the corresponding element in the array of points.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
GraphicsPath, GraphicsPathIterator, PathData


PenAlignment

The PenAlignment enumeration specifies the alignment of a pen relative to the stroke that is being drawn.

enum PenAlignment{
  PenAlignmentCenter = 0,
  PenAlignmentInset  = 1,
};

Elements

PenAlignmentCenter
Specifies that the pen is aligned on the center of the line that is drawn.
PenAlignmentInset
Specifies, when drawing a polygon, that the pen is aligned on the inside of the edge of the polygon.

Remarks

If you set the alignment of a Pen object to PenAlignmentInset, you cannot use that pen to draw compound lines or triangular dash caps.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


PenType

The PenType enumeration indicates the type of pattern, texture, or gradient that a pen draws.

enum PenType{
  PenTypeSolidColor     = BrushTypeSolidColor,
  PenTypeHatchFill      = BrushTypeHatchFill,
  PenTypeTextureFill    = BrushTypeTextureFill,
  PenTypePathGradient   = BrushTypePathGradient,
  PenTypeLinearGradient = BrushTypeLinearGradient,
  PenTypeUnknown        = -1
};

Elements

PenTypeSolidColor
Indicates that the pen draws with a solid color.
PenTypeHatchFill
Indicates that the pen draws with a hatch pattern that is specified by a HatchBrush object.
PenTypeTextureFill
Indicates that the pen draws with a texture that is specified by a TextureBrush object.
PenTypePathGradient
Indicates that the pen draws with a color gradient that is specified by a PathGradientBrush object.
PenTypeLinearGradient
Indicates that the pen draws with a color gradient that is specified by a LinearGradientBrush object.
PenTypeUnknown
Indicates that the pen type is unknown.

Remarks

A pen's type is determined when the pen is constructed. For example, if you pass a HatchBrush object to a Pen constructor, then the pen that is constructed has a pen type of PenTypeHatchFill. If you pass a Color object or a SolidBrush object to a Pen constructor, then the pen that is constructed has a pen type of PenTypeSolidColor.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


PixelOffsetMode

The PixelOffsetMode enumeration specifies the pixel offset mode of a Graphics object. This enumeration is used by the GetPixelOffsetMode and SetPixelOffsetMode methods of the Graphics class.

enum PixelOffsetMode{
  PixelOffsetModeInvalid     = QualityModeInvalid,
  PixelOffsetModeDefault     = QualityModeDefault,
  PixelOffsetModeHighSpeed   = QualityModeLow,
  PixelOffsetModeHighQuality = QualityModeHigh,
  PixelOffsetModeNone,
  PixelOffsetModeHalf
};

Elements

PixelOffsetModeDefault
Equivalent to PixelOffsetModeNone.
PixelOffsetModeHighSpeed
Equivalent to PixelOffsetModeNone.
PixelOffsetModeHighQuality
Equivalent to PixelOffsetModeHalf.
PixelOffsetModeNone
Indicates that pixel centers have integer coordinates.
PixelOffsetModeHalf
Indicates that pixel centers have coordinates that are half way between integer values.

Remarks

Consider the pixel in the upper-left corner of an image with address (0, 0). With PixelOffsetModeNone, the pixel covers the area between –0.5 and 0.5 in both the x and y directions; that is, the pixel center is at (0, 0). With PixelOffsetModeHalf, the pixel covers the area between 0 and 1 in both the x and y directions; that is, the pixel center is at (0.5, 0.5).

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
GetPixelOffsetMode, SetPixelOffsetMode


RotateFlipType

The RotateFlipType enumeration specifies the direction of an image's rotation and the axis used to flip the image.

enum RotateFlipType{
  RotateNoneFlipNone = 0,
  Rotate90FlipNone = 1,
  Rotate180FlipNone = 2,
  Rotate270FlipNone = 3,
  RotateNoneFlipX = 4,
  Rotate90FlipX = 5,
  Rotate180FlipX = 6,
  Rotate270FlipX = 7,
  RotateNoneFlipY = Rotate180FlipX,
  Rotate90FlipY = Rotate270FlipX,
  Rotate180FlipY = RotateNoneFlipX,
  Rotate270FlipY = Rotate90FlipX,
  RotateNoneFlipXY = Rotate180FlipNone,
  Rotate90FlipXY = Rotate270FlipNone,
  Rotate180FlipXY = RotateNoneFlipNone,
  Rotate270FlipXY = Rotate90FlipNone
};

Elements

RotateNoneFlipNone
Specifies no rotation and no flipping.
Rotate90FlipNone
Specifies a 90-degree rotation without flipping.
Rotate180FlipNone
Specifies a 180-degree rotation without flipping.
Rotate270FlipNone
Specifies a 270-degree rotation without flipping.
RotateNoneFlipX
Specifies no rotation and a horizontal flip.
Rotate90FlipX
Specifies a 90-degree rotation followed by a horizontal flip.
Rotate180FlipX
Specifies a 180-degree rotation followed by a horizontal flip.
Rotate270FlipX
Specifies a 270-degree rotation followed by a horizontal flip.
RotateNoneFlipY
Specifies no rotation and a vertical flip.
Rotate90FlipY
Specifies a 90-degree rotation followed by a vertical flip.
Rotate180FlipY
Specifies a 180-degree rotation followed by a vertical flip.
Rotate270FlipY
Specifies a 270-degree rotation followed by a vertical flip.
RotateNoneFlipXY
Specifies no rotation, a horizontal flip, and then a vertical flip.
Rotate90FlipXY
Specifies a 90-degree rotation followed by a horizontal flip and then a vertical flip.
Rotate180FlipXY
Specifies a 180-degree rotation followed by a horizontal flip and then a vertical flip.
Rotate270FlipXY
Specifies a 270-degree rotation followed by a horizontal flip and then a vertical flip.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusimaging.h; include Gdiplus.h.


SmoothingMode

The SmoothingMode enumeration specifies whether smoothing (antialiasing) is applied to lines and curves. This enumeration is used by the GetSmoothingMode and SetSmoothingMode methods of the Graphics class.

enum SmoothingMode{
  SmoothingModeInvalid     = QualityModeInvalid,
  SmoothingModeDefault     = QualityModeDefault,
  SmoothingModeHighSpeed   = QualityModeLow,
  SmoothingModeHighQuality = QualityModeHigh,
  SmoothingModeNone,
  SmoothingModeAntiAlias
};

Elements

SmoothingModeDefault
Specifies that smoothing is not applied.
SmoothingModeHighSpeed
Specifies that smoothing is not applied.
SmoothingModeHighQuality
Specifies that smoothing is applied.
SmoothingModeNone
Specifies that smoothing is not applied.
SmoothingModeAntiAlias
Specifies that smoothing is applied.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
GetSmoothingMode, SetSmoothingMode


Status

The Status enumeration indicates the result of a GDI+ method call.

enum Status{
  Ok                = 0,
  GenericError      = 1,
  InvalidParameter  = 2,
  OutOfMemory       = 3,
  ObjectBusy        = 4,
  InsufficientBuffer = 5,
  NotImplemented     = 6,
  Win32Error         = 7,
  WrongState         = 8,
  Aborted            = 9,
  FileNotFound       = 10,
  ValueOverflow      = 11,
  AccessDenied       = 12,
  UnknownImageFormat = 13,
  FontFamilyNotFound = 14,
  FontStyleNotFound  = 15,
  NotTrueTypeFont    = 16,
  UnsupportedGdiplusVersion = 17,
  GdiplusNotInitialized     = 18,
  PropertyNotFound     = 19,
  PropertyNotSupported = 20
};

Elements

Ok
Indicates that the method call was successful.
GenericError
Indicates that there was an error on the method call, which is identified as something other than those defined by the other elements of this enumeration.
InvalidParameter
Indicates that one of the arguments passed to the method was not valid.
OutOfMemory
Indicates that the operating system is out of memory and could not allocate memory to process the method call. For an explanation of how constructors use the OutOfMemory status, see the Remarks section at the end of this topic.
ObjectBusy
Indicates that one of the arguments specified in the API call is already in use in another thread.
InsufficientBuffer
Indicates that a buffer specified as an argument in the API call is not large enough to hold the data to be received.
NotImplemented
Indicates that the method is not implemented.
Win32Error
Indicates that the method generated a Win32Error.
WrongState
Indicates that the object is in an invalid state to satisfy the API call. For example, calling GetColor from a pen that isn't a single, solid color results in a WrongState status.
Aborted
Indicates that the method was aborted.
FileNotFound
Indicates that the specified image file or metafile cannot be found.
ValueOverflow
Indicates that the method performed an arithmetic operation that produced a numeric overflow.
AccessDenied
Indicates that a write operation is not allowed on the specified file.
UnknownImageFormat
Indicates that the specified image file format is not known.
FontFamilyNotFound
Indicates that the specified font family cannot be found. Either the font family name is incorrect or the font family is not installed.
FontStyleNotFound
Indicates that the specified style is not available for the specified font family.
NotTrueTypeFont
Indicates that the font retrieved from an HDC or LOGFONT is not a TrueType font and cannot be used with GDI+.
UnsupportedGdiplusVersion
Indicates that the version of GDI+ that is installed on the system is incompatible with the version with which the application was compiled.
GdiplusNotInitialized
Indicates that the GDI+ API is not in an initialized state. To function, all GDI+ objects require that GDI+ be in an initialized state. Initialize GDI+ by calling GdiplusStartup.
PropertyNotFound
Indicates that the specified property does not exist in the image.
PropertyNotSupported
Indicates that the specified property is not supported by the format of the image and, therefore, cannot be set.

Remarks

If you construct a GDI+ object and then immediately call the GetLastStatus method of that object, you can determine whether the constructor succeeded or failed. In such cases, GetLastStatus might return OutOfMemory even though there was plenty of memory available to create the object. Several GDI+ constructors set the status to OutOfMemory when they fail regardless of the reason for failure.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplustypes.h; include Gdiplus.h.


StringAlignment

The StringAlignment enumeration specifies how a string is aligned in reference to the bounding rectangle. A bounding rectangle is used to define the area in which the text displays.

enum StringAlignment{
  StringAlignmentNear   = 0,
  StringAlignmentCenter = 1,
  StringAlignmentFar    = 2
};

Elements

StringAlignmentNear
Specifies that alignment is towards the origin of the bounding rectangle. May be used for alignment of characters along the line or for alignment of lines within the rectangle. For a right to left bounding rectangle (StringFormatFlagsDirectionRightToLeft), the origin is at the upper right.
StringAlignmentCenter
Specifies that alignment is centered between origin and extent (width) of the formatting rectangle.
StringAlignmentFar
Specifies that alignment is to the far extent (right side) of the formatting rectangle.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


StringDigitSubstitute

The StringDigitSubstitute enumeration specifies how to substitute digits in a string according to a user's locale or language.

enum StringDigitSubstitute{
  StringDigitSubstituteUser = 0,
  StringDigitSubstituteNone = 1,
  StringDigitSubstituteNational = 2,
  StringDigitSubstituteTraditional = 3
};

Elements

StringDigitSubstituteUser
Specifies a user-defined substitution scheme.
StringDigitSubstituteNone
Specifies to disable substitutions.
StringDigitSubstituteNational
Specifies substitution digits that correspond with the official national language of the user's locale.
StringDigitSubstituteTraditional
Specifies substitution digits that correspond with the user's native script or language, which may be different from the official national language of the user's locale.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


StringFormatFlags

The StringFormatFlags enumeration specifies text layout information (such as orientation and clipping) and display manipulations (such as ellipsis insertion, digit substitution, and representation of characters that are not supported by a font).

enum StringFormatFlags{
  StringFormatFlagsDirectionRightToLeft = 0x00000001,
  StringFormatFlagsDirectionVertical = 0x00000002,
  StringFormatFlagsNoFitBlackBox = 0x00000004,
  StringFormatFlagsDisplayFormatControl = 0x00000020,
  StringFormatFlagsNoFontFallback = 0x00000400,
  StringFormatFlagsMeasureTrailingSpaces = 0x00000800,
  StringFormatFlagsNoWrap = 0x00001000,
  StringFormatFlagsLineLimit = 0x00002000,
  StringFormatFlagsNoClip = 0x00004000
};

Elements

StringFormatFlagsDirectionRightToLeft
Specifies that reading order is right to left. For horizontal text, characters are read from right to left. For vertical text, columns are read from right to left. By default, horizontal or vertical text is read from left to right.
StringFormatFlagsDirectionVertical
Specifies that individual lines of text are drawn vertically on the display device. By default, lines of text are horizontal, each new line below the previous line.
StringFormatFlagsNoFitBlackBox
Specifies that parts of characters are allowed to overhang the string's layout rectangle. By default, characters are first aligned inside the rectangle's boundaries, then any characters which still overhang the boundaries are repositioned to avoid any overhang and thereby avoid affecting pixels outside the layout rectangle. An italic, lowercase letter F (f) is an example of a character that may have overhanging parts. Setting this flag ensures that the character aligns visually with the lines above and below but may cause parts of characters, which lie outside the layout rectangle, to be clipped or painted.
StringFormatFlagsDisplayFormatControl
Specifies that Unicode layout control characters are displayed with a representative character.
StringFormatFlagsNoFontFallback
Specifies that an alternate font is used for characters that are not supported in the requested font. By default, any missing characters are displayed with the "fonts missing" character, usually an open square.
StringFormatFlagsMeasureTrailingSpaces
Specifies that the space at the end of each line is included in a string measurement. By default, the boundary rectangle returned by the Graphics::MeasureString method excludes the space at the end of each line. Set this flag to include that space in the measurement.
StringFormatFlagsNoWrap
Specifies that the wrapping of text to the next line is disabled. NoWrap is implied when a point of origin is used instead of a layout rectangle. When drawing text within a rectangle, by default, text is broken at the last word boundary that is inside the rectangle's boundary and wrapped to the next line.
StringFormatFlagsLineLimit
Specifies that only entire lines are laid out in the layout rectangle. By default, layout continues until the end of the text or until no more lines are visible as a result of clipping, whichever comes first. The default settings allow the last line to be partially obscured by a layout rectangle that is not a whole multiple of the line height. To ensure that only whole lines are seen, set this flag and be careful to provide a layout rectangle at least as tall as the height of one line.
StringFormatFlagsNoClip
Specifies that characters overhanging the layout rectangle and text extending outside the layout rectangle are allowed to show. By default, all overhanging characters and text that extends outside the layout rectangle are clipped. Any trailing spaces (spaces that are at the end of a line) that extend outside the layout rectangle are clipped. Therefore, the setting of this flag will have an effect on a string measurement if trailing spaces are being included in the measurement. If clipping is enabled, trailing spaces that extend outside the layout rectangle are not included in the measurement. If clipping is disabled, all trailing spaces are included in the measurement, regardless of whether they are outside the layout rectangle.

Remarks

Multiple flags set can produce combined effects:

  • When both StringFormatFlagsDirectionVertical and StringFormatFlagsDirectionRightToLeft are set, individual lines of text are drawn vertically. The first line starts at the right edge of the layout rectangle; the second line of text is to the left of the first line, and so on.
  • When StringFormatFlagsDirectionVertical is set and StringFormatFlagsDirectionRightToLeft is not set, individual lines of text are drawn vertically. The first line starts at the left edge of the layout rectangle; the second line of text is to the right of the first line.
  • When StringFormatFlagsDirectionRightToLeft is set and StringFormatFlagsDirectionVertical is not set, the individual lines of text are horizontal and the reading order is from right to left. This setting does not change the order in which characters are displayed, it simply specifies the order in which characters can be read.

The StringFormatFlagsDirectionVertical and StringFormatFlagsDirectionRightToLeft flags can affect string alignment.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
SetFormatFlags, StringTrimming, StringAlignment, StringDigitSubstitute, DrawString Methods, MeasureString Methods
Tasks and Examples
Formatting Text


StringTrimming

The StringTrimming enumeration specifies how to trim characters from a string so that the string fits into a layout rectangle. The layout rectangle is used to position and size the display string.

enum StringTrimming{
  StringTrimmingNone      = 0,
  StringTrimmingCharacter = 1,
  StringTrimmingWord      = 2,
  StringTrimmingEllipsisCharacter = 3,
  StringTrimmingEllipsisWord      = 4,
  StringTrimmingEllipsisPath      = 5
};

Elements

StringTrimmingNone
Specifies that no trimming is done.
StringTrimmingCharacter
Specifies that the string is broken at the boundary of the last character that is inside the layout rectangle. This is the default.
StringTrimmingWord
Specifies that the string is broken at the boundary of the last word that is inside the layout rectangle.
StringTrimmingEllipsisCharacter
Specifies that the string is broken at the boundary of the last character that is inside the layout rectangle and an ellipsis (…) is inserted after the character.
StringTrimmingEllipsisWord
Specifies that the string is broken at the boundary of the last word that is inside the layout rectangle and an ellipsis (…) is inserted after the word.
StringTrimmingEllipsisPath
Specifies that the center is removed from the string and replaced by an ellipsis. The algorithm keeps as much of the last portion of the string as possible.

Remarks

Trimming affects only the last visible or partly visible (due to clipping) line of text.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
SetTrimming, StringFormatFlags, StringAlignment, StringDigitSubstitute, DrawString Methods, MeasureString Methods
Tasks and Examples
Formatting Text


TextRenderingHint

The TextRenderingHint enumeration specifies the process used to render text. The process affects the quality of the text.

enum TextRenderingHint{
  TextRenderingHintSystemDefault = 0,
  TextRenderingHintSingleBitPerPixelGridFit,
  TextRenderingHintSingleBitPerPixel,
  TextRenderingHintAntiAliasGridFit,
  TextRenderingHintAntiAlias,
  TextRenderingHintClearTypeGridFit
};

Elements

TextRenderingHintSystemDefault
Specifies that a character is drawn using the currently selected system font smoothing mode (also called a rendering hint).
TextRenderingHintSingleBitPerPixelGridFit
Specifies that a character is drawn using its glyph bitmap and hinting to improve character appearance on stems and curvature.
TextRenderingHintSingleBitPerPixel
Specifies that a character is drawn using its glyph bitmap and no hinting. This results in better performance at the expense of quality.
TextRenderingHintAntiAliasGridFit
Specifies that a character is drawn using its antialiased glyph bitmap and hinting. This results in much better quality due to antialiasing at a higher performance cost.
TextRenderingHintAntiAlias
Specifies that a character is drawn using its antialiased glyph bitmap and no hinting. Stem width differences may be noticeable because hinting is turned off.
TextRenderingHintClearTypeGridFit
Specifies that a character is drawn using its glyph ClearType bitmap and hinting. This type of text rendering cannot be used along with CompositingModeSourceCopy.

Windows XP and Windows .NET Server only: ClearType rendering is supported only on Windows XP and Windows .NET Server. Therefore, TextRenderingHintClearTypeGridFit is ignored on other operating systems even though GDI+ is supported on those operating systems.

Remarks

The quality associated with each process varies according to the circumstances. TextRenderingHintClearTypeGridFit provides the best quality for most LCD monitors and relatively small font sizes. TextRenderingHintAntiAlias provides the best quality for rotated text. Generally, a process that produces higher quality text is slower than a process that produces lower quality text.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.

See Also

Reference
CompositingMode, DrawString Methods, GetTextRenderingHint, SetTextRenderingHint
Tasks and Examples
Antialiasing with Text


Unit

The Unit enumeration specifies the unit of measure for a given data type.

enum Unit{
  UnitWorld,
  UnitDisplay,
  UnitPixel,
  UnitPoint,
  UnitInch,
  UnitDocument,
  UnitMillimeter
};

Elements

UnitWorld
Specifies world coordinates, a nonphysical unit.
UnitDisplay
Specifies display units. For example, if the display device is a monitor, then the unit is 1 pixel.
UnitPixel
Specifies that a unit is 1 pixel.
UnitPoint
Specifies that a unit is 1 point or 1/72 inch.
UnitInch
Specifies that a unit is 1 inch.
UnitDocument
Specifies that a unit is 1/300 inch.
UnitMillimeter
Specifies that a unit is 1 millimeter.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


WarpMode

The WarpMode enumeration specifies warp modes that can be used to transform images.

enum WarpMode{
  WarpModePerspective,
  WarpModeBilinear
};

Elements

WarpModePerspective
Specifies the perspective warp mode.
WarpModeBilinear
Specifies the bilinear warp mode.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


WrapMode

The WrapMode enumeration specifies how repeated copies of an image are used to tile an area.

enum WrapMode{
  WrapModeTile,
  WrapModeTileFlipX,
  WrapModeTileFlipY,
  WrapModeTileFlipXY,
  WrapModeClamp
};

Elements

WrapModeTile
Specifies tiling without flipping.
WrapModeTileFlipX
Species that tiles are flipped horizontally as you move from one tile to the next in a row.
WrapModeTileFlipY
Specifies that tiles are flipped vertically as you move from one tile to the next in a column.
WrapModeTileFlipXY
Specifies that tiles are flipped horizontally as you move along a row and flipped vertically as you move along a column.
WrapModeClamp
Specifies that no tiling takes place.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusenums.h; include Gdiplus.h.


Structures

GDI+ defines the following structures:

  • ColorMap
  • ColorMatrix
  • ColorPalette
  • ENHMETAHEADER3
  • GdiplusStartupInput
  • GdiplusStartupOutput
  • PWMFRect16
  • WmfPlaceableFileHeader


ColorMap

The ColorMap structure contains two Color objects. Several methods of the ImageAttributes class adjust image colors by using a color remap table, which is an array of ColorMap structures.

struct ColorMap{
  Color  oldColor;
  Color  newColor;
};

Data Members

oldColor
The original color.
newColor
The new color.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolormatrix.h; include Gdiplus.h.

See Also

Reference
Color, ImageAttributes
Tasks and Examples
Using a Color Remap Table


ColorMatrix

The ColorMatrix structure contains a 5×5 matrix of real numbers. Several methods of the ImageAttributes class adjust image colors by using a color matrix.

struct ColorMatrix{
  REAL  m[5][5];
};

Data Members

m
5×5 array of real numbers.

Remarks

A 5×5 color matrix is a homogeneous matrix for a 4-space transformation. The element in the fifth row and fifth column of a 5×5 homogeneous matrix must be 1, and all of the other elements in the fifth column must be 0. Color matrices are used to transform color vectors. The first four components of a color vector hold the red, green, blue, and alpha components (in that order) of a color. The fifth component of a color vector is always 1.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluscolormatrix.h; include Gdiplus.h.

See Also

Reference
Color, ImageAttributes
Tasks and Examples
Recoloring


ColorPalette

The ColorPalette structure defines an array of colors that make up a color palette. The colors are 32-bit ARGB colors.

struct ColorPalette{
  UINT  Flags;
  UINT  Count;
  ARGB  Entries[1];
};

Data Members

Flags
Combination of flags from the PaletteFlags enumeration.
Count
Number of elements in the Entries array.
Entries
Array of ARGB colors.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdipluspixelformats.h; include Gdiplus.h.

See Also

Reference
Color, GetPalette, SetPalette
Concepts
Types of Bitmaps


ENHMETAHEADER3

The ENHMETAHEADER3 structure contains enhanced-metafile data including the dimensions of the metafile image, the number of records in the metafile, and the resolution of the device on which the metafile was created.

typedef struct
{
  DWORD   iType;
  DWORD   nSize;
  RECTL   rclBounds;
  RECTL   rclFrame;
  DWORD   dSignature;
  DWORD   nVersion;
  DWORD   nBytes;
  DWORD   nRecords;
  WORD    nHandles;
  WORD    sReserved;
  DWORD   nDescription;
  DWORD   offDescription;
  DWORD   nPalEntries;
  SIZEL   szlDevice;
  SIZEL   szlMillimeters;
} ENHMETAHEADER3;

Data Members

iType
Record type. Value is always EMR_HEADER.
nSize
Structure size, in bytes. This may be greater than the value returned by sizeof(ENHMETAHEADER3).
rclBounds
Bounding rectangle, in device units, for the image stored in the metafile.
rclFrame
Rectangle, in 0.01 millimeter units, that surrounds the image stored in the metafile.
dSignature
Must be ENHMETA_SIGNATURE.
nVersion
Version number of the metafile format. The current version is 0x10000.
nBytes
Size, in bytes, of the metafile.
nRecords
Number of records in the metafile.
nHandles
Number of handles in the metafile handle table. Handle index zero is reserved.
sReserved
Reserved. Must be zero.
nDescription
Number of characters in the string that contains the description of the metafile's contents. This member is 0 if the metafile does not have a description string.
offDescription
Offset from the beginning of the ENHMETAHEADER3 structure to the string that contains the description of the metafile's contents. This member is 0 if the metafile does not have a description string.
nPalEntries
Number of entries in the metafile palette.
szlDevice
Resolution, in pixels, of the reference device.
szlMillimeters
Resolution, in millimeters, of the reference device.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.


GdiplusStartupInput

The GdiplusStartupInput structure holds a block of arguments that are required by the GdiplusStartup function.

struct GdiplusStartupInput
{
  UINT32 GdiplusVersion;             // Must be 1
  DebugEventProc DebugEventCallback; // Ignored on free builds
  BOOL SuppressBackgroundThread;     // FALSE unless you're prepared to call
                                     // the hook/unhook functions properly
  BOOL SuppressExternalCodecs;       // FALSE unless you want GDI+ only to
                                     // use its internal image codecs

  GdiplusStartupInput(
    DebugEventProc debugEventCallback = NULL,
    BOOL suppressBackgroundThread = FALSE,
    BOOL suppressExternalCodecs = FALSE)
  {
    GdiplusVersion = 1;
    DebugEventCallback = debugEventCallback;
    SuppressBackgroundThread = suppressBackgroundThread;
    SuppressExternalCodecs = suppressExternalCodecs;
  }
};

typedef VOID (WINAPI *DebugEventProc)(DebugEventLevel level, CHAR *message);

Data Members

GdiplusVersion
Specifies the version of GDI+. Must be 1.
DebugEventCallback
Pointer to a callback function that GDI+ can call, on debug builds, for assertions and warnings. The default value is NULL.
SuppressBackgroundThread
Boolean value that specifies whether to suppress the GDI+ background thread. If you set this member to TRUE, GdiplusStartup returns (in its output parameter) a pointer to a hook function and a pointer to an unhook function. You must call those functions appropriately to replace the background thread. If you do not want to be responsible for calling the hook and unhook functions, set this member to FALSE. The default value is FALSE.
SuppressExternalCodecs
Boolean value that specifies whether you want GDI+ to suppress external image codecs. GDI+ version 1.0 does not support external image codecs, so this parameter is ignored.

Remarks

The GdiplusStartupInput structure provides a constructor that sets the GdiplusVersion member to 1 and allows you to specify values for the other three members. All of the constructor parameters are optional, so you can declare a variable of type GdiplusStartupInput without passing any arguments to the constructor, and all of the members will be initialized with appropriate default values.

If you set the SuppressBackgroundThread member of the GdiplusStartup input parameter to TRUE, you must call the hook and unhook functions returned in the output parameter. Call those functions before and after the application's main message loop; that is, a message loop that is active for the lifetime of GDI+. Call the hook function before the loop starts, and call the unhook function after the loop ends.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusinit.h; include Gdiplus.h.

See Also

Reference
GdiplusShutdown, GdiplusStartup, GdiplusStartupOutput
Tasks and Examples
Getting Started


GdiplusStartupOutput

The GdiplusStartup function uses the GdiplusStartupOutput structure to return (in its output parameter) a pointer to a hook function and a pointer to an unhook function. If you set the SuppressBackgroundThread member of the input parameter to TRUE, then you are responsible for calling those functions to replace the GDI+ background thread.

Call the hook and unhook functions before and after the application's main message loop; that is, a message loop that is active for the lifetime of GDI+. Call the hook function before the loop starts, and call the unhook function after the loop ends.

If you do not want to be responsible for calling the hook and unhook functions, set the SuppressBackgroundThread member of the input parameter (passed to GdiplusStartup) to FALSE.

struct GdiplusStartupOutput
{
  NotificationHookProc NotificationHook;
  NotificationUnhookProc NotificationUnhook;
};

typedef Status (WINAPI *NotificationHookProc)(OUT ULONG_PTR *token);

typedef VOID (WINAPI *NotificationUnhookProc)(ULONG_PTR token);

Data Members

NotificationHook
Receives a pointer to a hook function.
NotificationUnhook
Receives a pointer to an unhook function.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusinit.h; include Gdiplus.h.

See Also

Reference
GdiplusShutdown, GdiplusStartup, GdiplusStartupInput
Tasks and Examples
Getting Started


PWMFRect16

The PWMFRect16 structure defines a rectangle that bounds a placeable metafile. The rectangle defines the size and position of the metafile.

typedef struct
{
  INT16  Left;
  INT16  Top;
  INT16  Right;
  INT16  Bottom;
} PWMFRect16;

Data Members

Left
Left coordinate of the rectangle that bounds the metafile.
Top
Top coordinate of the rectangle that bounds the metafile.
Right
Right coordinate of the rectangle that bounds the metafile.
Bottom
Bottom coordinate of the rectangle that bounds the metafile.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
WmfPlaceableFileHeader


WmfPlaceableFileHeader

The WmfPlaceableFileHeader structure defines the fields of a placeable metafile header. Placeable metafiles were created as a way of specifying how a metafile is mapped and scaled on a display device.

typedef struct
{
  UINT32      Key;          // GDIP_WMF_PLACEABLEKEY
  INT16       Hmf;          // Metafile handle number (always 0)
  PWMFRect16  BoundingBox;  // Coordinates in metafile units
  INT16       Inch;         // Number of metafile units per inch
  UINT32      Reserved;     // Reserved (always 0)
  INT16       Checksum;     // Checksum value for previous 10 WORDs
} WmfPlaceableFileHeader;

Data Members

Key
Identification value that indicates the presence of a placeable metafile header. This value is always 0x9AC6CDD7.
Hmf
Handle to the metafile in memory. When written to disk, this field is not used and will always contains the value 0.
BoundingBox
Destination rectangle, measured in twips, for displaying the metafile.
Inch
Number of twips per inch used to represent the image.

Normally, there are 1440 twips per inch; however, this number can be changed to scale the image.

  • A value of 720 specifies that the image is twice its normal size.
  • A value of 360 specifies that the image is four times its normal size.
  • A value of 2880 specifies that the image is half its normal size.
Reserved
Not used and is always set to 0.
Checksum
Checksum for the previous 10 WORDs in the header. This value can be used to determine whether the metafile has become corrupted.

Remarks

Although placeable metafiles are quite common, they are not directly supported by the Windows API. To display a placeable metafile using the Windows API, you must first strip the placeable metafile header from the file. This is typically performed by copying the metafile to a temporary file starting at file offset 22 (0x16). This is because each placeable metafile begins with a 22-byte header that is followed by a standard metafile.

Requirements

Windows NT/2000/XP: Included in Windows XP and Windows .NET Server.
Redistributable: Requires GDI+ on Windows NT 4.0 SP6; Windows 2000; and Windows 98/Me.
Header: Declared in Gdiplusmetaheader.h; include Gdiplus.h.

See Also

Reference
PWMFRect16


Topic Not Found

The requested topic was not found. The following are possible causes and solutions.

  • Problem: You are using a local installation, but you did not install the component that contains this topic.

    Solution: Install the complete SDK documentation from the latest MSDN Library or SDK CD. If you do not have a CD, a low-cost SDK CD is available from the Developer Store at the following locations:

    U.S.
    International

    The latest SDK documentation is also available for download from http://www.microsoft.com/msdownload/platformsdk/sdkupdate/.

  • Problem: You are using the documentation directly from the MSDN Library CD and the disc is not in the drive.

    Solution: Insert the MSDN Library CD into the drive.