I have a WPF application for drawing (Like Microsoft Paint) and I use WriteableBitmap and subscribe mouse event to do that.
It works perfectly and the ink tracks my mouse immediately when I run the program by Visual Studio no matter in debug mode or release mode
However, I get bad performance when I drawing by running the program exe file (\bin\Release\net5.0-windows\oooo.exe OR \bin\Debug\net5.0-windows\oooo.exe). the ink is drawn slower and has some delay after the mouse moving when drawing.
The difference (click to view gifs):
Even I build this application on local, I got the same bad result. Is there any thing I can fix this?
The code is as follows:
MainWindow.xaml
<Window x:Class="paint_test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow" Height="900" Width="1600"
Loaded="Window_Loaded">
<Grid>
<Canvas Name="MainCanvas" Background="Bisque"/>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
namespace paint_test
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MainCanvas.Children.Add(new PaintCanvas((int)MainCanvas.ActualWidth, (int)MainCanvas.ActualHeight));
}
}
}
PaintCanvas.cs
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace paint_test
{
public class PaintCanvas : System.Windows.Controls.Image
{
WriteableBitmap fullWriteableBmp;
int paintingSize = 10;
Color paintingColor = Colors.Blue;
public PaintCanvas(int width, int height)
{
RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.NearestNeighbor);
RenderOptions.SetEdgeMode(this, EdgeMode.Aliased);
fullWriteableBmp = BitmapFactory.New(width, height);
Source = fullWriteableBmp;
MouseDown += PaintCanvas_MouseDown;
MouseMove += PaintCanvas_MouseMove;
}
private void PaintCanvas_MouseDown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton != MouseButtonState.Pressed) return;
DrawPixel(e);
}
private void PaintCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton != MouseButtonState.Pressed) return;
DrawPixel(e);
}
private void DrawPixel(MouseEventArgs e)
{
int x1 = (int)e.GetPosition(this).X - (paintingSize / 2);
int y1 = (int)e.GetPosition(this).Y - (paintingSize / 2);
int x2 = (int)e.GetPosition(this).X + (paintingSize / 2);
int y2 = (int)e.GetPosition(this).Y + (paintingSize / 2);
fullWriteableBmp.FillEllipse(x1, y1, x2, y2, paintingColor);
}
}
}