C# 画箭头
绘制箭头
1,直接用平台库
Pen arrowPen = new Pen(Color.Blue);
arrowPen.Width = 4;
arrowPen.EndCap = System.Drawing.Drawing2D.LineCap.ArrowAnchor;
Graphics gfx = this.pCanvas.CreateGraphics();
gfx.DrawLine(arrowPen,
5, 5,
5, 100);
2,设置箭头样式
System.Drawing.Drawing2D.AdjustableArrowCap lineCap =
new System.Drawing.Drawing2D.AdjustableArrowCap(6, 6, true);
Pen redArrowPen = new Pen(Color.Red, 4);
redArrowPen.CustomEndCap = lineCap;
Graphics gfx = this.pCanvas.CreateGraphics();
gfx.DrawLine(redArrowPen,
25, 5,
25, 100);
3,手动绘制
//线的起点
PointF startPt = new PointF(100, 300);
//线的终点
PointF endPt = new PointF(200, 200);
//箭头的宽
float width = 10;
//箭头夹角
double angle = 60.0 / 180 * Math.PI;
//求BC长度
double widthBE = width / 2 / (Math.Tan(angle / 2));
//直线向量
Vector2 lineVector = new Vector2(endPt.X - startPt.X, endPt.Y - startPt.Y);
//单位向量
lineVector.Normalize();
//求BE向量
Vector2 beVector = (float)widthBE * -lineVector;
//求E点坐标
PointF ePt=new PointF();
//ePt - endPt = bcVector
ePt.X = endPt.X + beVector.X;
ePt.Y = endPt.Y + beVector.Y;
//因为CD向量和AB向量垂直,所以CD方向向量为
Vector2 cdVector = new Vector2(-lineVector.Y, lineVector.X);
//求单位向量
cdVector.Normalize();
//求CE向量
Vector2 ceVector = width / 2 * cdVector;
//求C点坐标,ePt - cPt = ceVector;
PointF cPt = new PointF();
cPt.X = ePt.X - ceVector.X;
cPt.Y = ePt.Y - ceVector.Y;
//求DE向量
Vector2 deVector = width / 2 * -cdVector;
//求D点,ePt-dPt = deVector;
PointF dPt = new PointF();
dPt.X = ePt.X - deVector.X;
dPt.Y = ePt.Y - deVector.Y;
//开始绘制
Graphics gfx = this.pCanvas.CreateGraphics();
//绘制线
gfx.DrawLine(Pens.Blue, startPt, endPt);
//绘制箭头
//gfx.DrawPolygon(Pens.Green,
// new PointF[]{
// cPt,dPt,endPt});
gfx.FillPolygon(Brushes.Green,
new PointF[]{
cPt,dPt,endPt});
手动绘制原理:
分为两部分绘制:
绘制直线较为简单,麻烦在绘制箭头(多边形)。
已知:aP(A点坐标),bP(B点坐标),θ角(angle表示),CD长度width.
求:点C坐标,点D坐标。
解:
1,求出向量AB abVector=bP-aP;,并且单位向量化。此时abVector代表了方向
2,BE的长度求解 widthBE= width / 2 / (Math.Tan(angle / 2)); (三角形BEC为直角三角形)。
3,求解向量BE beVector = (float)widthBE * -abVector; (由长度和AB单位向量决定)。
4,求解E点坐标 eP – bP = beVector ,所以 eP = bP + beVector .
5,4中求出了E点坐标,如果能够求出向量CE和向量ED,那么点C和点D的坐标就知道了。
因为向量CD和向量AB垂直,所以向量CD为:
cdVector = ( –abVector.Y , abVector.X);
同时对cdVector 单位化,此时cdVector 代表了CD方向。
6,则CE向量:
ceVector = ceWidth*cdVector ;
则点C eP – cP = ceVector ; 即 cP = eP – ceVector
同理, dP = eP – deVector;
7,此时求出了点 C和点D,加上点B可以构成一个Polygon了。