如何在 WPF 中调整 Canvas 的大小?
我正在编写一个 WPF 应用程序,其中有一个 Canvas
。该画布将在运行时自定义渲染。这有点像游戏,需要以像素为单位来衡量。我需要能够将我的 Canvas
设置为 478x478 像素(客户端矩形大小)。我不希望在我的 Canvas
上进行任何缩放或其他与分辨率无关的步骤。
我不确定这在 WPF 中是否可行,因为它的本质是与分辨率无关。我的问题:
- 如何在运行时调整
Canvas
的大小(要调用的函数?) - 当我调整
Canvas
的大小时,可渲染区域(客户端矩形)会是这样吗?尺寸?如果没有,我如何调整它的大小以确保客户端矩形具有特定的宽度/高度? - 是否可以以像素为单位设置
Canvas
的宽度/高度? WPF 与分辨率无关的方面如何干扰我想要做的事情? - 当我调整
Canvas
的大小时,其他控件是否会像 WPF 设计器中的设计那样适当调整大小?
提前致谢。
I'm writing a WPF app that has a Canvas
in it. This canvas will be custom rendered at runtime. It's sort of like a game in that it needs to be measured in pixels. I need to be able to set my Canvas
to 478x478 pixels (client rectangle size). I don't want any scaling or other resolution-independent steps to take place on my Canvas
.
I'm not sure if this is possible in WPF, since its nature is to be resolution independent. My questions:
- How do I resize my
Canvas
at runtime (function to call?) - When I resize my
Canvas
, is the renderable area (the client rectangle) going to be that size? If not, how can I resize it to make sure the client rectangle is a specific width/height? - Is it possible to set the width/height of the
Canvas
in Pixels? How does the resolution-independent aspect of WPF interfere with what I'm trying to do? - When I resize my
Canvas
, will other controls resize appropriately as they have been designed to do in the WPF designer?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
位于画布中的任何元素都不会根据画布的大小调整大小或重新定位。所以我认为设置画布的大小没有任何优势。也许您应该只设置窗口的固定大小。
否则,只需设置 Canvas.Width、Height 和 ClipToBounds=True,您就拥有一个固定大小的画布,可以使用 X/Y 坐标定位其子元素。
另外,您应该确保在画布上设置 SnapsToDevicePixels=True ,以便子元素具有清晰的像素对齐边界。
Any elements positioned in a canvas will not resize or reposition based upon the size of the canvas. So I don't think there's any advantage to setting the size of the canvas. Maybe you should just set a fixed size of the window instead.
Otherwise, just set the Canvas.Width, Height, and ClipToBounds=True and you have a fixed sized canvas that positions its child elements with X/Y coordinates.
Also you should be sure to set SnapsToDevicePixels=True on the canvas so that child elements will have crisp pixel-aligned bounds.
调整大小是蛋糕:
这设置了大小,您可以渲染到此之外的坐标,但它将被剪裁。您可以将画布包裹在滚动条内,以允许用户查看画布高度/宽度之外的内容。
至于你的其余问题,我想你可以看到这个SO问题答案
resizing is cake:
this sets the size, you CAN render to coordinates outside of this, but it will be clipped. You can wrap your canvas inside a scroller to allow the user to see what is outside the height/width of the canvas.
as for the rest of your questions, i think you can see this SO question for your answers
2020 年更新:在 WPF .NET CORE 上:如果
Canvas
是Viewbox
的子级,则内容会自动缩放到Viewbox
高度,并且宽度。Update 2020: on WPF .NET CORE: If the
Canvas
is a child of aViewbox
, the content is automatically scaled to theViewbox
height and width.