Animating a CImage to fade in on creation

2019-08-21 20:04发布

问题:

I currently have a CView which consists of a single centralized CImage which displays upon immediate loading of my application.

I want to prettify it a little by making the CImage fade in on startup instead of simply being displayed (I already have a splash-screen, so I'm not asking for how to animate a CWnd).

In order to display my image, I have overrided the CView::OnDraw method, as follows:

void CWelcomeView::OnDraw( _In_ CDC* pDC ) 
{
    CView::OnDraw( pDC );

    static CImage backgroundImage;
    static bool bImageLoaded = false;

    if( !bImageLoaded )
    {
        backgroundImage.LoadFromResource( AfxGetInstanceHandle(), IDB_WELCOMESCREEN );

        bImageLoaded = true;
    }

    CRect clientRect;
    GetClientRect( &clientRect );

    // The detination rectangle should be the same size as the image:
    POINT pointTopLeft = {(clientRect.Width()-backgroundImage.GetWidth())/2, (clientRect.Height()-backgroundImage.GetHeight())/2};
    CRect destRect( pointTopLeft, CSize( backgroundImage.GetWidth(), backgroundImage.GetHeight() ) );

    // Draw the image in the right space:
    backgroundImage.Draw( pDC->GetSafeHdc(), destRect );
}

Now I'm not entirely sure how to go about fading it in on creation. My current plan of action is to create a timer based on std::chrono::steady_clock and change the alpha value of the CImage based on the difference between the current time point and the time at which the clock started (which I will keep as a member variable).

However, I'm not sure how to change the alpha value of the image as a whole?

Thanks in advance!

回答1:

Instead of using backgroundImage.Draw(), use AlphaBlend

backgroundImage.AlphaBlend(pDC->GetSafeHdc(), destRect
    , CRect(0, 0, backgroundImage.GetWidth(), backgroundImage.GetHeight())
    , bySrcAlpha);

Start the value of bySrcAlpha at 255 and decrement it by an appropriate value in your timer function.