10.4 Filling a Rectangle with a Texture Brush

 <  Day Day Up  >  

You want to create a rectangle that uses an image to fill its interior.


Technique

The process of drawing a rectangle, or any other shape, using a texture-based brush is similar to those of the last two recipes. Call the DrawRectangle or FillRectangle method using a TextureBrush object as the brush. The TextureBrush constructor uses a single parameter, which is an Image object. Recipe 10.15 details different ways to load an image. The easiest way is to call the static method FromFile defined in the Image class passing the path to an image file on the file system:

 
 Graphics g = panel1.CreateGraphics(); Image img = Image.FromFile( "myimage.jpg" ); g.FillRectangle( new TextureBrush(img), e.X, e.Y, img.Width, img.Height ); g.Dispose(); 

Comments

You can use a HatchBrush to fill a shape with a specified pattern. However, the HatchBrush class doesn't allow a developer to define his own pattern. You can use the TextureBrush class to create your own pattern, although you lose the benefit of being able to specify a background and foreground color . A TextureBrush uses an Image as its rendering output.

When rendering a shape using a TextureBrush , the image is not aligned with the X and Y coordinate of the shape being drawn. For instance, the top-left corner of the image associated with a TextureBrush is not aligned with the top-left corner of the shape being drawn. In fact, the image is aligned with the corner of the visible surface being rendered to, and if the image is smaller than the width and height of the surface, it is tiled. With that little bit of information, you can see how easy it is to create a Windows Form whose background contains a tiled image:

 
 protected override void OnPaint(PaintEventArgs e) {     e.Graphics.FillRectangle( new TextureBrush( myImage ),         0, 0, this.Width, this.Height ); } 
 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net