1 回答
TA贡献1886条经验 获得超2个赞
您可以使用WriteableBitmap. 这非常快,但它通过将单个字节写入位图来工作,因此如果您需要将效果应用于绘图,那么您必须自己编写它们。这是一个如何使用WriteableBitmap. 在调试模式下,在我的计算机上的 1600 x 1200 像素图像上绘制 1000 条线(每条线由 1600 个点组成)需要大约 100 毫秒,但我确信这可以优化。
我只是随机绘制线条,但您可以从Canvas触控笔获取事件并捕获其位置,并在每次笔画后传递它们。
public partial class MainWindow : Window
{
private WriteableBitmap _bitmap;
private readonly Random _random = new Random();
private readonly Stopwatch _stopwatch = new Stopwatch();
private const int White = 0x00000000;
private const int Red = 0x00FF0000;
private int _width;
private int _height;
public MainWindow()
{
InitializeComponent();
CanvasImage.Loaded += OnLoaded;
}
private async void OnLoaded(object sender, RoutedEventArgs e)
{
_width = (int)DrawableCanvas.ActualWidth;
_height = (int)DrawableCanvas.ActualHeight;
_bitmap = new WriteableBitmap(_width, _height, 96, 96, PixelFormats.Bgr32, null);
CanvasImage.Source = _bitmap;
while (true)
{
unsafe
{
for (var index = 0; index < _width * _height; index++)
*((int*)_bitmap.BackBuffer + index) = White;
}
_stopwatch.Start();
for (var index = 0; index < 1000; index++)
{
var start = _random.Next(0, _width);
var points = Enumerable.Range(0, _width).Select(x => new Point((x + start) % _width, x % _height));
UpdateImage(points);
}
Debug.WriteLine($"Last 1000 draws took: {_stopwatch.ElapsedMilliseconds} ms");
_stopwatch.Reset();
await Task.Delay(300);
}
}
private void UpdateImage(IEnumerable<Point> points)
{
_bitmap.Lock();
foreach (var point in points)
{
var x = (int)point.X;
var y = (int)point.Y;
var offset = _width * y + x;
unsafe
{
*((int*)_bitmap.BackBuffer + offset) = Red;
}
}
_bitmap.AddDirtyRect(new Int32Rect(0, 0, _width, _height));
_bitmap.Unlock();
}
}
并查看:
<Grid>
<Border Width="1604" Height="1204" BorderThickness="2" BorderBrush="Blue">
<Canvas x:Name="DrawableCanvas">
<Image x:Name="CanvasImage"></Image>
</Canvas>
</Border>
</Grid>
- 1 回答
- 0 关注
- 231 浏览
添加回答
举报