Share via


如何建立星形漸層筆刷

若要建立星形漸層筆刷,請使用 ID2DRenderTarget::CreateRadialGradientBrush 方法,並指定星形漸層筆刷屬性和漸層停駐點集合。 某些多載可讓您指定筆刷屬性。 下列程式代碼示範如何建立星形漸層筆刷來填滿圓形,以及繪製圓形外框的實心黑色筆刷。

此程式代碼會產生下圖所示的輸出。

填滿星形漸層筆刷的圓形圖例

  1. 宣告ID2D1RadialGradientBrush類型的變數。

        ID2D1RadialGradientBrush *m_pRadialGradientBrush;
    
  2. 建立D2D1_GRADIENT_STOP結構的陣列,以放入漸層停駐點集合中。 D2D1_GRADIENT_STOP 結構包含漸層停駐點的位置和色彩。 位置表示筆刷中漸層停駐點的相對位置。 此值在 [0.0f, 1.0f] 範圍內,如下列程式代碼所示。

    // 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. 使用 ID2D1RenderTarget::CreateGradientStopCollection 方法,從先前宣告的 D2D1_GRADIENT_STOP 結構數位建立 ID2D1GradientStopCollection 集合。 然後,使用 CreateRadialGradientBrush 建立星形漸層筆刷。

    注意

    從 Windows 8 開始,您可以使用 ID2D1DeviceContext::CreateGradientStopCollection 方法來建立 ID2D1GradientStopCollection1 集合,而不是 ID2D1RenderTarget::CreateGradientStopCollection 方法。 這個介面會在直線或預乘色彩中加入高色彩漸層和漸層插補點。 如需詳細資訊,請參閱 ID2DDeviceContext::CreateGradientStopCollection 頁面。

     

    // The center of the gradient is in the center of the box.
    // The gradient origin offset was set to zero(0, 0) or center in this case.
    if (SUCCEEDED(hr))
    {
        hr = m_pRenderTarget->CreateRadialGradientBrush(
            D2D1::RadialGradientBrushProperties(
                D2D1::Point2F(75, 75),
                D2D1::Point2F(0, 0),
                75,
                75),
            pGradientStops,
            &m_pRadialGradientBrush
            );
    }
    
    m_pRenderTarget->FillEllipse(ellipse, m_pRadialGradientBrush);
    m_pRenderTarget->DrawEllipse(ellipse, m_pBlackBrush, 1, NULL);
    

Direct2D 參考