问题
I want to be able to use a panel or similar to draw graphics onto a Winform. I cannot seem to see anything regarding adding scrollbars if the graphics become larger than the control?
Is it possible to do this with a panel or is there a similar control that will allow it?
Thanks.
回答1:
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);
}
}
回答2:
I'm not 100% sure what you're trying to accomplish, but here is a similar SO question that might help you.
You could also try using a PictureBox that you would manually change its size as the graphics get larger. Then set your form AutoScroll to true.
来源:https://stackoverflow.com/questions/4305011/c-sharp-panel-for-drawing-graphics-and-scrolling