1. Trang chủ
  2. » Công Nghệ Thông Tin

gdi programming with c sharp phần 3 docx

70 681 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 70
Dung lượng 4,73 MB

Nội dung

FillRegion fills a specified region with a brush. This method takes a brush and a region as input parameters. Listing 3.29 creates a Region object from a rectangle and calls FillRegion to fill the region. Listing 3.29 Filling regions Rectangle rect = new Rectangle(20, 20, 150, 100); Region rgn = new Region(rect); e.Graphics.FillRegion(new SolidBrush(Color.Green) , rgn); Note Chapter 6 discusses rectangles and regions in more detail. 3.2.3 Miscellaneous Graphics Class Methods The Graphics class provides more than just draw and fill methods. Miscellaneous methods are defined in Table 3.6. Some of these methods are discussed in more detail later. 3.2.3.1 The Clear Method The Clear method clears the entire drawing surface and fills it with the specified background color. It takes one argument, of type Color. To clear a form, an application passes the form's background color. The following code snippet uses the Clear method to clear a form. form.Graphics g = this.CreateGraphics(); g.Clear(this.BackColor); g.Dispose(); This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. Table 3.6. Some miscellaneous Graphics methods MethodDescription AddMetafileComment Adds a comment to a Metafile object. Clear Clears the entire drawing surface and fills it with the specified background color. ExcludeClip Updates the clip region to exclude the area specified by a Rectangle structure. Flush Forces execution of all pending graphics operations and returns immediately without waiting for the operations to finish. FromHdc Creates a new Graphics object from a device context handle. FromHwnd Creates a new Graphics object from a window handle. FromImage Creates a new Graphics object from an Image object. GetHalftonePalette Returns a handle to the current Windows halftone palette. GetHdc Returns the device context handle associated with a Graphics object. GetNearestColor Returns the nearest color to the specified Color structure. IntersectClip Updates the clip region of a Graphics object to the intersection of the current clip region and a Rectangle structure. IsVisible Returns true if a point is within the visible clip region. MeasureCharacterRanges Returns an array of Region objects, each of which bounds a range of character positions within a string. MeasureString Measures a string when drawn with the specified Font object. MultiplyTransform Multiplies the world transformation and the Matrix object. ReleaseHdc Releases a device context handle obtained by a previous call to the GetHdc method. ResetClip Resets the clip region to an infinite region. ResetTransform Resets the world transformation matrix to the identity matrix. Restore Restores the state of a Graphics object to the state represented by a GraphicsState object. Takes GraphicsState as input, removes the information block from the stack, and restores the Graphics object to the state it was in when it was saved. RotateTransform Applies rotation to the transformation matrix. Save Saves the information block of a Graphics object. The information block stores the state of the Graphics object. The Save method returns a GraphicsState object that identifies the information block. ScaleTransform Applies the specified scaling operation to the transformation matrix. SetClip Sets the clipping region to the Clip property. TransformPoints Transforms an array of points from one coordinate space to another using the current world and page transformations. TranslateClip Translates the clipping region by specified amounts in the horizontal and vertical directions. TranslateTransform Prepends the specified translation to the transformation matrix. This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. 3.2.3.2 The MeasureString Method MeasureString measures a string when it is drawn with a Font object and returns the size of the string as a SizeF object. You can use SizeF to find out the height and width of string. MeasureString can also be used to find the total number of characters and lines in a string. It has seven overloaded methods. It takes two required parameters: the string and font to measure. Optional parameters you can pass include the width of the string in pixels, maximum layout area of the text, string format, and combinations of these parameters. Note Chapter 5 discusses string operations in detail. Listing 3.30 uses the MeasureString method to measure a string's height and width and draws a rectangle and a circle around the string. This example also shows how to find the total number of lines and characters of a string. Listing 3.30 Using the MeasureString method Graphics g = Graphics.FromHwnd(this.Handle); g.Clear(this.BackColor); string testString = "This is a test string"; Font verdana14 = new Font("Verdana", 14); Font tahoma18 = new Font("Tahoma", 18); int nChars; int nLines; // Call MeasureString to measure a string SizeF sz = g.MeasureString(testString, verdana14); string stringDetails = "Height: "+sz.Height.ToString() + ", Width: "+sz.Width.ToString(); MessageBox.Show("First string details: "+ stringDetails); g.DrawString(testString, verdana14, Brushes.Green, new PointF(0, 100)); g.DrawRectangle(new Pen(Color.Red, 2), 0.0F, 100.0F, sz.Width, sz.Height); sz = g.MeasureString("Ellipse", tahoma18, new SizeF(0.0F, 100.0F), new StringFormat(), out nChars, out nLines); stringDetails = "Height: "+sz.Height.ToString() + ", Width: "+sz.Width.ToString() + ", Lines: "+nLines.ToString() + ", Chars: "+nChars.ToString(); MessageBox.Show("Second string details: "+ stringDetails); This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. g.DrawString("Ellipse", tahoma18, Brushes.Blue, new PointF(10, 10)); g.DrawEllipse( new Pen(Color.Red, 3), 10, 10, sz.Width, sz.Height);g.Dispose() Figure 3.41 shows the output from Listing 3.30. Figure 3.41. Using MeasureString when drawing text 3.2.3.3 The FromImage, FromHdc, and FromHwnd Methods As we discussed earlier, an application can use Graphics class members to get a Graphics object. The Graphics class provides three methods to create a Graphics object: FromHwnd, FromHdc, and FromImage. FromImage takes an Image object as input parameter and returns a Graphics object. We will discuss FromImage in more detail in Chapters 7 and 8. The following code snippet creates a Graphics object from an Image object. Once a Graphics object has been created, you can call its members. Image img = Image.FromFile("Rose.jpg"); Graphics g = Graphics.FromImage(img); // Do something g.Dispose(); This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. Note Make sure you call the Dispose method of the Graphics object when you're finished with it. FromHdc creates a Graphics object from a window handle to a device context. The following code snippet shows an example in which FromHdc takes one parameter, of type IntPtr. IntPtr hdc = e.Graphics.GetHdc(); Graphics g= Graphics.FromHdc(hdc); // Do something e.Graphics.ReleaseHdc(hdc); g.Dispose(); Note You need to call the ReleaseHdc method to release resources allocated by a window handle to a device context, and also make sure you call the Dispose method of the Graphics object when you're finished with it. FromHwnd returns a Graphics object for a form. The following method takes a window handle. Graphics g = Graphics.FromHwnd(this.Handle); To draw on a form, an application can pass this handle. Once an application has a Graphics object, it can call any Graphics class method to draw graphics objects. [ Team LiB ] This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. [ Team LiB ] 3.3 The GDI+Painter Application Almost every chapter of this book will show a real-world example to illustrate the concepts discussed in it. In this chapter we create an application, GDI+Painter, that you can use to draw and fill simple graphics objects. If you wish, you can add more functionality to the application. Once you are done drawing graphics shapes, the program allows you to save your drawing in bitmap format. You can modify the program to save a drawing in .jpeg or .gif format. The program is a Windows Forms application and looks like Figure 3.42. It has three draw buttons (line, ellipse, and rectangle) and two fill buttons (rectangle and ellipse). The Save Image button allows you to save the image. Figure 3.42. The GDI+Painter application Click on a button and the program draws the selected item on the form. Here's how it works: First we define some private class-level variables: // Variables private Bitmap bitmap = null; private Bitmap curBitmap = null; private bool dragMode = false; private int drawIndex = 1; This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. private int curX, curY, x, y; private int diffX, diffY; private Graphics curGraphics; private Pen curPen; private SolidBrush curBrush; private Size fullSize; Note Please download GDI+Painter application source code from online (www.awprofessional.com/titles/0321160770). The next step is to initialize objects. On the form-load event handler, we create a bitmap and a Graphics object from the bitmap, which represents the entire form. We set its background color to the form's background color by calling the Graphics.Clear method. We also create a Pen object and a Brush object when the form loads. Listing 3.31 gives the form-load event handler code. Listing 3.31 The form-load event handler private void Form1_Load(object sender, System.EventArgs e) { // Get the full size of the form fullSize = SystemInformation .PrimaryMonitorMaximizedWindowSize; // Create a bitmap using full size bitmap = new Bitmap(fullSize.Width, fullSize.Height); // Create a Graphics object from Bitmap curGraphics = Graphics.FromImage(bitmap); // Set background color as form's color curGraphics.Clear(this.BackColor); // Create a new pen and brush as // default pen and brush curPen = new Pen(Color.Black); curBrush = new SolidBrush(Color.Black); } When we click on a button, we find out which button was selected and save it in the drawIndex variable. Listing 3.32 gives code for the button click event handler for all buttons. Listing 3.32 Saving a selected button private void LineDraw_Click(object sender, System.EventArgs e) { drawIndex = 1; } This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. private void RectDraw_Click(object sender, System.EventArgs e) { drawIndex = 2; } private void EllipseDraw_Click(object sender, System.EventArgs e) { drawIndex = 3; } private void FilledEllipse_Click(object sender, System.EventArgs e) { drawIndex = 5; } When we start drawing on the form, we save the starting point on the mouse-down events and the ending point on the mouse-up events (see Listing 3.33). From these two points we can determine the area of the rectangle we're trying to draw. We use this rectangle in draw and fill methods. On a mouse-move event, we calculate the difference between the ending and starting points that are used to draw the rectangle. Notice also that on mouse down we set dragMode to true, and on mouse up we set dragMode to false. On the basis of the area covered by user selection, we draw or fill objects on mouse up, which gives the user a visible drawing effect. You will also see the RefreshFormBackground method, which we will discuss shortly. Listing 3.33 The mouse-down event handler private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) { // Store the starting point of // the rectangle and set the drag mode // to true curX = e.X; curY = e.Y; dragMode = true; } private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { // Find out the ending point of // the rectangle and calculate the // difference between starting and ending // points to find out the height and width // of the rectangle x = e.X; y = e.Y; diffX = e.X - curX; diffY = e.Y - curY; // If dragMode is true, call refresh // to force the window to repaint if (dragMode) { this.Refresh(); This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. } } private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { diffX = x - curX; diffY = y - curY; switch (drawIndex) { case 1: { // Draw a line curGraphics.DrawLine(curPen, curX, curY, x, y); break; } case 2: { // Draw an ellipse curGraphics.DrawEllipse(curPen, curX, curY, diffX, diffY); break; } case 3: { // Draw a rectangle curGraphics.DrawRectangle(curPen, curX, curY, diffX, diffY); break; } case 4: { // Fill the rectangle curGraphics.FillRectangle(curBrush, curX, curY, diffX, diffY); break; } case 5: { // Fill the ellipse curGraphics.FillEllipse(curBrush, curX, curY, diffX, diffY); break; } } // Refresh RefreshFormBackground(); // Set drag mode to false dragMode = false; } Now we add code to the form's paint event handler, which draws and fills the object. Listing 3.34 gives the code for the OnPaint method. Listing 3.34 The OnPaint method This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { Graphics g = e.Graphics; // If dragMode is true, draw the selected // graphics shape if (dragMode) { switch (drawIndex) { case 1: { g.DrawLine(curPen, curX, curY, x, y); break; } case 2: { g.DrawEllipse(curPen, curX, curY, diffX, diffY); break; } case 3: { g.DrawRectangle(curPen, curX, curY, diffX, diffY); break; } case 4: { g.FillRectangle(curBrush, curX, curY, diffX, diffY); break; } case 5: { g.FillEllipse(curBrush, curX, curY, diffX, diffY); break; } } } } Here's a little trick. You may have noticed that we used the RefreshFormBackground method. This method sets the current drawing as the background of the form. Listing 3.35 gives code for the method. Listing 3.35 The RefreshFormBackground method private void RefreshFormBackground() { curBitmap = bitmap.Clone( new Rectangle(0, 0, this.Width, this.Height), bitmap.PixelFormat); this.BackgroundImage = curBitmap; This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it. Thanks. [...]... void ForeColorBtn_Click(object sender, System.EventArgs e) { // Use ColorDialog to select a color ColorDialog clrDlg = new ColorDialog(); if (clrDlg.ShowDialog() == DialogResult.OK) { // Save color as foreground color, // and fill text box with this color forClr = clrDlg.Color; textBox1.BackColor = forClr; } } private void BackColorBtn_Click(object sender, System.EventArgs e) { This document was created... unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks // Use ColorDialog to select a color ColorDialog clrDlg = new ColorDialog(); if (clrDlg.ShowDialog() == DialogResult.OK) { // Save color as background color, // and fill text box with this color backClr = clrDlg.Color; textBox2.BackColor = backClr; } } The last step is to apply the selected styles and colors, create a hatch brush,... document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks new Rectangle(250, 150, 200, 200); public ArrayList sliceList = new ArrayList(); struct sliceData { public int share; public Color clr; }; private Color curClr = Color.Black; int shareTotal = 0; The Select Color button allows us to select the color for a share As Listing 3. 39 shows, we use ColorDialog... application in action We add shares 10, 20, 30 , 40, and 50 with different colors The Draw Chart button click draws a pie chart, with the output shown in Figure 3. 44 Figure 3. 44 The Draw Chart button click in action This document was created by an unregistered ChmMagic, please go to http://www.bisenter.com to register it Thanks The Fill Chart button fills the chart, with the output shown in Figure 3. 45... vertical lines that cross and are spaced 50 percent closer together than Cross lines SolidDiamond A hatch with the appearance of a checkerboard placed diagonally Sphere A hatch with the appearance of spheres laid adjacent to one another Trellis A hatch with the appearance of a trellis Vertical A pattern of vertical lines Wave Horizontal lines that are composed of tildes Weave A hatch with the appearance... button click event handler private void ApplyBtn_Click(object sender, System.EventArgs e) { // Create a Graphics object Graphics g = this.CreateGraphics(); g.Clear(this.BackColor); // Read current style from combo box string str = comboBox1.Text; // Find out the style and set it as the // current style switch(str) { case "BackwardDiagonal": style = HatchStyle.BackwardDiagonal; break; case "DashedVertical":... 20, 30 , 40, 50 The total is 150 The percentage of the share with value 10 is 10/150 Figure 3. 43 A pie chart–drawing application Listing 3. 38 adds variables You may notice the structuresliceData, which has two public variables:share and clr The share variable represents the share of a slice, and clr is its color Listing 3. 38 The sliceData structure // User-defined variables private Rectangle rect =... lines, each of which is composed of dots that cross ForwardDiagonal A pattern of lines on a diagonal from upper left to lower right Horizontal A pattern of horizontal lines HorizontalBrick A hatch with the appearance of horizontally layered bricks LargeCheckerBoard A hatch with the appearance of a checker-board with squares that are twice the size of SmallCheckerBoard LargeConfetti A hatch with the... entered data to the ListBox control Listing 3. 40 Adding pie chart data private void button1_Click(object sender, System.EventArgs e) { int slice = Convert.ToInt32(textBox1.Text); shareTotal += slice; sliceData dt; dt.clr = curClr; dt.share = slice; sliceList.Add(dt); listBox1.Items.Add( "Share:"+slice.ToString()+" ," + curClr.ToString() ); } The Draw Chart and Fill Chart button clicks are used to draw the... ColorDialog to select a color Listing 3. 39 Selecting a color private void ColorBtn_Click(object sender, System.EventArgs e) { ColorDialog clrDlg = new ColorDialog(); if (clrDlg.ShowDialog() == DialogResult.OK) { curClr = clrDlg.Color; } } The Add Slice button adds the data to an array to be added to the list for calculation As Listing 3. 40 shows, all data is added to an array This code also adds the . palette. GetHdc Returns the device context handle associated with a Graphics object. GetNearestColor Returns the nearest color to the specified Color structure. IntersectClip Updates the clip region. break; } case 2: { // Draw an ellipse curGraphics.DrawEllipse(curPen, curX, curY, diffX, diffY); break; } case 3: { // Draw a rectangle curGraphics.DrawRectangle(curPen, curX, curY, diffX,. = Color.Black; int shareTotal = 0; The Select Color button allows us to select the color for a share. As Listing 3. 39 shows, we use ColorDialog to select a color. Listing 3. 39 Selecting a color private

Ngày đăng: 12/08/2014, 19:20

TỪ KHÓA LIÊN QUAN