简体   繁体   English

WPF-将图像绘制到画布上并反复擦除和重新绘制

[英]WPF - Drawing image to canvas and erasing and redrawing repeatedly

I currently have a canvas with an image background in a WPF application. 我目前在WPF应用程序中有一个带有图像背景的画布。 Above this canvas, I have a slider control. 在此画布上方,我有一个滑块控件。 I need to, as users slide the value of the slider back and forth, draw a red line straight down across the canvas. 当用户来回滑动滑块的值时,我需要在画布上垂直向下绘制一条红线。 I need to do this every time the slider value is changed such that the red line is always aligned with the slider's thumb. 每次更改滑块值时都需要执行此操作,以使红线始终与滑块的拇指对齐。 The big problem I'm having here is trying to figure out how to efficiently draw the line, and then "erase" the previously drawn line and drawing a new line at the new thumb value when user's change the slider's value. 我在这里遇到的最大问题是试图弄清楚如何有效地绘制线条,然后在用户更改滑块的值时“擦除”先前绘制的线条并在新的拇指值处绘制新的线条。 If I simply redraw the canvas's background image, the application lags a lot and doesn't work well (plus, this just straight out doesn't completely solve the problem as you can still see the previously drawn lines anyway). 如果我只是简单地重画画布的背景图像,则该应用程序会滞后很多并且不能很好地工作(此外,仅凭直截了当就无法完全解决问题,因为您仍然可以看到先前绘制的线条)。

Any help would be absolutely appreciated, particularly with examples as I this is my first WPF application in C# and I'm stilling getting a feel for it's uniqueness (as opposed to Windows Forms). 任何帮助将绝对受到赞赏,尤其是示例,因为这是我在C#中的第一个WPF应用程序,而且我仍对它的独特性(与Windows Forms相对)仍然有所感触。 Thanks a lot! 非常感谢!

Rather than trying to draw the line yourself, a more WPF way to approach it would be to use a Line object. 与其尝试自己绘制线条,不如使用WPF进行处理,可以使用Line对象。 See Shapes and Basic Drawing in WPF Overview . 请参见WPF概述中的形状和基本工程图 Since you want the line to be aligned with the Slider, you can use data binding to bind the X position of the line to the position of the Slider: 由于您希望线与滑块对齐,因此可以使用数据绑定将线的X位置绑定到滑块的位置:

<DockPanel>
    <Slider
        Name="HorizontalSlider"
        DockPanel.Dock="Top"
        Maximum="{Binding ActualWidth, ElementName=Canvas}"/>
    <Canvas Name="Canvas" Margin="5.5 0">
        <Line
            X1="{Binding Value, ElementName=HorizontalSlider}"
            Y1="0"
            X2="{Binding Value, ElementName=HorizontalSlider}"
            Y2="{Binding ActualHeight, RelativeSource={RelativeSource AncestorType=Canvas}}"
            Stroke="Red"/>
    </Canvas>
</DockPanel>

(Note that I cheated a little by setting the margin on the Canvas to 5.5. The thumb on the slider has some thickness and doesn't move the entire width of the slider control, so in order to get the line to line up with the center I tried to make the canvas have the same width as the track.) (请注意,我通过将Canvas的边距设置为5.5有点作弊。滑块上的拇指有一定的厚度,并且不会移动滑块控件的整个宽度,因此为了使线条与我试图使画布的宽度与轨道的宽度相同。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM