如图 panel放置在背景图片上,遮挡住屋顶的位置,然后窗体放大后
放大以后位置跑偏了,怎么样设置才能让panel跟着背景图片动 一直遮挡屋顶部分。
解决方案
5
先讲一下原理吧。例如你的图片原来是200X200的,而你的panel的位置为x=20, y=20,长为10,宽为10。那么相对于pannel在图片中的相对位置就是x为20/200=0.1,y为20/200=0.1,长和宽都为10/200 = 0.05。按照这个比例关系,假如图片变成了原来的1.5倍,图片的长宽都是300,那么你的panel的位置和大小也要随之变化。那么panel的x为300*0.1=30,y位300*0.1=30,长和宽也是300*0.05=15。
那么剩下的就是要知道什么时候图片的大小发生改变,并在改变后更新panel的位置和大小。
本人看你图片好像是平铺占满整个form,那么你可以注册form的SizeChanged事件form.SizeChanged+=……。在事件的处理函数中获得图片的大小并根据比例关系更新panel的位置和大小
30
        RectangleF k;
        protected override void OnLoad(EventArgs e)
        {
            //记录下 Panel 与 Form 的相对位置
            k = new RectangleF(
                (float)panel1.Left / (float)Width,
                (float)panel1.Top / (float)Height,
                (float)panel1.Width / (float)Width,
                (float)panel1.Height / (float)Height);
        }
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            //重置 Panel 的相关属性
            panel1.Left = (int)(k.X * Width);
            panel1.Top = (int)(k.Y * Height);
            panel1.Width = (int)(k.Width * Width);
            panel1.Height = (int)(k.Height * Height);
        }
5
        protected override void OnLoad(EventArgs e)
        {
            foreach (Control c in Controls)
            {
                var k = new RectangleF(
                    (float)c.Left / (float)Width,
                    (float)c.Top / (float)Height,
                    (float)c.Width / (float)Width,
                    (float)c.Height / (float)Height);
                c.Tag = k;
            }
        }
        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            foreach (Control c in Controls)
            {
                var k = (RectangleF)c.Tag;
                c.Left = (int)(k.X * Width);
                c.Top = (int)(k.Y * Height);
                c.Width = (int)(k.Width * Width);
                c.Height = (int)(k.Height * Height);
            }
        }