這裏有一個Windows窗體程序,繪製正方形的二維網格是隨機黑色或紅色:高效繪製二維網格在WPF
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Forms_Panel_Random_Squares
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Width = 350;
Height = 350;
var panel = new Panel() { Dock = DockStyle.Fill };
Controls.Add(panel);
var random = new Random();
panel.Paint += (sender, e) =>
{
e.Graphics.Clear(Color.Black);
for (int i = 0; i < 30; i++)
for (int j = 0; j < 30; j++)
{
if (random.Next(2) == 1)
e.Graphics.FillRectangle(
new SolidBrush(Color.Red),
i * 10,
j * 10,
10,
10);
}
};
}
}
}
產生的程序看起來是這樣的:
下面是使用Rectangle
對象爲每平方(幼稚)翻譯WPF:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
namespace WPF_Canvas_Random_Squares
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Width = 350;
Height = 350;
var canvas = new Canvas();
Content = canvas;
Random random = new Random();
Rectangle[,] rectangles = new Rectangle[30, 30];
for (int i = 0; i < rectangles.GetLength(0); i++)
for (int j = 0; j < rectangles.GetLength(1); j++)
{
rectangles[i, j] =
new Rectangle()
{
Width = 10,
Height = 10,
Fill = random.Next(2) == 0 ? Brushes.Black : Brushes.Red,
RenderTransform = new TranslateTransform(i * 10, j * 10)
};
canvas.Children.Add(rectangles[i, j]);
}
}
}
}
由於世界上的每個單元都有一個對象的開銷,WPF版本似乎是更多內存低效的方式。
有沒有一種方法可以以與Forms版本一樣高效的風格編寫該程序?或者是沒有辦法創建所有這些Rectangle
對象?
你想要的對象,或者只是改變背景顏色和你需要使用一個Canvas不是網格 –
的,我想呈現的狀態在一個二維數組。所以我不需要在視圖層面上沉重的對象表示。 – dharmatech
看看'DrawingContext'這個[SO回答](http://stackoverflow.com/a/2944417/479512)建議 –