Udostępnij za pośrednictwem


Jak utworzyć pędzel gradientu liniowego

Aby utworzyć pędzel gradientu liniowego, użyj metody CreateLinearGradientBrush i określ właściwości pędzla gradientu liniowego oraz kolekcję stopni gradientu. Niektóre przeciążenia umożliwiają określenie właściwości pędzla. Poniższy kod pokazuje, jak utworzyć pędzel gradientu liniowego, aby wypełnić kwadrat, oraz czarny pędzel do narysowania konturu kwadratu.

Kod generuje dane wyjściowe pokazane na poniższej ilustracji.

ilustracja kwadratu wypełnionego pędzlem gradientowym liniowym

  1. Zadeklaruj zmienną typu ID2D1LinearGradientBrush.

        ID2D1LinearGradientBrush *m_pLinearGradientBrush;
    
  2. Użyj metody ID2D1RenderTarget::CreateGradientStopCollection, aby utworzyć ID2D1GradientStopCollection kolekcję z zadeklarowaną tablicą struktur D2D1_GRADIENT_STOP, jak pokazano w poniższym kodzie.

    Notatka

    Począwszy od systemu Windows 8, możesz użyć metody ID2D1DeviceContext::CreateGradientStopCollection, aby utworzyć kolekcję ID2D1GradientStopCollection1. Ten interfejs dodaje gradienty o wysokiej głębi koloru i interpolację gradientów w kolorach liniowych lub z góry wymnożonych. Aby uzyskać więcej informacji, zobacz stronę ID2DDeviceContext::CreateGradientStopCollection.

     

    // Create an array of gradient stops to put in the gradient stop
    // collection that will be used in the gradient brush.
    ID2D1GradientStopCollection *pGradientStops = NULL;
    
    D2D1_GRADIENT_STOP gradientStops[2];
    gradientStops[0].color = D2D1::ColorF(D2D1::ColorF::Yellow, 1);
    gradientStops[0].position = 0.0f;
    gradientStops[1].color = D2D1::ColorF(D2D1::ColorF::ForestGreen, 1);
    gradientStops[1].position = 1.0f;
    // Create the ID2D1GradientStopCollection from a previously
    // declared array of D2D1_GRADIENT_STOP structs.
    hr = m_pRenderTarget->CreateGradientStopCollection(
        gradientStops,
        2,
        D2D1_GAMMA_2_2,
        D2D1_EXTEND_MODE_CLAMP,
        &pGradientStops
        );
    
  3. Użyj ID2D1RenderTarget::CreateLinearGradientBrush, aby utworzyć pędzel gradientu liniowego, wypełnić kwadrat pędzlem i narysować kwadrat za pomocą czarnego pędzla.

    // The line that determines the direction of the gradient starts at
    // the upper-left corner of the square and ends at the lower-right corner.
    
    if (SUCCEEDED(hr))
    {
        hr = m_pRenderTarget->CreateLinearGradientBrush(
            D2D1::LinearGradientBrushProperties(
                D2D1::Point2F(0, 0),
                D2D1::Point2F(150, 150)),
            pGradientStops,
            &m_pLinearGradientBrush
            );
    }
    
    m_pRenderTarget->FillRectangle(&rcBrushRect, m_pLinearGradientBrush);
    m_pRenderTarget->DrawRectangle(&rcBrushRect, m_pBlackBrush, 1, NULL);
    

Odwołanie Direct2D