我在winform下用GDI画图,大概的需求是这样:
1,给点两个点AB。同时指定AB的颜色。
2,将AB连线拓宽5个像素,构成一个矩形。
3,按照AB连线的方向,用AB之间渐变的颜色绘制这个矩形。上面第二步的时候计算就有点点麻烦,第三步的时候我要用LinearBrush来填充,可是LinearBrush只能按照一个与坐标轴平行的矩形来填充,而不能按照AB连线之间的方向来填充。大家有什么好的办法吗?

解决方案 »

  1.   

    lz到底用GDI还是GDI+,这个很不一样的!从lz问题看来是GDI+,GDI没有LinearBrush。你可以计算出AB点对水平的Matrix,然后把Matrix应用到LinearBrush即可。
      

  2.   


     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();
            }
      

  3.   

    You may draw a rectangle, fill it, then rotate it :-)        protected override void OnPaint(PaintEventArgs e)
            {
                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.
      

  4.   


    这个才是正确的
    两点画矩形就是用DrowRectangle来画的
    要填充的话就FillRectangle();
      

  5.   

    GentleCat's method is a better one.
    Free free to ignore my post :)
      

  6.   

    try to keep it simple and smart...
      

  7.   

    确实是,我第一次就是用了类似gomoku老大的方法,旋转刷子,搞的太复杂了,调了半天也没完全调对,所以上来看看有没有别的解决方法。果然还是可以像GentleCat 那样写的很简洁啊,谢谢了!