我可以使用下面的代码在图像上绘图.但我的问题是,这不是一条连续的路线.看起来好像坏了.有关更好的理解,请参见下图.
我的XAML:
<Grid x:Name="Gridimage1" Grid.Column="0">
<Image Name="image1" HorizontalAlignment="Left" VerticalAlignment="Top" Stretch="Fill" >
</Image>
</Grid>
我的c#代码:
#region "Drawing on image"
static WriteableBitmap writeableBitmap;
static Image i;
public void DrawingOnImage() // this function will be called after image load
{
if (image1.Source != null)
{
i = new Image();
RenderOptions.SetBitmapScalingMode(image1, BitmapScalingMode.NearestNeighbor);
RenderOptions.SetEdgeMode(image1, EdgeMode.Aliased);
BitmapSource BitmapSrc = new FormatConvertedBitmap(image1.Source as BitmapSource, PixelFormats.Default, null, 0);
//writeableBitmap = new WriteableBitmap((int)image1.ActualWidth, (int)image1.ActualHeight, 96, 96, PixelFormats.Bgr32, null);
writeableBitmap = new WriteableBitmap(BitmapSrc);
image1.Source = writeableBitmap;
//image1.Stretch = Stretch.None;
image1.HorizontalAlignment = HorizontalAlignment.Left;
image1.VerticalAlignment = VerticalAlignment.Top;
i = image1;
image1.MouseMove += new MouseEventHandler(i_MouseMove);
image1.MouseLeftButtonDown +=
new MouseButtonEventHandler(i_MouseLeftButtonDown);
image1.MouseRightButtonDown +=
new MouseButtonEventHandler(i_MouseRightButtonDown);
}
}
static void i_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DrawPixel(e);
}
static void i_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
DrawPixel(e);
}
}
static void DrawPixel(MouseEventArgs e)
{
double CR = i.Source.Height / i.ActualHeight;
double RR = i.Source.Width / i.ActualWidth;
int column = (int)(e.GetPosition(i).X * RR) ;
int row = (int)(e.GetPosition(i).Y * CR);
// Reserve the back buffer for updates.
writeableBitmap.Lock();
unsafe
{
// Get a pointer to the back buffer.
int pBackBuffer = (int)writeableBitmap.BackBuffer;
// Fin d the address of the pixel to draw.
pBackBuffer += row * writeableBitmap.BackBufferStride;
pBackBuffer += column * 4;
// Compute the pixel's color.
int color_data = 255 << 16; // R
color_data |= 128 << 8; // G
color_data |= 255 << 0; // B
// Assign the color data to the pixel.
*((int*)pBackBuffer) = color_data;
}
// Specify the area of the bitmap that changed.
writeableBitmap.AddDirtyRect(new Int32Rect(column, row, 1, 1));
// Release the back buffer and make it available for display.
writeableBitmap.Unlock();
}
#endregion
图像输出:
你可以看到我绘制的线条(粉红色).这不是一条连续的路线.我哪里失败了?
更新:
我的发现在@ loxxy的Inputs.Set oldx之后,oldy到零初始化.
if (oldx == 0 && oldy == 0)
{
writeableBitmap.DrawLineAa(column, row, column, row, SelectedColor);
}
else
{
if (Math.Abs(oldx - column) > 10 || Math.Abs(oldy - row) > 10)
{
writeableBitmap.DrawLineAa(column, row, column, row, SelectedColor);
}
else
{
writeableBitmap.DrawLineAa(column, row, oldx, oldy, SelectedColor);
}
}
oldx = column;
oldy = row;
最佳答案 由于您是逐像素绘制的,因此鼠标必须以更快的速度更新坐标.
而且我相信这与鼠标的DPI有关……你无能为力.
所以请尝试画一条线.在WPF中是这样的:
WriteableBitmapExtensions.DrawLine