最近因为工作的原因,修改了一些同事写的Silverlight程序。知道Silverlight是WPF的一个子集,倒是很想看看WPF能有怎样一个效率表现。想起以前做过的一个“质点链”的Demo.于是就抄起VS2008将例子改写成WPF。
:
(完整项目文件) 1 public partial class Window1 : Window
2 {
3 private Ellipse[] circles;
4 public Window1()
5 {
6 InitializeComponent();
7 InitCirlces(100);
8 }
9
10 private void InitCirlces(int nCircle)
11 {
12 circles =new Ellipse[nCircle];
13 for(int i=0; i<nCircle; ++i)
14 {
15 Ellipse c = new Ellipse();
16 c.Height = 3;
17 c.Width = 3;
18 c.Stroke = new SolidColorBrush(Colors.Black);
19 c.Visibility= Visibility.Visible;
20 c.RenderTransform = new TranslateTransform();
21 Canvas.SetTop(c, 0);
22 Canvas.SetLeft(c, 0);
23 board.Children.Add(c);
24 circles[i]=c;
25 }
26
27
28 }
29 private void Window_MouseMove(object sender, MouseEventArgs e)
30 {
31 Point p=e.GetPosition(this);
32 var firstC = circles[0];
33 SetPos(firstC, p);
34 for (int i = 1; i < circles.Length; ++i )
35 {
36 Ellipse c = circles[i];
37 Point curP = GetPos(c);
38 Vector v = p - curP;
39 double len = v.Length;
40 if (len > 5)
41 {
42 v.Normalize();
43 v = v * (len - 5);
44 p = curP + v;
45 SetPos(c, p);
46 }else
47 {
48 p = curP;
49 }
50 }
51
52 }
53
54 private void SetPos(UIElement ue, Point p)
55 {
56 TranslateTransform tr = ue.RenderTransform as TranslateTransform;
57 tr.X = p.X;
58 tr.Y = p.Y;
59 //Canvas.SetTop(ue, p.Y);
60 //Canvas.SetLeft(ue, p.X);
61 }
62
63 private Point GetPos(UIElement ue)
64 {
65 TranslateTransform tr = ue.RenderTransform as TranslateTransform;
66 return new Point(tr.X, tr.Y);
67 //return new Point(Canvas.GetLeft(ue), Canvas.GetTop(ue));
68 }
69
70 } 实际运行结果很不理想。cpu占用率很高。通过性能分析工具发现,大多数时间都浪费在了TranslateTransform.Set_X和TranslateTransform.Set_Y上。
刚刚翻看WPF不足半天,不敢确认效率低是WPF本身的问题,还是自己选择的实现方式的问题。
如果有好的建议,请留言。
:(完整项目文件)