Sco*_*ski 2 c# mouse grid onmousemove cursor-position
我正在开发一个绘制简单点网格的应用程序.我希望鼠标在网格上的点之间捕捉,最终在网格上绘制线条.
我有一个方法,它接收当前鼠标位置(X,Y)并计算最近的网格坐标.
当我创建一个事件并尝试将鼠标移动到新坐标时,整个系统变得不稳定.鼠标不会在网格点之间平滑地捕捉.
我已经复制了下面的代码示例来说明我正在尝试做什么.有没有人有任何建议他们可以提供我如何消除鼠标运动中的跳跃?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GridTest
{
public partial class Form1 : Form
{
Graphics g;
const int gridsize = 20;
public Form1()
{
InitializeComponent();
g = splitContainer1.Panel2.CreateGraphics();
splitContainer1.Panel2.Invalidate();
}
private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
{
Drawgrid();
}
private void Drawgrid()
{
for (int x = 0; x < splitContainer1.Panel2.ClientSize.Width; x += gridsize)
{
for (int y = 0; y < splitContainer1.Panel2.ClientSize.Height; y += gridsize)
{ g.DrawLine(Pens.Black, new Point(x, y), new Point(x + 1, y)); }
}
}
private void splitContainer1_Panel2_MouseMove(object sender, MouseEventArgs e)
{
Point newPosition = new Point();
newPosition = RoundToNearest(gridsize, e.Location);
Cursor.Position = splitContainer1.Panel2.PointToScreen(newPosition);
}
private Point RoundToNearest(int nearestRoundValue, Point currentPoint)
{
Point newPoint = new Point();
int lastDigit;
lastDigit = currentPoint.X % nearestRoundValue;
if (lastDigit >= (nearestRoundValue/2))
{ newPoint.X = currentPoint.X - lastDigit + nearestRoundValue; }
else
{ newPoint.X = currentPoint.X - lastDigit; }
lastDigit = currentPoint.Y % nearestRoundValue;
if (lastDigit >= (nearestRoundValue / 2))
{ newPoint.Y = currentPoint.Y - lastDigit + nearestRoundValue; }
else
{ newPoint.Y = currentPoint.Y - lastDigit; }
return newPoint;
}
}
}
Run Code Online (Sandbox Code Playgroud)
不要修改光标位置.你不需要.
相反,绘制就像它被捕捉到网格一样.当用户点击某处时,只需从最近的网格点绘制线条.
例如,如果用户点击(197,198),但您知道最近的点实际上是(200,200),则只需绘制一条线到(200,200)而不是(197,198).
请不要乱用实际的光标位置.
我不知道是否有某种方法可以隐藏鼠标光标.如果有,您可以隐藏它并自己绘制,而无需修改实际位置.
归档时间: |
|
查看次数: |
4503 次 |
最近记录: |