Drawing Objects with GDI+The GDI+ classes for drawing images are contained in the following four namespaces:
To draw simple images, you need to import both the System.Drawing and System.Drawing.Imaging namespaces. If you need to perform more advanced graphics functions, you also need to import the System.Drawing.Drawing2D namespace. Finally, if you need to display text with different fonts, you need to import the System.Drawing.Text namespace. The two classes that you'll need to use most often are Bitmap and Graphics . Both of these classes can be found in the System.Drawing namespace. Creating a BitmapThe Bitmap class represents an image in memory. It represents all the pixels of an image and contains methods for setting and reading individual pixels. You can use a bitmap to represent either a new or an existing image. To load an existing image into a bitmap, you initialize it like this: objBitmap = New Bitmap( "c:\myImage.Gif" ) This statement creates a new bitmap from an image named myImage.Gif . The Bitmap class includes several methods for constructing a new image. The simplest method is to specify the horizontal and vertical number of pixels like this: objBitmap = New Bitmap( 400, 100 ) This statement creates a new bitmap with 400 horizontal pixels and 100 vertical pixels. A bitmap is represented in memory with a certain pixel format. This format determines exactly how many bits are used to represent each pixel. By default, bitmaps are created with a pixel format of Format32bppARGB . When the pixel format is Format32bppARGB , 32 bits represent each pixel. The ARGB indicates the order of the color components for each pixel. In the case of the Format32bppARGB pixel format, 8 bits represent the alpha color component, 8 bits represent the red color component, 8 bits represent the green color component, and 8 bits represent the blue color component. NOTE The alpha component determines the transparency of a pixel. A low alpha value creates a transparent pixel; a high alpha value creates an opaque pixel. You can change the default pixel format of a bitmap when you create it like this: objBitmap = New Bitmap( 400, 200, PixelFormat.Format64bppARGB ) This statement creates a new bitmap that uses 64 bits to represent each color. A Format64bppARGB pixel format enables you to represent 16,777,216 shades of color. NOTE To view all the possible pixel formats, see the .NET Framework Software Development Kit Documentation. You can find the PixelFormat enumeration in the System.Drawing.Imaging namespace. You can save an image represented by a bitmap to the hard drive or to a stream by calling its Save method. To save an image to the hard drive, use the following statement (the ASPNET user account requires write permissions on the c:\ directory to do this): objBitmap.Save( "c:\myImage.Gif", ImageFormat.Gif ) To save a bitmap to the Response object's output stream, use the following statement: objBitmap.Save( Response.OutputStream, ImageFormat.JPEG ) Notice, in both cases, that you need to specify the format of the image by referring to a member of the ImageFormat enumeration. Working with the Graphics ObjectThe Bitmap class enables you to work only with individual pixels. If you want to draw something fancy, such as a rectangle or a line, you need to use the Graphics class. The page in Listing 27.3, for example, generates an image that contains a rectangle with the Bitmap and Graphics classes. Listing 27.3 Graphics.aspx<%@ Page ContentType="image/gif" %> <%@ Import namespace="System.Drawing" %> <%@ Import namespace="System.Drawing.Imaging" %> <Script Runat="Server"> Sub Page_Load Dim objBitmap As Bitmap Dim objGraphics As Graphics ' Create Bitmap objBitmap = New Bitmap( 400, 200 ) ' Initialize Graphics Class objGraphics = Graphics.FromImage( objBitmap ) objGraphics.DrawRectangle( Pens.Red, 100, 100, 50, 50 ) ' Display Bitmap objBitmap.Save( Response.OutputStream, ImageFormat.Gif ) End Sub </Script> The C# version of this code can be found on the CD-ROM. In Listing 27.3, a 400x200 pixel bitmap is initialized . Next , an instance of the Graphics class is created with the FromImage method. The DrawRectangle method then draws a rectangle on the bitmap. Finally, the image is actually displayed by calling the Save method to save the image to the Response object's output stream (see Figure 27.3). Figure 27.3. Using the Graphics class.
By default, when you create a new bitmap, it uses the color black as the background color. You can use the Graphics class to change the background color by calling the Clear method with a new color like this: objGraphics.Clear( Color.Red ) This statement sets all the pixels in a bitmap to the color red. Setting Graphics QualityWhen drawing ellipses and other curved objects, you can produce better results by modifying the value of the SmoothingMode property. This property can accept the following five values:
If you enable antialiasing, for example, intermediate colors are drawn between the boundaries of different colors to blend them. In theory, antialiasing should result in smoother curves. The image in Figure 27.4 illustrates how different values of the SmoothingMode property alter the appearance of an ellipse. The page used to generate the images is included on the CD with the name Smooth.aspx . Figure 27.4. Effects of the SmoothingMode property.
To get the most from antialiasing, you should use JPEG images rather than GIF images, because JPEG images support more colors and can represent gradations in color more efficiently . Using ColorsColors are represented by the GDI+ Color structure, which contains hundreds of properties that represent individual colors. For example, if you want to use the color blue, you can use the Blue property of the Color structure ( Color.Blue ), and if you want to use the color dark cyan, you can use the DarkCyan property of the Color structure ( Color.DarkCyan ). NOTE You can find the Color structure in the System.Drawing namespace. You can use any of the color properties from the Color structure when working with the image classes. For example, you can set a pixel to the color blue by using the following statement: objBitmap.SetPixel( 100, 100, Color.Blue ) A color has alpha, red, green, and blue components. The following code, for example, displays the alpha, red, green, and blue components for the color MediumOrchid : Response.Write( "<li> Alpha:" & Color.MediumOrchid.A ) Response.Write( "<li> Red:" & Color.MediumOrchid.R ) Response.Write( "<li> Green:" & Color.MediumOrchid.G ) Response.Write( "<li> Blue:" & Color.MediumOrchid.B ) Although a color is completely defined by its alpha, red, green, and blue components, you also can use the properties of the Color structure to retrieve a color's brightness, hue, and saturation like this: Response.Write( "<li> Brightness: " & Color.MediumOrchid.GetBrightness ) Response.Write( "<li> Hue: " & Color.MediumOrchid.GetHue ) Response.Write( "<li> Saturation: " & Color.MediumOrchid.GetSaturation ) The brightness is the amount of white or black in a color. The hue refers to the color's position on the linear spectrum of the color wheel. The saturation defines the light intensity of the color. Converting ColorsYou can convert a color string into a GDI+ color by using the Color structure's FromName method like this: Dim objColor As Color objColor = Color.FromName( "blue" ) This statement takes the string blue and converts it into a GDI+ color. You also can use the FromArgb method to convert a red-green-blue value into a color. For example, the following statement assigns the color red to the objColor variable: Dim objColor As Color objColor = Color.FromArgb( 255, 0, 0 ) You also have the option of specifying an alpha value with the FromArgb method: Dim objColor As Color objColor = Color.FromArgb( 100, 255, 0, 0 ) In this example, the first value passed to the FromArgb method represents the alpha value. The remaining three values represent the red, green, and blue values. If you want to create a color with a new alpha value from an existing color, you can change it like this: Dim objColor As Color objColor = Color.FromArgb( 100, Color.Yellow ) This statement assigns the color yellow, with an alpha value of 100, to the objColor variable. Finally, if you need to convert between HTML colors and GDI+ colors, you can use the methods of the ColorTranslator class. The FromHTML method takes an HTML color string, such as white or #FFFFFF , and converts it into a GDI+ color. The ToHTML method performs the opposite operation, as you can see in this example: Dim objColor As Color objColor = ColorTranslator.FromHTML( "#00FF00" ) Response.Write( ColorTranslator.ToHTML( Color.Blue ) ) Setting a Color's Alpha ValueSpecifying an alpha value for a color is useful when you're working with overlapping images. For example, the page in Listing 27.4 contains two overlapping filled rectangles. Because the top rectangle has an alpha value less than 255, the colors of the two rectangles are blended everywhere they overlap (see Figure 27.5). Listing 27.4 Alpha.aspx<%@ Page ContentType="image/gif" %> <%@ Import Namespace="System.Drawing" %> <%@ Import Namespace="System.Drawing.Imaging" %> <Script Runat="Server"> Sub Page_Load Dim objBitmap As Bitmap Dim objGraphics As Graphics Dim objBrush, objBrush2 As Brush ' Create Bitmap objBitmap = New Bitmap( 400, 400 ) objGraphics = Graphics.FromImage( objBitmap ) ' Create Different Colored Brushes objBrush = New SolidBrush( Color.Blue ) objBrush2 = New SolidBrush( Color.FromArgb( 100, Color.Orange ) ) ' Create Rectangles objGraphics.FillRectangle( objBrush, 10, 10, 100, 100 ) objGraphics.FillRectangle( objBrush2, 50, 50, 100, 100 ) ' Display the Bitmap objBitmap.Save( Response.OutputStream, ImageFormat.Gif ) End Sub </Script> The C# version of this code can be found on the CD-ROM. Figure 27.5. Modifying the alpha value.
The two rectangles displayed in the page in Listing 27.4 are painted with different colored brushes. The first rectangle is painted with a solid blue brush. The second rectangle is painted with an orange brush that has an alpha value of 100. When the orange rectangle is rendered, the orange pixels are blended with the blue pixels wherever the two rectangles overlap. Using BrushesYou use a brush to fill the shapes that you create with the Graphics class, such as rectangles, ellipses, and polygons. You can choose from these five predefined brushes:
In addition to these five types of brushes, GDI+ includes a number of standard brushes. The following sections provide examples showing how you can use all the different types of brushes. Using the Standard BrushesThe easiest way to use a brush is to use one of the standard brushes included in the Brushes class. The Brushes class contains brushes that correspond to all the standard colors. For example, the page in Listing 27.5 uses a Blue brush to fill the interior of a circle. Listing 27.5 StandardBrush.aspx<%@ Page ContentType="image/gif" %> <%@ Import namespace="System.Drawing" %> <%@ Import namespace="System.Drawing.Imaging" %> <Script Runat="Server"> Sub Page_Load Dim objBitmap As Bitmap Dim objGraphics As Graphics ' Create Bitmap objBitmap = New Bitmap( 300, 300 ) ' Create Graphics objGraphics = Graphics.FromImage( objBitmap ) ' Draw Ellipse objGraphics.FillEllipse( Brushes.Blue, 10, 10, 200, 200 ) ' Display Bitmap objBitmap.Save( Response.OutputStream, ImageFormat.Gif ) End Sub </Script> The C# version of this code can be found on the CD-ROM. The standard Blue brush from the Brushes class is used with the FillEllipse method to render a circle with a blue background. Using SolidBrushIf you need to use a color that is not represented by one of the standard brushes described in the preceding section, you need to use SolidBrush . For example, the page in Listing 27.6 renders a rectangle that is filled with a custom background color. Listing 27.6 SolidBrush.aspx<%@ Page ContentType="image/gif" %> <%@ Import namespace="System.Drawing" %> <%@ Import namespace="System.Drawing.Imaging" %> <%@ Import namespace="System.Drawing.Drawing2D" %> <Script Runat="Server"> Sub Page_Load Dim objBitmap As Bitmap Dim objGraphics As Graphics Dim objBrush As SolidBrush ' Create Bitmap objBitmap = New Bitmap( 400, 200 ) ' Create Graphics objGraphics = Graphics.FromImage( objBitmap ) ' Create Solid Brush objBrush = New SolidBrush( Color.FromArgb( 80, 132, 234 ) ) ' Draw Rectangle objGraphics.FillRectangle( objBrush, 10, 10, 380, 180 ) ' Display Bitmap objBitmap.Save( Response.OutputStream, ImageFormat.Gif ) End Sub </Script> The C# version of this code can be found on the CD-ROM. In Listing 27.6, SolidBrush is initialized with a custom color, which is created with help from the FromArgb method. SolidBrush is passed to the FillRectangle method to render the rectangle with the custom background color. Using HatchBrushHatchBrush enables you to fill a shape with a hatch pattern. For example, the page in Listing 27.7 fills an ellipse with a plaid HatchBrush (see Figure 27.6). Listing 27.7 HatchBrush.aspx<%@ Page ContentType="image/gif" %> <%@ Import namespace="System.Drawing" %> <%@ Import namespace="System.Drawing.Imaging" %> <%@ Import namespace="System.Drawing.Drawing2D" %> <Script Runat="Server"> Sub Page_Load Dim objBitmap As Bitmap Dim objGraphics As Graphics Dim objBrush As HatchBrush ' Create Bitmap objBitmap = New Bitmap( 400, 200 ) ' Create Graphics objGraphics = Graphics.FromImage( objBitmap ) ' Create Hatch Brush objBrush = New HatchBrush( HatchStyle.Plaid, Color.Red ) ' Draw Ellipse objGraphics.FillEllipse( objBrush, 10, 10, 380, 180 ) ' Display Bitmap objBitmap.Save( Response.OutputStream, ImageFormat.Gif ) End Sub </Script> The C# version of this code can be found on the CD-ROM. Figure 27.6. Using a HatchBrush .
In Listing 27.7, a HatchBrush named objBrush is created. HatchBrush is initialized with a particular HatchStyle property and a particular foreground color. You can choose from dozens of HatchStyle properties, including Divot , DottedGrid , and SmallConfetti . See the .NET Framework SDK Documentation for a complete list (look up HatchStyle in the index). Using LinearGradientBrushLinearGradientBrush enables you to fill a shape with a color gradient. For example, the page in Listing 27.8 draws a rectangle that is filled with a gradation of colors between red and yellow (see Figure 27.7). Listing 27.8 LinearGradientBrush.aspx<%@ Page ContentType="image/gif" %> <%@ Import namespace="System.Drawing" %> <%@ Import namespace="System.Drawing.Imaging" %> <%@ Import namespace="System.Drawing.Drawing2D" %> <Script Runat="Server"> Sub Page_Load Dim objBitmap As Bitmap Dim objGraphics As Graphics Dim objRect As Rectangle Dim objBrush As LinearGradientBrush ' Create Bitmap objBitmap = New Bitmap( 400, 200 ) ' Create Graphics objGraphics = Graphics.FromImage( objBitmap ) ' Create Rectangle objRect = New Rectangle( 10, 10, 300, 100 ) ' Create LinearGradient Brush objBrush = New LinearGradientBrush( objRect, Color.Red, _ Color.Yellow, LinearGradientMode.ForwardDiagonal ) ' Draw Rectangle objGraphics.FillRectangle( objBrush, objRect ) ' Display Bitmap objBitmap.Save( Response.OutputStream, ImageFormat.Gif ) End Sub </Script> The C# version of this code can be found on the CD-ROM. Figure 27.7. Using a LinearGradientBrush .
In Listing 27.8, LinearGradientBrush is initialized with four parameters: the Rectangle to fill, the starting color, the ending color, and LinearGradientMode . LinearGradientMode determines exactly how the gradation of colors is rendered. It can have the following four values:
Using PathGradientBrushPathGradientBrush is similar to LinearGradientBrush , except that it enables you to create more complicated effects. For example, the page in Listing 27.9 uses PathGradientBrush to fill a path built from two lines and two circles (see Figure 27.8). Listing 27.9 PathGradientBrush.aspx<%@ Page ContentType="image/gif" %> <%@ Import namespace="System.Drawing" %> <%@ Import namespace="System.Drawing.Imaging" %> <%@ Import namespace="System.Drawing.Drawing2D" %> <Script Runat="Server"> Sub Page_Load Dim objBitmap As Bitmap Dim objGraphics As Graphics Dim objPath As GraphicsPath Dim objBrush As PathGradientBrush ' Create Bitmap objBitmap = New Bitmap( 400, 400 ) ' Create Graphics objGraphics = Graphics.FromImage( objBitmap ) ' Create Path objPath = New GraphicsPath( ) objPath.AddLine( 10, 10, 300, 10 ) objPath.AddEllipse( 50, 50, 300, 300 ) objPath.AddEllipse( 10, 10, 200, 200 ) objPath.AddLine( 10, 300, 100, 300 ) ' Create PathGradient Brush objBrush = New PathGradientBrush( objPath ) objBrush.CenterColor = Color.Red ' Draw Path objGraphics.FillPath( objBrush, objPath ) ' Display Bitmap objBitmap.Save( Response.OutputStream, ImageFormat.Gif ) End Sub </Script> The C# version of this code can be found on the CD-ROM. Figure 27.8. Using a PathGradientBrush .
PathGradientBrush is initialized with an instance of the GraphicsPath class. Next, the CenterColor property is assigned the color red. When the path is rendered, it will be filled with a red gradient. Using TextureBrushYou can use TextureBrush to fill a shape with an image. By default, the image is tiled across the background of the shape. The page in Listing 27.10 illustrates how to use TextureBrush (see Figure 27.9). Listing 27.10 TextureBrush.aspx<%@ Page ContentType="image/gif" %> <%@ Import namespace="System.Drawing" %> <%@ Import namespace="System.Drawing.Imaging" %> <%@ Import namespace="System.Drawing.Drawing2D" %> <Script Runat="Server"> Sub Page_Load Dim objBitmap As Bitmap Dim objGraphics As Graphics Dim objBrushImage As Bitmap Dim objBrush As TextureBrush ' Create Bitmap objBitmap = New Bitmap( 400, 200 ) ' Create Graphics objGraphics = Graphics.FromImage( objBitmap ) ' Create Texture Brush objBrushImage = New Bitmap( "c:\sphere.gif" ) objBrush = New TextureBrush( objBrushImage ) ' Draw Rectangle objGraphics.FillRectangle( objBrush, 10, 10, 380, 180 ) ' Display Bitmap objBitmap.Save( Response.OutputStream, ImageFormat.Gif ) End Sub </Script> The C# version of this code can be found on the CD-ROM. Figure 27.9. Using a TextureBrush .
In Listing 27.10, a GIF image named sphere.gif is used with TextureBrush . First, the image is loaded from the hard drive into a bitmap. (You'll need to supply the correct path for this image on your hard drive.) Next, TextureBrush is initialized with the image. Finally, TextureBrush is used with the FillRectangle method when rendering the rectangle. Using PensBrushes are used to fill the interiors of shapes; pens are used to draw lines and curves with a certain width, style, and color. For example, by setting certain properties of a pen, you can draw dashed or dotted lines. By setting other pen properties, you can draw lines that start and end with arrows. In the following sections, you learn how to draw shapes with the various styles of pens. Using the Standard PensThe easiest method of using a pen is to use one of the standard pens represented by the properties of the Pens class. The Pens class contains pens that represent all the standard colors. For example, in Listing 27.11, a rectangle is drawn with a green pen. Listing 27.11 StandardPens.aspx<%@ Page ContentType="image/gif" %> <%@ Import namespace="System.Drawing" %> <%@ Import namespace="System.Drawing.Imaging" %> <Script Runat="Server"> Sub Page_Load Dim objBitmap As Bitmap Dim objGraphics As Graphics ' Create Bitmap objBitmap = New Bitmap( 400, 200 ) ' Create Graphics objGraphics = Graphics.FromImage( objBitmap ) ' Draw Rectangle objGraphics.DrawRectangle( Pens.Green, 50, 50, 100, 100 ) ' Display Bitmap objBitmap.Save( Response.OutputStream, ImageFormat.Gif ) End Sub </Script> The C# version of this code can be found on the CD-ROM. The green pen is represented by the Green property of the Pens class. This pen is passed as the first parameter to the DrawRectangle method. Creating Custom PensIf you need to create a pen with custom properties, you can explicitly initialize an instance of the Pen class. For example, the page in Listing 27.12 uses a 5-pixel wide purple pen to draw a circle (see Figure 27.10). Listing 27.12 CustomPen.aspx<%@ Page ContentType="image/gif" %> <%@ Import namespace="System.Drawing" %> <%@ Import namespace="System.Drawing.Imaging" %> <Script Runat="Server"> Sub Page_Load Dim objBitmap As Bitmap Dim objGraphics As Graphics Dim objPen As Pen ' Create Bitmap objBitmap = New Bitmap( 400, 400 ) ' Create Graphics objGraphics = Graphics.FromImage( objBitmap ) ' Create Custom Pen objPen = New Pen( Color.Purple ) objPen.Width = 5 ' Draw Circle objGraphics.DrawEllipse( objPen, 10, 10, 200, 200 ) ' Display Bitmap objBitmap.Save( Response.OutputStream, ImageFormat.Gif ) End Sub </Script> The C# version of this code can be found on the CD-ROM. Figure 27.10. Using a custom pen.
The instance of the Pen class is initialized with the color purple. Next, the pen's Width property is assigned the value 5 . The circle is rendered by passing the pen as the first parameter to the DrawEllipse method. Setting Pen StylesYou can draw dashed or dotted lines with a pen by setting the DashStyle property. This property accepts the following values from the DashStyle enumeration:
The page in Listing 27.13 illustrates how setting different DashStyle properties modifies the appearance of a line (see Figure 27.11). Listing 27.13 DashStyle.aspx<%@ Page ContentType="image/gif" %> <%@ Import namespace="System.Drawing" %> <%@ Import namespace="System.Drawing.Imaging" %> <%@ Import namespace="System.Drawing.Drawing2D" %> <Script Runat="Server"> Sub Page_Load Dim objBitmap As Bitmap Dim objGraphics As Graphics Dim objPen As Pen ' Create Bitmap objBitmap = New Bitmap( 400, 200 ) ' Create Graphics objGraphics = Graphics.FromImage( objBitmap ) ' Create Custom Pen objPen = New Pen( Color.White ) objPen.Width = 4 ' Draw Dash Line objPen.DashStyle = DashStyle.Dash objGraphics.DrawLine( objPen, 10, 20, 350, 20 ) ' Draw DashDot Line objPen.DashStyle = DashStyle.DashDot objGraphics.DrawLine( objPen, 10, 40, 350, 40 ) ' Draw DashDotDot Line objPen.DashStyle = DashStyle.DashDotDot objGraphics.DrawLine( objPen, 10, 60, 350, 60 ) ' Draw Dot Line objPen.DashStyle = DashStyle.Dot objGraphics.DrawLine( objPen, 10, 80, 350, 80 ) ' Draw DashDotDot Line objPen.DashStyle = DashStyle.Solid objGraphics.DrawLine( objPen, 10, 100, 350, 100 ) ' Display Bitmap objBitmap.Save( Response.OutputStream, ImageFormat.Gif ) End Sub </Script> The C# version of this code can be found on the CD-ROM. Figure 27.11. Modifying the DashStyle property.
In Listing 27.13, you set different DashStyle properties by assigning different values to these properties of the Pen class. Setting Pen Cap StylesYou can set various cap styles with the Pen class. For example, you can set the cap style for both the start and end of a line. Here's a list of the values that you can use for setting the cap style (from the LineCap enumeration):
When working with dashed lines, you can use the following three values (from the DashCap enumeration):
You can set the cap styles for a pen with the StartCap , EndCap , and DashCap properties like this: objPen.StartCap = LineCap.Square objPen.EndCap = LineCap.Round objPen.DashCap = DashCap.Triangle The page in Listing 27.14 illustrates how different cap styles alter the appearance of a line (see Figure 27.12). Listing 27.14 PenCaps.aspx<%@ Page ContentType="image/gif" %> <%@ Import namespace="System.Drawing" %> <%@ Import namespace="System.Drawing.Imaging" %> <%@ Import namespace="System.Drawing.Drawing2D" %> <Script Runat="Server"> Sub Page_Load Dim objBitmap As Bitmap Dim objGraphics As Graphics Dim objPen As Pen ' Create Bitmap objBitmap = New Bitmap( 400, 200 ) ' Create Graphics objGraphics = Graphics.FromImage( objBitmap ) ' Create Custom Pen objPen = New Pen( Color.White ) objPen.Width = 6 ' Draw ArrowAnchor Cap objPen.EndCap = LineCap.ArrowAnchor objGraphics.DrawLine( objPen, 10, 20, 350, 20 ) ' Draw DiamondAnchor Cap objPen.EndCap = LineCap.DiamondAnchor objGraphics.DrawLine( objPen, 10, 40, 350, 40 ) ' Draw Flat Cap objPen.EndCap = LineCap.Flat objGraphics.DrawLine( objPen, 10, 60, 350, 60 ) ' Draw Round Cap objPen.EndCap = LineCap.Round objGraphics.DrawLine( objPen, 10, 80, 350, 80 ) ' Draw RoundAnchor Cap objPen.EndCap = LineCap.RoundAnchor objGraphics.DrawLine( objPen, 10, 100, 350, 100 ) ' Draw Square Cap objPen.EndCap = LineCap.Square objGraphics.DrawLine( objPen, 10, 120, 350, 120 ) ' Draw SquareAnchorCap objPen.EndCap = LineCap.SquareAnchor objGraphics.DrawLine( objPen, 10, 140, 350, 140 ) ' Draw TriangleCap objPen.EndCap = LineCap.Triangle objGraphics.DrawLine( objPen, 10, 160, 350, 160 ) ' Display Bitmap objBitmap.Save( Response.OutputStream, ImageFormat.Gif ) End Sub </Script> The C# version of this code can be found on the CD-ROM. Figure 27.12. Using different cap styles.
Setting Pen Line Join StylesYou can control the appearance of joins between lines drawn with a pen by modifying the value of the LineJoin property. You can assign the following values to this property (from the LineJoin enumeration):
The page in Listing 27.15 illustrates how different LineJoin values modify the appearance of a rectangle (see Figure 27.13). Listing 27.15 LineJoin.aspx<%@ Page ContentType="image/gif" %> <%@ Import namespace="System.Drawing" %> <%@ Import namespace="System.Drawing.Imaging" %> <%@ Import namespace="System.Drawing.Drawing2D" %> <Script Runat="Server"> Sub Page_Load Dim objBitmap As Bitmap Dim objGraphics As Graphics Dim objPen As Pen ' Create Bitmap objBitmap = New Bitmap( 400, 200 ) ' Create Graphics objGraphics = Graphics.FromImage( objBitmap ) ' Create Custom Pen objPen = New Pen( Color.White ) objPen.Width = 10 ' Draw Bevel LineJoin objPen.LineJoin = LineJoin.Bevel objGraphics.DrawRectangle( objPen, 10, 20, 350, 40 ) ' Draw Miter LineJoin objPen.LineJoin = LineJoin.Miter objGraphics.DrawRectangle( objPen, 10, 80, 350, 40 ) ' Draw Bevel LineJoin objPen.LineJoin = LineJoin.Round objGraphics.DrawRectangle( objPen, 10, 140, 350, 40 ) ' Display Bitmap objBitmap.Save( Response.OutputStream, ImageFormat.Gif ) End Sub </Script> The C# version of this code can be found on the CD-ROM. Figure 27.13. Using different LineJoin values.
Using different LineJoin properties can be very valuable when you're generating images of buttons dynamically. For example, by setting LineJoin to Round , you can display rounded button images. Drawing a RectangleThe Graphics class includes two methods for drawing rectangles: DrawRectangle and FillRectangle . The DrawRectangle method draws the outlines of a rectangle, and the FillRectangle method draws a rectangle with a filled interior. You use the DrawRectangle method with a pen. The pen specifies the color and style of the outline of the rectangle. For example, the following statement draws a rectangle with the standard Yellow pen: objGraphics.DrawRectangle( Pens.Yellow, 10, 10, 50, 50 ) The first parameter represents a pen, the second parameter represents the x coordinate of the rectangle's upper-left corner, the third parameter represents the y coordinate of the rectangle's upper-left corner, the fourth parameter represents the rectangle's width, and the final parameter represents the rectangle's height. The FillRectangle method draws a rectangle with its interior filled. You use the FillRectangle method with a brush. For example, the following statement creates a rectangle filled with the color green: objGraphics.FillRectangle( Brushes.Green, 10, 10, 50, 50 ) Drawing a LineYou can draw a line by using the DrawLine method. For example, the following statement draws a line between the coordinates 10, 10 and 50,50: objGraphics.DrawLine( Pens.Red, 10, 10, 50, 50 ) Notice that you must specify a pen when drawing a line. This example uses the standard Red pen. By setting properties of the pen, you can control exactly how the line is rendered. Drawing an EllipseYou can draw circles and other ellipses by using either the DrawEllipse or FillEllipse method of the Graphics class. The DrawEllipse method draws the outline of an ellipse, and the FillEllipse method draws an ellipse with its interior filled. You use the DrawEllipse method with a pen. For example, the following statement draws an ellipse with an orange outline: objGraphics.DrawEllipse( Pens.Orange, 10, 10, 50, 50 ) The first parameter represents an orange pen; the remaining four parameters define a bounding rectangle for the ellipse. To fill an ellipse with a certain color or pattern, use the FillEllipse method with a brush. For example, the following statement renders an ellipse filled with the color purple: objGraphics.FillEllipse( Brushes.Purple, 10, 10, 50, 50 ) Drawing a CurveYou can draw a curve by using the DrawCurve method. For example, the following statements draw a curve through four points: Dim arrPoints() As Point = { _ New Point( 10, 10 ), _ New Point( 60, 30 ), _ New Point( 110, 30 ), _ New Point( 160, 10 ) } objGraphics.DrawCurve( Pens.White, arrPoints ) When using the DrawCurve method, you must supply both a pen and an array that contains at least four points. You also have the option of drawing a closed curve. In a closed curve, the last point is automatically connected to the first point, as shown here: Dim arrPoints() As Point = { _ New Point( 10, 10 ), _ New Point( 60, 30 ), _ New Point( 110, 30 ), _ New Point( 160, 10 ) } objGraphics.DrawClosedCurve( Pens.White, arrPoints ) Finally, you can draw a filled closed curve by using the FillClosedCurve method and supplying a brush like this: Dim arrPoints() As Point = { _ New Point( 10, 10 ), _ New Point( 60, 30 ), _ New Point( 110, 30 ), _ New Point( 160, 10 ) } objGraphics.FillClosedCurve( Brushes.White, arrPoints ) In this example, the interior of the closed curve is filled with a white brush. Drawing a B zier CurveYou can draw a B zier curve by using the DrawBezier method. This method accepts five parameters: a pen and four points that describe the shape of the curve. The first and last points indicate the start and end points of the curve. The second and third points control the shape of the curve, as you can see here: Dim objPoint1 As Point = New Point( 10, 10 ) Dim objPoint2 As Point = New Point( 60, 30 ) Dim objPoint3 As Point = New Point( 110, 30 ) Dim objPoint4 As Point = New Point( 160, 10 ) objGraphics.DrawBezier( Pens.Blue, objPoint1, objPoint2, objPoint3, objPoint4 ) This statement draws a B zier curve with a blue pen. Drawing an ArcTo draw an arc, use the DrawArc method. For example, the following statement draws a half circle: objGraphics.DrawArc( Pens.Green, 50, 50, 100, 100, 90, 180 ) The first parameter is a pen. The next four parameters describe a rectangle that bounds the arc, and the last two parameters represent the start and sweep angle of the arc. Drawing a Pie SectionIf you need to draw a pie chart, you can use the DrawPie and FillPie methods. For example, the following statement draws a pie section in the shape of a well-known arcade game character: objGraphics.DrawPie( Pens.Yellow, 50, 50, 100, 100, 45, 270 ) The first parameter represents a pen. The next four parameters describe a bounding rectangle for the arc, and the last two parameters represent the start and sweep angle of the arc. You can render a filled pie section by using the FillPie method like this: objGraphics.FillPie( Brushes.Yellow, 50, 50, 100, 100, 45, 270 ) This statement draws a pie section filled with the color yellow. Drawing a PolygonA polygon represents a sequence of points connected by lines. You can draw a polygon by using the DrawPolygon method. For example, the following statements draw the outlines of a triangle with four points (the first and last points are the same): Dim arrPoints() As Point = { _ New Point( 100, 10 ), _ New Point( 10, 100 ), _ New Point( 190, 100 ), _ New Point( 100, 10 ) } objGraphics.DrawPolygon( Pens.Maroon, arrPoints ) You also have the option of drawing a filled polygon by using the FillPolygon method like this: Dim arrPoints() As Point = { _ New Point( 100, 10 ), _ New Point( 10, 100 ), _ New Point( 190, 100 ), _ New Point( 100, 10 ) } objGraphics.FillPolygon( Brushes.Maroon, arrPoints ) In this example, the FillPolygon method draws a triangle filled with the color maroon. Drawing an ImageIf you need to add an image to another image, you can use the DrawImage method. For example, the following statement adds an image named sphere.gif to the current bitmap: Dim objNewImage As Bitmap = New Bitmap( "c:\sphere.gif" ) objGraphics.DrawImage( objNewImage, 10, 10 ) When you add an image using the DrawImage method, you also can specify a new width and height for the image being added. For example, the following statements stretch the sphere.gif image to 300 pixels wide and 100 pixels high: Dim objNewImage As Bitmap = New Bitmap( "c:\sphere.gif" ) objGraphics.DrawImage( objNewImage, 10, 10, 300, 100 ) When adding an image, you might need to make one of the colors contained in the image transparent. You can make any color transparent by using the MakeTransparent method like this: Dim objNewImage As Bitmap = New Bitmap( "c:\sphere.gif" ) objNewImage.MakeTransparent( Color.White ) objGraphics.DrawImage( objNewImage, 10, 10 ) In this example, the color white is made transparent. When the sphere.gif image is added, any white pixels in the image appear transparent. |