8.5 Create a Scrollable Image


Problem

You need to create a scrollable picture with dynamic content.

Solution

Leverage the automatic scroll capabilities of the System.Windows.Forms.Panel control by setting Panel.AutoScroll to true and placing a System.Windows.Forms.PictureBox with the image content inside the Panel .

Discussion

The Panel control has built-in scrolling support. If you place any controls in it that extend beyond its bounds, and you set Panel.AutoScroll to true , the panel will show scroll bars that allow the user to move through the content. This works particularly well with large images. You can load or create the image in memory, assign it to a picture box (which has no intrinsic support for scrolling), and then show the picture box inside the panel. The only consideration you need to remember is to make sure you set the picture box dimensions equal to the full size of the image you want to show.

The following example creates an image the represents a document. The image is generated as an in-memory bitmap, and several lines of text are added using the Graphics.DrawString method. The image is then bound to a picture box, which is shown in a scrollable panel, as shown in Figure 8.5.

 using System; using System.Windows.Forms; using System.Drawing; public class PictureScroll : System.Windows.Forms.Form {     private System.Windows.Forms.PictureBox pictureBox1;     private System.Windows.Forms.Panel panel1;     // (Designer code omitted.)     private void PictureScroll_Load(object sender, System.EventArgs e) {              string text = "The quick brown fox jumps over the lazy dog.";         Font font = new Font("Tahoma", 20);         // Create an in-memory bitmap.         Bitmap b = new Bitmap(600, 600);         Graphics g = Graphics.FromImage(b);         g.FillRectangle(Brushes.White, new Rectangle(0, 0, b.Width,            b.Height));         // Draw several lines of text on the bitmap.         for (int i=0; i < 10; i++) {             g.DrawString(text, font, Brushes.Black, 50, 50 + i*60);         }         // Display the bitmap in the picture box.         pictureBox1.BackgroundImage = b;         pictureBox1.Size = b.Size;     } } 

Figure 8.5: Adding scrolling support to custom content.



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

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