c#做画板时怎样调用系统的函数去实现填充功能。
首先我们需要引用命名空间:using System.Runtime.InteropServices;
然后我们需要引用系统的扩展方法语句如下:
[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hdc, IntPtr
hgdiobj);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateSolidBrush(int crColor);
[DllImport("gdi32.dll")]
public static extern bool ExtFloodFill(IntPtr hdc, int
nXStart, int nYStart, int crColor, uint fuFillType);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
public static extern int GetPixel(IntPtr hdc, int x, int y);
public static uint FLOODFILLBORDER = 0;
public static uint FLOODFILLSURFACE = 1;
然后我们需要去调用上面的方法去实现填充功能。
IntPtr vDC = graphics.GetHdc();
IntPtr vBrush = CreateSolidBrush
(ColorTranslator.ToWin32(pp.Color));//(ColorTranslator.ToWin32
(Color.Red));
IntPtr vPreviouseBrush = SelectObject(vDC,
vBrush);
ExtFloodFill(vDC, e.X, e.Y, GetPixel(vDC, 5, 5),
FLOODFILLSURFACE);
SelectObject(vDC, vPreviouseBrush);
DeleteObject(vBrush);
graphics.ReleaseHdc(vDC);
我们需要注意的就是ExtFloodFill(vDC, e.X, e.Y, GetPixel(vDC, 5, 5),
FLOODFILLSURFACE)这个方法的使用。这才是我们真正需要的做些改变来实现
我们需要的功能。e.x,e.y获取当前的鼠标的位置,以这个点为圆心向它的四
面八方进行扩展去实现填充。
下面谈谈我们做画板时需要注意的一些事项:
using System.Drawing.Imaging;
//画椭圆
private void drawellipse()
{
button1.Image = new Bitmap(20, 20);
Graphics gra = Graphics.FromImage(button1.Image);
gra.SmoothingMode =
System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
gra.DrawEllipse(Pens.Black, 0, 0, 19, 19);
gra.Dispose();
}
SmoothingMode 平滑模式指定直线、曲线和已填充区域的边缘是否采用平滑处
理(又称锯齿消除功能)。我们在窗口初始化时调用这个方法实现在按钮上面
填充图片。
在初始化时我们初始化当前窗口的背景图片。
this.BackgroundImage = new Bitmap(this.ClientSize.Width,
this.ClientSize.Height);
///画图
private void drawp_w_picpath(Graphics gra)
{
gra.SmoothingMode =
System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
switch (number)
{
case 1:
gra.DrawEllipse(new Pen(pencolor), new
Rectangle(start, new Size(end.X - start.X, end.Y - start.Y)));
break;
case 2:
gra.DrawRectangle(new Pen(pencolor), new
Rectangle(start, new Size(end.X - start.X, end.Y - start.Y)));
break;
case 3:
gra.DrawLine(new Pen(pencolor), start, end);
break;
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
//mark = false;
Graphics gra = Graphics.FromImage(this.BackgroundImage);
drawp_w_picpath(gra);
gra.Dispose();
}
在窗口的mouseup事件时就在按钮上面画椭圆。