问题
I'm trying to write a tile-based game in WPF 4. I want the game board to scale to fit the window, so I'm using a Viewbox; but I want each tile to be on a nice, crisp pixel boundary. I might be wrong, but my understanding is that this is what the new UseLayoutRounding property is supposed to be for -- but it isn't working the way I expect.
Here's a window that demonstrates the issue:
<Window x:Class="Tyler.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="600" Height="400" Background="Black">
<Viewbox>
<Canvas Width="1000" Height="1000">
<Rectangle Canvas.Left="100" Canvas.Top="100"
Width="100" Height="100" Fill="Gray"/>
<Rectangle Canvas.Left="200" Canvas.Top="100"
Width="100" Height="100" Fill="Gray"/>
</Canvas>
</Viewbox>
</Window>
The two rectangles are adjacent, but because of the sub-pixel coordinates (resulting from the Viewbox's scaling), I end up with a darker gray seam between them. That's what I'm trying to get rid of -- I want them to blend together seamlessly.
But UseLayoutRounding doesn't seem to have this effect. I've tried setting UseLayoutRounding="True"
on the Window, the Viewbox, the Canvas, the Rectangles -- I've even tried putting it on all of them at once. There's no effect on the seam.
What am I missing (or misunderstanding)? How can I get layout rounding to work with a Viewbox?
回答1:
SnapsToDevicePixels=True
is what you want
<Viewbox SnapsToDevicePixels="True" >
<Canvas Width="1000" Height="1000">
<Rectangle Canvas.Left="100" Canvas.Top="100"
Width="100" Height="100" Fill="Gray"/>
<Rectangle Canvas.Left="200" Canvas.Top="100"
Width="100" Height="100" Fill="Gray"/>
</Canvas>
</Viewbox>
来源:https://stackoverflow.com/questions/1857289/why-does-uselayoutrounding-not-seem-to-work-with-viewbox