别这么着急:)
用gdi+和gdi画图一样,大部分功能更简单了。
1、怎样画任意曲线,按下鼠标左键不放开始画图
2、画直线时,想然线条跟随鼠标,怎么实现?
3、怎样取颜色的反值?
你这三个问题,基本上是一个问题,就是想实现一种橡皮筋效果。
这里gdi+没有提供足够的支持,没提供异或笔SETROP2.(据说是为了和打印统一处理的缘故)
要实现异或有两种方法
1。通过调用API,直接调用SETROP2
2。调用ControlPaint类的静态方法DrawReversibleLine等。
下面是调用API的例子实现的矩形橡皮筋
aspx.net xingze老兄提供(想你啊)
----------------------------------------------
//更详细的例子:
class SelectRect
{
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
}
[DllImport("GDI32.DLL")]
static extern int SetROP2(IntPtr hdc,int nDrawMode);
[DllImport("USER32.DLL")]
static extern int DrawFocusRect(IntPtr hdc,ref RECT lpRect);
private const int R2_NOTXORPEN = 10;
//member
private RECT m_rect;
private Graphics m_g;
private IntPtr m_hDC;
public void begin
Move(Graphics g, int x,int y) //Call at MouseDown
{
m_g=g;
m_hDC=m_g.GetHdc();
m_rect.left = m_rect.right = x;
m_rect.top = m_rect.bottom = y;
DrawSelectRect();
//绘制
}
public void Move(int x,int y) //call at MouseMove
{
DrawSelectRect();
//清除
m_rect.right = x;
m_rect.bottom = y;
DrawSelectRect();
//绘制
}
public Rectangle EndMove() // call at MouseUp
{
DrawSelectRect();
//清除
m_g.ReleaseHdc(m_hDC);
m_g.Dispose();
RECT rc=NormalizeRect(m_rect);
return (new Rectangle(rc.left,rc.top,rc.right,rc.bottom));
}
private void DrawSelectRect()
{
int nOldDrawMode=SetROP2(m_hDC,R2_NOTXORPEN);
RECT rc=NormalizeRect(m_rect);
DrawFocusRect(m_hDC,ref rc);
SetROP2(m_hDC,nOldDrawMode);
}
//标准化RECT结构
private RECT NormalizeRect(RECT rc)
{
RECT tmpRc=rc;
if (rc.left>rc.right)
{
tmpRc.left = rc.right;
tmpRc.right = rc.left;
}
if(rc.top > rc.bottom)
{
tmpRc.top = rc.bottom ;
tmpRc.bottom = rc.top;
}
return tmpRc;
}
}
使用方法:
private SelectRect MySelRect=new SelectRect();
private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
MySelRect.begin
Move(this.CreateGraphics(),e.X,e.Y);
}
private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
MySelRect.Move(e.X,e.Y);
}
private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
Rectangle rc;
if (e.Button == MouseButtons.Left)
{
rc=MySelRect.EndMove();
}
}