计算一条线的精确像素 [英] Calculating Exact Pixels for a line
问题描述
说我想尽力做成一条直线,尽管可以有任何角度
Say i want to try to make a straight line albeit with any angle
public class Line : Control
{
public Point start { get; set; }
public Point end { get; set; }
public Pen pen = new Pen(Color.Red);
protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.DrawLine(pen, start, end);
base.OnPaint(e);
}
}
此行已在自定义控件上进行.
This line has been made on a custom control.
现在我该如何计算精确的像素,以便可以使用 MouseMove
进行命中测试.
Now how can i calculate the exact pixels on which the line has been made so i can implement a hit test with MouseMove
.
推荐答案
有Win32调用,用于枚举将使用GDI调用绘制的线条的像素.我相信这是您要完成的最佳技术.请参见 LineDDA 及其关联的回调
There are Win32 calls for enumerating the pixels of a line that would be drawn using GDI calls. I believe this is the best technique for what you're trying to accomplish. See LineDDA and its associated callback LineDDAProc.
这是在C#中使用它的方式.请注意,根据LineDDA的文档,终点不包括在输出中.
Here's how you would use it from C#. Note that the end point is not included in the output, as per the documentation of LineDDA.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
public static List<Point> GetPointsOnLine(Point point1, Point point2)
{
var points = new List<Point>();
var handle = GCHandle.Alloc(points);
try
{
LineDDA(point1.X, point1.Y, point2.X, point2.Y, GetPointsOnLineCallback, GCHandle.ToIntPtr(handle));
}
finally
{
handle.Free();
}
return points;
}
private static void GetPointsOnLineCallback(int x, int y, IntPtr lpData)
{
var handle = GCHandle.FromIntPtr(lpData);
var points = (List<Point>) handle.Target;
points.Add(new Point(x, y));
}
[DllImport("gdi32.dll")]
private static extern bool LineDDA(int nXStart, int nYStart, int nXEnd, int nYEnd, LineDDAProc lpLineFunc, IntPtr lpData);
// The signature for the callback method
private delegate void LineDDAProc(int x, int y, IntPtr lpData);
这篇关于计算一条线的精确像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!