Search code examples
visual-c++mfcgdi

Drawing a line with a gradient color with VC++ & MFC


My question is same as the following link

Drawing a line with a gradient color

I need to draw a curve with gradient color. Color should very from light blue to dark blue.I need to do it using VC++ and MFC. CPen class seems to provide only option of using LOGBRUSH. There are options to use various gradient brushes with closed shapes but not with lines or curves. I have plans to draw curve in small segments of lines with each segment of different shade thus forming a gradient. Is their any easier way?


Solution

  • You can do this with Gdi+

    First you need to initialize Gdi+ See for example this link.

    #include <Gdiplus.h>
    using namespace Gdiplus;
    ...
    
    struct GdiplusInit {
        GdiplusInit() {
            GdiplusStartupInput inp;
            GdiplusStartupOutput outp;
            GdiplusStartup(&token_, &inp, &outp);
        }
        ~GdiplusInit() {
            GdiplusShutdown(token_);
        }
    private:
        ULONG_PTR token_;
    } gdiplusInit; //This will initialize Gdi+ once, and shuts it down on exit
    

    To duplicate the C# example in your question:

    void CMyWnd::OnPaint()
    {
        CPaintDC dc(this);
    
        Graphics gr(dc);
    
        Point x = Point(0, 0);
        Point y = Point(100, 100);
    
        LinearGradientBrush brush(x, y, Color(255, 255, 255), Color(255, 0, 0));
        Gdiplus::Pen pen(&brush, 2.0f);
        gr.DrawLine(&pen, x, y);
    
    }