C#使用Graphics在窗体上绘图(加滚动条)

来源:互联网 发布:宽带连接拨号软件 编辑:程序博客网 时间:2024/04/30 05:06

代码如下:

 public partial class Form1 : Form
    {
        Pen redPen = new Pen(Color.Red, 3);
        Size RectangleSize = new Size(200,200);
        Size EllipseSize = new Size(200, 150);
        public Form1()
        {
            InitializeComponent();
            this.AutoScrollMinSize = new Size(250,360);
        }


        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Size ScrollOffset = new Size(this.AutoScrollPosition);
            if ((e.ClipRectangle.Top + ScrollOffset.Width) < 350 && (e.ClipRectangle.Left + ScrollOffset.Height) < 250)
            {
            
            Rectangle rectangel = new Rectangle(new Point(0 + ScrollOffset.Width, 0 +ScrollOffset.Height), RectangleSize);
            Rectangle Ellipse = new Rectangle(new Point(50 + ScrollOffset.Width, 200 + ScrollOffset.Height), EllipseSize);
                var dc = e.Graphics;


                dc.DrawRectangle(redPen, rectangel);
                dc.DrawEllipse(redPen, Ellipse);
            }
           
        }
    }

   this.AutoScrollMinSize = new Size(250,360);这句是确定自动加载滚动条时窗体的大小。如果窗体小于这个值,程序就会自动加载滚动条。

   Size ScrollOffset = new Size(this.AutoScrollPosition); 这个是保存引用拖动滚动条时,窗体的位置信息。

e.ClipRectangle,是描述的客户区的矩形,即可能被遮盖的矩形左上角。因此,如果这个角在画图的范围内,那么就应该重新再画一次。

如果滚动条向下移动了10个单位,那么 相对于B的位置,就是B的height-10,由此表示B向上移动了10个单位。所以把判断条件加上了if方法中。

Rectangle rectangel = new Rectangle(new Point(0 + ScrollOffset.Width, 0 +ScrollOffset.Height), RectangleSize);
            Rectangle Ellipse = new Rectangle(new Point(50 + ScrollOffset.Width, 200 + ScrollOffset.Height), EllipseSize);

重画的点也是以剪切板为标准,因为第一个点的位置都是由滚动条来确定的。所以需要加上滚动条的位置参数。

1 0
原创粉丝点击