我在winform下用GDI画图,大概的需求是这样:
1,给点两个点AB。同时指定AB的颜色。
2,将AB连线拓宽5个像素,构成一个矩形。
3,按照AB连线的方向,用AB之间渐变的颜色绘制这个矩形。上面第二步的时候计算就有点点麻烦,第三步的时候我要用LinearBrush来填充,可是LinearBrush只能按照一个与坐标轴平行的矩形来填充,而不能按照AB连线之间的方向来填充。大家有什么好的办法吗?
1,给点两个点AB。同时指定AB的颜色。
2,将AB连线拓宽5个像素,构成一个矩形。
3,按照AB连线的方向,用AB之间渐变的颜色绘制这个矩形。上面第二步的时候计算就有点点麻烦,第三步的时候我要用LinearBrush来填充,可是LinearBrush只能按照一个与坐标轴平行的矩形来填充,而不能按照AB连线之间的方向来填充。大家有什么好的办法吗?
private void DrawLine(Graphics g, Point A,Point B,Color cA,Color cB)
{
LinearGradientBrush lgb = new LinearGradientBrush(A, B, cA, cB);
Pen pen = new Pen(lgb,5);
g.DrawLine(pen, A, B);
pen.Dispose();
lgb.Dispose();
}
{
using (Graphics g = e.Graphics)
{
DrawGradienLine(g, new Point(100, 100), new Point(180, 240), Color.RoyalBlue, Color.PeachPuff);
}
}
static void DrawGradienLine(Graphics g, Point p1, Point p2, Color c1, Color c2)
{
PointF v = new PointF(p2.X - p1.X, p2.Y - p1.Y);
double angle = Math.Atan2( v.Y, v.X); // get the angle to the X-axis
double length = Math.Sqrt(v.X * v.X + v.Y * v.Y); // get the length of p1p2 RectangleF rect = new RectangleF( 0, 0, (float)length, 0);
rect.Inflate(0, 5); // inflate with (actually) 10 pixels :) g.TranslateTransform( p1.X, p1.Y); // translate to p1 AFTER rotation
g.RotateTransform((float)(angle * 180 / Math.PI)); // <--- rotation here
g.FillRectangle(new LinearGradientBrush(rect, c1, c2,LinearGradientMode.Horizontal), rect);
}Hope this might help.
这个才是正确的
两点画矩形就是用DrowRectangle来画的
要填充的话就FillRectangle();
Free free to ignore my post :)