[英]How do I keep the positions of my Buttons the same on a Canvas?
I have a WPF Window that has a Image in the background as a canvas. 我有一个WPF窗口,在后台有一个Image作为画布。 It is a picture of a pirate ship. 这是一艘海盗船的照片。 I want to have buttons attached to certain points on the image which stay the same even if the size of the window is altered. 我希望按钮附加到图像上的某些点,即使窗口的大小发生变化也保持不变。 With a fixed Window size this is fine. 使用固定的窗口大小,这很好。 Can I select Hotspots at all where my Buttons will stay in touch with the same position on the image? 我可以选择热点,我的按钮会与图像上的相同位置保持联系吗? Or do I use percentage positioning for the buttons? 或者我使用按钮的百分比定位?
This may be a lot to ask of WPF. 这对WPF来说可能有很多要求。
The buttons are on top of the canvas. 按钮位于画布顶部。
Thanks 谢谢
Assuming your Background Image stretches according to Window Size, I'd use a Converter
and set Canvas.Top
and Canvas.Left
based on a percentage. 假设您的背景图像根据窗口大小拉伸,我将使用Converter
并根据百分比设置Canvas.Top
和Canvas.Left
。
You could either code your own IValueConverter
that accepts the Canvas.Height
and Canvas.Width
, and a ConverterParameter identifying what percentage you want of the value, or I have a fairly generic Math Converter on my blog that you are free to use if you prefer. 您可以编写自己的IValueConverter
接受Canvas.Height
和Canvas.Width
,以及ConverterParameter识别您想要的值百分比,或者我在博客上有一个相当通用的Math Converter,如果您愿意,可以自由使用。
<Button Canvas.Top="{Binding ElementName=MyCanvas, Path=ActualHeight, Converter={StaticResource MathConverter}, ConverterParameter=@VALUE*.25}"
Canvas.Left="{Binding ElementName=MyCanvas, Path=ActualWith, Converter={StaticResource MathConverter}, ConverterParameter=@VALUE*.25}"
... />
(I forget if Height
/ Width
or ActualHeight
/ ActualWidth
is the more accurate value - you may need to test that one) (我忘了如果Height
/ Width
或ActualHeight
/ ActualWidth
是更准确的值 - 你可能需要测试那个)
You could take a common ancestor of the canvas and buttons, give it a fixed size, and wrap it in a Viewbox
. 你可以采用画布和按钮的共同祖先,给它一个固定的大小,并将其包装在Viewbox
。 Then you can let the Viewbox
take care of scaling for you. 然后,您可以让Viewbox
为您进行缩放。 The entire scene--buttons, image, and anything else--will be scaled together, so you won't need to manually adjust any positioning. 整个场景 - 按钮,图像和其他任何内容 - 将被缩放在一起,因此您无需手动调整任何定位。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.