更改父级时恢复PictureBox 的先前绝对位置? [英] Recover previous absolute position for PictureBox when Parent is changed?

查看:25
本文介绍了更改父级时恢复PictureBox 的先前绝对位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 GUI 中,我需要将 PictureBoxesParents 更改为背景 PictureBox,以便透明度正常工作.

In my GUI, i need to change Parents of PictureBoxes to the background PictureBox so that the transparency works correctly.

但是,更改父级也会更改图片框的位置.我曾尝试通过 PointToClient 获取图片框的绝对位置,但它不起作用.我将坐标放在注释中,即使图像明显改变了位置,它们在分配新父级后也不会改变.此外,我不认为它可能会起作用,因为它正在传递一个点,而不是一个包含更多关于父母的信息的对象,以及推断绝对位置所需的东西.

However, changing the parent also changes the location of the pictureboxes. I have tried grabbing the absolute location of the picture box via the PointToClient, but it doesn't work. I put the coordinates in the comments, and they don't change after assigning the new parent even though the image visibly changes location. Furthermore, I don't expect that it could possibly work as it's being passed a point, not an object with more information about parents and whatnot that's needed to deduce the absolute position.

推断元素绝对位置的正确方法是什么,以便我可以在其父元素更改后将图像移动到正确位置?或者有没有更好的方法来做到这一点?

What is the correct way to deduce the absolute position of an element so that I can move the image to the correct location after its parent changes? Or is there a better way to do this?

Point oldRel = pictureBox4.Location; //258, 109
Point oldAbs = PointToClient(oldRel); //75, -96
//Commenting out this line fixes the image shift but ruins the transparency
pictureBox4.Parent = pictureBox2;  
Point newRel = pictureBox4.Location; //258, 109
Point newAbs = PointToClient(pictureBox4.Location); //75, -96

推荐答案

这会将 Control child 从一个 Parent 移动到一个新的 Parent,保持绝对屏幕位置不变:

This will move a Control child from one Parent to a new one, keeping the absolute screen position intact:

void MoveTo(Control child, Control newParent )
{
    child.Location = newParent.PointToClient(child.PointToScreen(Point.Empty));
    child.Parent = newParent;
}

PointToClientPointToScreen 的技巧是从右父控件使用它们;不设置控件将默认为 Form,这将错过父级的实际位置..

The trick with PointToClient and PointToScreen is to use them from the right parent control; not setting the control will default to the Form, which will miss out on the actual position of the parent..

这篇关于更改父级时恢复PictureBox 的先前绝对位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆