0

Hello I am using Direct2D and i am using Radial Gradient Brush but i am stuck in one place.

My radial Gradient brush Code

struct SampleWindow : DesktopWindow

{
    //FOr Radial Gradient Brush

    ComPtr<ID2D1RadialGradientBrush> radialBrush;

    void CrateDeviceResources()
    {
        D2D1_GRADIENT_STOP stops[] =
        {
            {0.0f, COLOR_WHITE},
            {1.0f, COLOR_BLUE}
        };

        ComPtr<ID2D1GradientStopCollection> collection;
        m_target->CreateGradientStopCollection(stops, _countof(stops),collection.ReleaseAndGetAddressOf());

        D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props = {};
        m_target->CreateRadialGradientBrush(props,collection.Get(),radialBrush.ReleaseAndGetAddressOf());
    }

    void Draw()
    {
        auto size = m_target->GetSize();
        radialBrush -> SetCenter(Point2F(size.width / 2.0f, size.height / 2.0f));
        radialBrush -> SetRadiusX(size.width / 2.0f);
        radialBrush -> SetRadiusY(size.height / 2.0f);

        auto rect = RectF(0.0f, 0.0f, size.width, size.height);
        m_target -> FillRectangle(rect,radialBrush.Get());
    }

    void MouseMoved(int x, int y, WPARAM)
    {
        auto centere = radialBrush->GetCenter();
        radialBrush->SetGradientOriginOffset(Point2F(x - centere.x, y - centere.y));
        Invalidate();
    }
}

In the function mouse move when i use this line

auto centere = radialBrush->GetCenter();

my program breaks it tell me that

Access violation Exception

the DesktopWindow Class Code is:

BEGIN_MSG_MAP()
        MESSAGE_HANDLER(WM_PAINT, PaintHandler)
        MESSAGE_HANDLER(WM_DESTROY, DestroyHandler)
        MESSAGE_HANDLER(WM_SIZE, SizeHandler)
        MESSAGE_HANDLER(WM_DISPLAYCHANGE, DisplayChangeHandler)
        MESSAGE_HANDLER(WM_MOUSEMOVE, MouseMovedHandler)
    END_MSG_MAP()

LRESULT MouseMovedHandler(UINT, WPARAM wParam, LPARAM lParam,BOOL &)
    {
        MouseMoved(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam),wParam);
        return 0;
    }

     virtual void MouseMoved(int x, int y, WPARAM)
     {

     }

i make the MouseMoved function virtual so that i can ovverride this function in my other classes. i am not able to understand where i am doing wrong please correct me where should i make correction in my code.

Haseeb Khan
  • 930
  • 3
  • 19
  • 41

1 Answers1

0

the answer of this question is that Mouse Move function comes before the render target is initialized so to avoid this failure use this method

LRESULT MouseMovedHandler(UINT, WPARAM wParam, LPARAM lParam,BOOL &)
    {
        if (m_target)
        {
            MouseMoved(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam),wParam);
        }
        return 0;
    }

now the code will run fine

Haseeb Khan
  • 930
  • 3
  • 19
  • 41