GDI + learning record

Introduction to GDI +:

GDI (Graphics Device Interface), a set of API interfaces provided by Windows for image rendering.

GDI + is an optimized version of GDI, which is easier for developers to use.

usage method:

	
	/*GDI+ Header file*/
	#include <objidl.h>
	#include <gdiplus.h>
	/*The system is provided in the form of GdiPlus. dll, and the lib static file needs to be protected*/
	using namespace GdiPlus;
	#pragma Comment(lib,"Gdiplus.lib")
	
	//perhaps
	/*The header file already contains two files and links the Gdiplus.lib static file*/
	#include <atlimage.h>
	using namespace Gdiplus;




	/*You must initialize before using GDI*/
	GdiplusStartupInput gdiplusStartupInput;
	ULONG_PTR gdiplusToken;
	GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);
	
	..........
	..........
	..........


	//Close GDI after the program ends+
	GdiplusShutdown(gdiplusToken);

Graphics class

Graphics class is the core class in GDI+ API. It provides many member functions for drawing lines, curves, images, images and strings.

Graphics class is generally used in conjunction with Pen, font, SoildBrush and other classes.

void Graphics(IN HDC hdc)
It is constructed by a device context for drawing in the window

void Graphics(IN Image* image)
Through a Image Class object to draw an image

Drawing functions in Graphics class:

Member functionFunction function
DrawLineDraw first function
DrawLinesDraw polyline function
DrawRectangleDraw folded rectangle
DrawRectanglesDraw multiple rectangles
DrawEllipseDraw an ellipse
DrawArcarc
DrawStringDraw string
DrawPolygonDraw a closed polygonal area
DrawPieDraw a pie chart
FillRectangleFill rectangular area
FillEllipseFill ellipse
FillPolygonFill polygon
MeasureStringMeasure string height and width
DrawIamgeDraw pictures (PNG,BMPJPG)
TranslateTransformTranslation transformation
ResetTransfromCancel transformation
ScaleTransformScale transform
RotateTransformRotation transformation

For more information, please move to Microsoft GDI + documentation

Graphics class draw solid lines

//The brush determines the color and thickness, and two points determine a line
//Draw line function
Status DrawLine(IN const Pen* pen, //Brush object
                IN REAL x1, // Starting point X coordinate
                IN REAL y1, // Y coordinate of starting point
                IN REAL x2, // End X coordinate
                IN REAL y2) // End point Y coordinate


//Draw polyline function
//Multiple points confirm polyline
    Status DrawLines(IN const Pen* pen,		//Brush object
                     IN const Point* points,  	//Coordinate array
                     IN INT count)		//Length of coordinate array

//pen object
//pen class is the brush class of GDI +

    Pen(IN const Color& color,  IN REAL width = 1.0f);
	/*Specify a brush by a color and width*/
 
    Pen(IN const Brush* brush,  IN REAL width = 1.0f);
	/*Know a brush by a brush and width*/

//Color color class
   Color(IN BYTE r,IN BYTE g,IN BYTE b;
	/*Specify a color by, R value, G value, B value*/
   Color(IN BYTE a, IN BYTE r, IN BYTE g,IN BYTE b);
   /*Specify a color through a transparency, R value, G value, B value*/
//PointF class
Pointf(REAL x,REAL y);
/*Construct a coordinate point with x,y values*/
Pointf(const SizeF &size)
/*Construct a coordinate point through the SizeF value*/
//Status class
enum Status
{
	OK,
	GenericError,
	InvalidParameter,
	OutOfMemory,
	ObjectBusy,
	InsufficientBuffer,
	NotImplemented,
	......
	ProfileNotFound
};

The Graphics class draws dashed lines and arrow lines

  • Draw a dotted line
    Pen class provides SetDashStyle member method function to set brush style
Status SetDashStyle(IN DashStyle dasgStyle);
enum DashStyle
{
	DashStyleSolid,		//Solid line
	DashStyleDash,		//A straight line consisting of line segments
	DashStyleDot,		//A straight line consisting of points
	DashStyleDashDot,	//A straight line formed by dashes
	DashStyleDashDotDot,	//The dash dot pattern forms a straight line
	DashStyleCustom		//custom
};
  • Draw a line with an arrow
    The SetStartCap and SetEndCap methods of the Pen class specify the representation of the end of the line; the line cap can be flat, square, rounded, triangular or user-defined
//Set line start point
Status SetStartCap(IN LineCap startCap)

//Set line end point
Status SetEndCap(IN LineCap endCap);

//Set line middle
Status SetDashCap(IN DashCap dashCap);

enum LineCap
{
	LineCapFlat = 0,
	LineCapSquare = 1,
	LineCapRound = 2,
	LineCapTriangle = 3,

	LineCapNoAnchor = 0x10, //nothing
	LineCapSquareAnchor = 0x11, //square
	LineCapRounAnchor = 0x12	//fillet
	LineCapDiamondAnchor = 0x13, //Diamonds
	LineCapArrowAnchor	= 0x14,	  //arrow
	
	LineCapCustom  = 0xff, custom cap
	LineCapAnchorMask = 0xf0
};

enum DashCap
{
	DashCapFlat = 0, 	//nothing
	DashCapRound = 2,	//fillet
	DashCapTriangle	= 3  //triangle
};

The Graphics class draws a rectangle

  • Draw rectangle
//The brush determines the thickness and color, and two points + length and width determine the rectangle
Status DrawRectangle(IN const Pen *pen,	//Brush object
IN REAL x,	//Starting point x coordinate
IN REAL y,  //Starting point y coordinate
IN REAL  width,  //wide
IN REAL  height	 //high
);

The brush determines the thickness and color,Rectangular coordinates determine the shape
Status DrawRectangle(IN const Pen *pen,	//Brush object
IN const Rect & rect	//Rectangular coordinates
);
  • Draw multiple rectangles
 Status DrawRectangles(IN const Pen *pen,	//Brush object
IN const Rect & rects, 		//Rectangular coordinate array
IN INT count	// Number of rectangles);
  • Rect class
 class Rect
 {	
 	.....
 	INt X;	//Starting point x coordinate
 	INT Y;	//Starting point y coordinate
 	INT Width;	//wide
 	INT Height;	 //high
 }

Graphics class draws circles and arcs

  • Draw a circle
//The brush determines the color and thickness, and the circumscribed circle coordinates determine the ellipse
 Status DrawEllipse(
 IN const Pen *pen, 	//Brush object
 IN REAL x,		//Starting point x coordinate
 IN REAL y,		//Starting point y coordinate
 IN REAL width,	//wide
 IN REAL height	//high
 );
 
//The brush determines the color and thickness, and the circumscribed circle coordinates determine the ellipse
 Status DrawEllipse(
 IN const Pen *pen, 	//Brush object
 IN Rect & rect 		//Rectangular coordinates
 );
  • arc
//The brush determines the color and thickness, and the circumscribed rectangle determines the ellipse
 Status DrawArc(
IN const Pen *pen,		//Brush object
IN REAL x,					//Starting point x coordinate
IN REAL y,					//Starting point y coordinate
IN REAL width,			//wide
IN REAL height,			//high
IN REAL startAngle,	//Start angle
IN REAL sweepAngle	//arc angle 
)

//The brush determines the color and thickness, and the circumscribed rectangle and angle determine the arc
 Status DrawArc(
IN const Pen *pen,		//Brush object
IN const Rect &rect,	//Inscribed rectangle
IN REAL startAngle,	//Start angle
IN REAL sweepAngle	//arc angle 
)

Graphics class anti aliasing

  • Anti aliasing
    The member functions of the Graphics class provide anti aliasing
    Status SetSmoothingMode(
    In smoothingmode / / smoothing mode
    )

  • SmoothingMode type

 enum SmoothingMode
 {
 	SmoothingModeInvalid = QualityModeInvalid,	//Invalid mode
 	SmoothingModeDefault = QualityModeDefault,		//default
 	SmoothingModeHighspeed = QualityModeLow,		//High speed, low quality
 	SmoothingModeHightQuality = QualityModeHight,	//High quality, low speed
 	SmoothingModeNone,	//Not eliminate
 	SmoothingModeAntiAlias, 	//Anti aliasing
 }

Graphics class drawing polygons

  • draw a polygon
 //The brush determines the color and thickness, and multiple points are connected to form a polygon
 Status DrawPolygon(
IN const Pen *pen,		//paint brush
IN const PointF *points, //Array of points
IN INT count	//Number of points
);
  • Fill polygon
//The brush determines the fill color, and multiple points are connected to form a polygon
Status FillPolygon(
IN Brush *brush,	//Brush
IN const PointF *points, 	//Array of points
IN INT count	//Number of points
)

Graphics class pie chart

  • Draw pie chart
//The brush determines the color and thickness, the circumscribed rectangle determines the circle, and the start and angle determine the pie chart
Status DrawPie(
IN const Pen *pen,	//Brush object
IN const RectF &rect,	//Circumscribed rectangle of circle
IN REAL	startAngle,		//Start angle
IN REAL sweepAngle		//Rotation angle
)
  • Filling pie chart
//The brush determines the fill color, and multiple points are connected to form a polygon
Status FillPie(
IN const Brush *brush,		//Brush
IN const RectF & rect,		//Circumscribed rectangle of circle
IN REAL	 startAngle,		//Starting angle
IN REAL  sweepAngle			//Rotation angle
)

Fill the drawing with a solid brush

  • Brush class

The brush class is an abstract base class that defines brushes. Brush objects are used to fill graphics (rectangles, ellipses, pie charts, etc.)

  • SolidBrush class
    The SolidBrush class defines a solid color Brush, which is inherited from the Brush class. It is used to fill the interior of a graphic shape and use a color to construct the Brush

  • Fill rectangle

//Brush fill color, rectangle determines position
Status FillRecangle
{
IN const Brush *brush,	//Brush
IN const RectF &rect,	rectangle
};
  • Fill ellipse
//Brush fill color, circumscribe rectangle to determine the position of fill ellipse
Status FillEllipse(
IN const Brush *brush,	//Brush
IN const RectF &rect
);
  • Fill polygon
 //The brush is filled with color, and multiple points are connected to form a polygon
 Status FillPolygon(
IN	const Brush *brush,		//Brush
IN	const PointF *POINTS,	//Array of points
IN	INT	count		//Number of points
)

Fill with gradient brush

  • LinearGradientBrush class

The LinearGradientBrush class defines a brush that draws a color gradient

  • LinearGradientBrush construction
 			//Start, end, start color, end color
  LinearGradientBrush(Point &,Point &,Color &,Color&);

LinearGradientBrush (
IN const Rect &rect,	//The upper left corner of the rectangle determines the starting point and the lower right corner determines the end point
IN const Color &color1,//Start color
IN const Color &color2,//End color
IN REAL angle,	//angle
IN BOOL	isAngleScalable	//Specifies whether the angle is telescopic
);

The Graphics class draws text

  • Draw text
//The brush determines the color, the Font determines the Font, and the rectangle determines the range
Status	DrawString(
IN const WCHAR *string,	//text
IN INT	length,		//Text length
IN const Font	*font, //Font object
IN const PointF &origin, //Text start point
IN const Brush	*brush	 //TBrush Object 
)

//The brush determines the color, the Font determines the Font, and the rectangle determines the range
Status	DrawString(
IN const WCHAR *string,	//text
IN INT	length,		//Text length
IN const Font	*font, //Font object
IN const PointF &origin, //Text start point
IN const StringFormat *stringFormat,//Alignment
IN const Brush	*brush	 //TBrush Object 
)
  • Font class
class Font : public GdiplusBase
{
public:
    friend class Graphics;
        Font(
        IN const WCHAR *           familyName, //font name
        IN REAL                    emSize, //font size
        IN INT                     style   = FontStyleRegular,
        IN Unit                    unit    = UnitPoint,
        IN const FontCollection *  fontCollection = NULL
    );

Graphics class measurement string

  • Measurement string
 //The brush determines the fill color and the rectangle determines the fill position
 Status MeasureString(
IN const WCHAR *string,		//Measured string
IN INT lenght,	//Length of string
IN const Font 	*font,  //typeface
IN const PointF &origin,//Starting point coordinates
OUT RectF  *boundingBox //Measured boundary
)

Graphics class drawing pictures

  • Draw picture
    Drawing image objects
Status DrawImage(
IN Image *image,	//Image object to draw
IN const PointF &point	//The upper left corner of the drawing
)

```cpp
//Draw the image object x,y without drawing the starting point, width and height. Specify the height to draw (scalable image)
Status Drawimage(
IN Image	*image,	//Image object to draw
IN REAL x,	//The x coordinate of the starting point of the drawing
IN REAL y,  //Start y coordinate of drawing
IN REAL width,	//Drawn width
IN REAL height  //Drawn height
)
Member functionFunction function
FromFileCreate an Image object from a file
FromStreamCreating an image object from a stream
GetHeightGets the height of the image
GetwidthGets the width of the image
SaveSave picture object to file

Graphics class crop and zoom pictures

  • Crop picture
//Draws a portion of the image object to the specified starting point area
Status DrawImage(
IN Image *image,	//Image object to draw
IN INT x,		//The x coordinate drawn to the window
IN INT y,		//The y coordinate drawn to the window
IN INT srcx,	//Intercept from the starting x coordinate in the upper left corner of the original image
IN INT srcy,	//Start from the y coordinate at the upper left corner of the original image
IN INT srcwidth,	//Intercepted image width
IN INT srcheight,	//Intercepted image height
IN Unit srcUnit,	//Draw the image in pixels
)
  • Clipping and scaling
Status DrawImage(
IN Image *image,	//Image object to draw
IN const Rect & destRect,	//Draws to a rectangular area of the window
IN INT srcx,	//Intercept from the starting x coordinate in the upper left corner of the original image
IN INT srcy,	//Start from the y coordinate at the upper left corner of the original image
IN INT srcwidth,	//Intercepted image width
IN INT srcheight,	//Intercepted image height
IN Unit srcUnit,	//Draw the image in pixels
)

)

The Graphics class sets the scaling interpolation algorithm

  • Set interpolation mode
    Set the interpolation mode of this image object. The interpolation mode determines the algorithm used for image scaling or rotation.
Status	 SetinterpolationMode(
IN interpolationMode interpolationMode	//Interpolation mode
)
  • Interpolation algorithm
//Among them, the effect of interpolationmodequalitybic is the best and the consumption of system resources is the largest

enum InterpolationMode
{
	InterpolationModeInvalid,	//Invalid interpolation
	InterpolationModeDefault,	//Specify default mode
	InterpolationModeLowQuality,	//Specify low quality interpolation
	InterpolationModeHeightQuality,	//Specify high quality interpolation
	InterpolationModeBilinear,		//Specify bilinear interpolation
	InterpolationModeBilcubic,		//Specify bicubic interpolation
	InterpolationModeNearestNeighthbor,	//Specifies the nearest neighbor interpolation method
	InterpolationModeHightQualityBilinear,	//Specifies high quality bilinear interpolation
	InterpolationModeHightQualityBilcubic,	//Specifies high quality bicubic interpolation
}

Graphics class rotates and distorts pictures

  • Distorted picture
 //The image object can rotate, emit, and distort the image by specifying the coordinates of the upper left, lower right, and lower left corners of the original image
 
 Status DrawImage(
 IN Image *image,	//Image object to draw
 IN const Point,	//destPoints, 	// Array of points
 IN count,		//Number of point groups
);

Translation transformation with Graphics

  • Translation transformation
//Change the world transformation matrix using the product of itself and the translation matrix
Status TranslateTransform(
	IN REAL dx,		//Horizontal component of translation
	IN REAL dy,		//Vertical component of translation
	IN MatrixOrder order = matrixOrderPrepend
)
  • Reset translation transform
Set the world conversion matrix to the identity matrix,The identity matrix represents a transformation that does nothing.

Status ResetTransform();

Graphics for scaling transformation

  • Scale transform
//Change the world transformation matrix using the product of itself and the translation matrix
Status ScaleTransform(
   IN REAL sx,		//Horizontal component of translation
   IN REAL sy,		//Vertical component of translation
   IN MatrixOrder order = matrixOrderPrepend
)

Graphics for rotation transformation

  • Rotation transformation
//Change the world transformation matrix using the product of itself and the translation matrix
Status RotateTransform(
   IN REAL angle,		//Rotation angle
   IN MatrixOrder order = matrixOrderPrepend
)

Double buffer drawing of GDI +

  • Double buffer technology
    The double buffer principle can be understood vividly as: regard the computer screen as a blackboard. First, we establish a "virtual" blackboard in the memory environment, and then draw complex graphics on the blackboard. After all the graphics are drawn, we can "copy" the drawn graphics on the blackboard (in memory) to the computer screen at one time, which can greatly improve the drawing speed.

  • Double buffer implementation steps

  • Use Bitmap to create a memory Bitmap. The size of the Bitmap is consistent with the window area for easy copying. It is equivalent to GDI's CreateCompatbleBitmap.

  • Create a memory Graphics object using Graphics::FormImage, which is equivalent to the CreateCompatibleDC of GDI.

  • Use the Graphics object member functions (DrawEllipse,DrawImage, etc.) to draw various Graphics on the memory bitmap

  • Use Drawimage to draw the memory bitmap onto the window at one time

GDI + capture desktop pictures

  • Screen capture using GDI +
  • Gets the device context of the desktop
HDC hsrDC = CreateDC(TEXT("DISPLAY"),NULL,NULL,NULL)
or:
HDC GetWindowDC(HWND hWnd) //Full screen when handle is not NULL
  • Creates a memory device context environment compatible with the specified device
HDC = hMemDc = CreateCompatibleDC(hsrDC);
  • Create a memory compatible bitmap with a screen size for the memory compatible DC.
//Get screen size
int SX = GetSystemMetrics(SM_CXSCREEN);
int SY = GetSystemMetrics(SM_CYSCREEN)
HBITMAP hBitmap = CreateCompatibleBitmap(hsrDC,SX,SY);
  • Select memory bitmap into memory compatible DC
SelectObject(hMemDc,hBitmap);
  • Copy the contents of the DC of the window to the memory compatible DC, and the image will naturally be drawn to the memory compatible bitmap
BitBlt(hMenDc,0,0,SX,SY,hsrDC,0,0,SRCCOPY);
  • Convert HBITMAP to GDI + Bitmap and use
Bitmap bmp(hBitmap,NULL);

Code engineering:

Keywords: C++ Windows

Added by notaloser on Fri, 15 Oct 2021 06:21:16 +0300