Panel for Drawing Graphics and Scrolling

Panel for drawing graphics and scrolling

Set the AutoScroll property to true and the AutoScrollMinSize property to the size of the image. The scrollbars will now automatically appear when the image is too large.

You'll want to inherit your own class from Panel so that you can set the DoubleBuffered property to true in the constructor. Flicker would be noticeable otherwise. Some sample code:

using System;
using System.Drawing;
using System.Windows.Forms;

class ImageBox : Panel {
public ImageBox() {
this.AutoScroll = true;
this.DoubleBuffered = true;
}
private Image mImage;
public Image Image {
get { return mImage; }
set {
mImage = value;
if (value == null) this.AutoScrollMinSize = new Size(0, 0);
else {
var size = value.Size;
using (var gr = this.CreateGraphics()) {
size.Width = (int)(size.Width * gr.DpiX / value.HorizontalResolution);
size.Height = (int)(size.Height * gr.DpiY / value.VerticalResolution);
}
this.AutoScrollMinSize = size;
}
this.Invalidate();
}
}
protected override void OnPaint(PaintEventArgs e) {
e.Graphics.TranslateTransform(this.AutoScrollPosition.X, this.AutoScrollPosition.Y);
if (mImage != null) e.Graphics.DrawImage(mImage, 0, 0);
base.OnPaint(e);
}
}

c# drawing on the panel and scrolling the result

The standard mistake is forgetting to offset your drawing by the scroll position. Use the panel's AutoScrollPosition property, like this:

    void panel1_Paint(object sender, PaintEventArgs e) {
e.Graphics.TranslateTransform(panel1.AutoScrollPosition.X, panel1.AutoScrollPosition.Y);
e.Graphics.DrawLine(Pens.Black, 0, 0, 300, 2000);
}

The Panel control is in general pretty cranky about painting, it was designed to be a container control. You typically also want it double-buffered and to force a repaint when it is being resized. Setting the DoubleBuffered and ResizeRedraw properties requires deriving your own control from Panel.

Make Panel scrollable

The scrollbars won't show up until there's actually something in the Panel that you can't see all of.

Try placing a larger control, such as a PictureBox, inside the Panel, and setting the PictureBox's initial size as larger than the Panel.



Related Topics



Leave a reply



Submit