Nếu bạn muốn vẽ một đường, bạn shouldn không chỉ thay đổi màu sắc của một pixel tại một thời điểm, mà là lưu vị trí của chuột trong mỗi phương thức xử lý sự kiện MouseMove
.
Sau đó, bạn nên vẽ một dòng giữa vị trí trước đó (vị trí được lưu từ lần xuất hiện sự kiện trước đó) và vẽ Line
giữa hai điểm đó. Điều này sẽ làm cho các dòng được liên tục. Thông tin về các đường vẽ trên WriteableBitmap
có thể tìm thấy tại đây: Drawing line using WPF WriteableBitmap.BackBuffer.
Sau khi vẽ đường, đừng quên cập nhật vị trí trước đó đã lưu vào vị trí hiện tại :).
CẬP NHẬT
Tôi cũng đã tìm thấy một giải pháp khác.
Xác định XAML với hình ảnh bạn muốn vẽ trên:
<Window x:Class="SampleWPFApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="500" Width="520" Loaded="Window_Loaded" PreviewMouseDown="Window_PreviewMouseDown">
<Grid x:Name="layoutRoot" Background="Transparent">
<Image x:Name="image" />
</Grid>
Và sau đó, thêm mã đằng sau với những sự kiện xử lý:
//set width and height of your choice
RenderTargetBitmap bmp = null;
//...
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//initialize RenderTargetBitmap object
bmp = new RenderTargetBitmap((int)this.ActualWidth, (int)this.ActualHeight, 90, 90, PixelFormats.Default);
//set initialized bmp as image's source
image.Source = bmp;
}
/// <summary>
/// Helper method drawing a line.
/// </summary>
/// <param name="p1">Start point of the line to draw.</param>
/// <param name="p2">End point of the line to draw.</param>
/// <param name="pen">Pen to use to draw the line.</param>
/// <param name="thickness">Thickness of the line to draw.</param>
private void DrawLine(Point p1, Point p2, Pen pen, double thickness)
{
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
//set properties of the Pen object to make the line more smooth
pen.Thickness = thickness;
pen.StartLineCap = PenLineCap.Round;
pen.EndLineCap = PenLineCap.Round;
//write your drawing code here
drawingContext.DrawLine(pen, p1, p2);
}
}
Nguồn
2012-01-15 13:04:57
Có thể trùng lặp: http://stackoverflow.com/questions/3000591/drawing-line-using-wpf-writeablebitmap-backbuffer –