Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

c# - Panel for drawing graphics and scrolling

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...