WPF画布实时刷新的2种方法
来源:互联网 发布:unity3d中自动寻路 编辑:程序博客网 时间:2024/06/09 17:14
WPF项目上,需要在Canvas上重复的画图,并将每次的图保存起来。画倒是没什么,但发现过程中窗体一直处于空白状态,直到结束Canvas上才显示内容。网上找了些资料,也还是没搞定,反正大概知道是线程间的交互问题。最后,终于找到了2种解决的办法,写了个例子收集下来,以后反正用的到。例子很简单,也就在主窗体上放一个Canvas和一个Button,点击Button会刷新10次画布。
MainWindow.xaml主界面代码
<Grid> <Canvas Height="232" HorizontalAlignment="Left" Margin="12,12,0,0" Name="canvas1" VerticalAlignment="Top" Width="467"></Canvas> <Button Content="Button" Height="23" Name="button1" Width="75" Click="button1_Click" Margin="12,265,416,23" /> </Grid>MainWindow.xaml.cs后台代码
第一种实现
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { for (int i = 0; i < 10; i++) { if (i % 2 == 0) { Ellipse el = new Ellipse(); el.Height = 30; el.Width = 60; el.Fill = Brushes.Red; el.Stroke = Brushes.Black; canvas1.Children.Add(el); } else { Ellipse el = new Ellipse(); el.Height = 30; el.Width = 60; el.Fill = Brushes.Yellow; el.Stroke = Brushes.Green; canvas1.Children.Add(el); } System.Threading.Thread.Sleep(1000); DispatcherHelper.DoEvents(); } } } public static class DispatcherHelper { [SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public static void DoEvents() { DispatcherFrame frame = new DispatcherFrame(); Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background, new DispatcherOperationCallback(ExitFrames), frame); try { Dispatcher.PushFrame(frame); } catch (InvalidOperationException) { } } private static object ExitFrames(object frame) { ((DispatcherFrame)frame).Continue = false; return null; } }第二种实现
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { Thread anotherThread = new Thread(() => { for (int i = 0; i < 10; i++) { canvas1.Dispatcher.BeginInvoke((Action)(() => { canvas1.Children.Add(new Ellipse { Height = 30, Width = 60, Fill = i % 2 == 0 ? Brushes.Red : Brushes.Yellow, Stroke = i % 2 == 0 ? Brushes.Black : Brushes.Green }); })); Thread.Sleep(1000); } }); anotherThread.SetApartmentState(ApartmentState.STA); anotherThread.Start(); } }
- WPF画布实时刷新的2种方法
- recycler实时刷新的方法
- HTML5画布的实时画图
- Delphi 画布或者窗体实时刷新时会出现闪烁的效果
- 实时刷新图形数据的方法
- WPF+SignalR实现用户列表实时刷新
- 两种创建画布方法的差别
- WPF InkCanvas画布
- canvas的方法--画布的基本方法
- WPF 下 label 的刷新
- 网页数据的实时刷新
- 网页数据的实时刷新
- 实现实时刷新的效果
- Swing实时刷新的实现
- TableView的刷新问题(2种方法
- 一种基于画布的绝对定位方法
- Canva画布类的常用方法总结
- h5的canvas画布常用方法
- Problem 1 东风谷早苗(robot.cpp/c/pas)
- 对listBox控件 数据项进行操作 批量加入到另一个listBox列表框中
- JAVA WEB 项目无法发布?
- log4j xml配置详解
- log4j XML 配置文件
- WPF画布实时刷新的2种方法
- sql随机数
- 从google code svn下载代码 提示svn url不存在的解决方法
- JavaScript_form表单非空、密码验证。
- python3之数字(在实际应用中的数字--变量和基本表达式)
- Windows日志操作总结 For .NET
- 一步一步写算法(之prim算法 下)
- 图片
- Android中获得一个扇形的剪裁区