gpt4 book ai didi

c# - Brushes.White 使图形演示变慢

转载 作者:太空狗 更新时间:2023-10-29 19:47:05 25 4
gpt4 key购买 nike

下面是康威生命游戏在 WPF 中的一个(非常幼稚的)实现。这只是一个演示...

xaml:

<Window x:Class="wpf_conway_life_2013_05_19.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="500" Width="500">
<Grid>
<Canvas Name="canvas"
Width="auto"
Height="auto"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
</Canvas>
</Grid>
</Window>

代码隐藏:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace wpf_conway_life_2013_05_19
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

var random = new Random();

var data = new int[100, 100];

var dataB = new int[100, 100];

Func<int, int, int> at = (x, y) =>
{
if (x < 0) x = 100 + x;
if (x >= 100) x = x % 100;
if (y < 0) y = 100 + y;
if (y >= 100) y = y % 100;

return data[x, y];
};

for (var x = 0; x < 100; x++)
for (var y = 0; y < 100; y++)
data[x, y] = random.Next(2);

var rectangles = new Rectangle[100, 100];

for (var x = 0; x < 100; x++)
for (var y = 0; y < 100; y++)
{
rectangles[x, y] = new Rectangle();

canvas.Children.Add(rectangles[x, y]);
}

canvas.SizeChanged += (s, e) =>
{
for (var x = 0; x < 100; x++)
{
for (var y = 0; y < 100; y++)
{
rectangles[x, y].Width = canvas.ActualWidth / 100;
rectangles[x, y].Height = canvas.ActualHeight / 100;

Canvas.SetLeft(rectangles[x, y], (canvas.ActualWidth / 100) * x);
Canvas.SetTop(rectangles[x, y], (canvas.ActualHeight / 100) * y);
}
}
};

Action macroStep = () =>
{
dataB = new int[100, 100];

for (var x = 0; x < 100; x++)
{
for (var y = 0; y < 100; y++)
{
var neighbors = 0;

for (var i = -1; i <= 1; i++)
for (var j = -1; j <= 1; j++)
if (i == 0 && j == 0)
continue;
else
neighbors += at(x + i, y + j);

dataB[x, y] = data[x, y];

if (neighbors < 2) dataB[x, y] = 0;
if (neighbors == 3) dataB[x, y] = 1;
if (neighbors > 3) dataB[x, y] = 0;

rectangles[x, y].Fill = dataB[x, y] == 0 ? new SolidColorBrush(new Color()) : Brushes.Black;
}
}

data = dataB;
};

var timer = new DispatcherTimer();

timer.Tick += (s, e) => macroStep();

timer.Start();
}
}
}

这是它的样子:

enter image description here

如果我用 Brushes.White 替换 new SolidColorBrush(new Color()) 程序运行得更慢。为什么?

我正在使用 2010 Express 在 Windows 7 64 位上进行测试。

最佳答案

因为 new Color() 的 alpha 值为零,这意味着 WPF 不必渲染它,因为它是完全透明的 - 另一方面,白色的 alpha 是 255,这意味着它是必须渲染的完全纯白色。

关于c# - Brushes.White 使图形演示变慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16642461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com