如何建立星形漸層筆刷

若要建立星形漸層筆刷,請使用 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方法。 此介面會在直線或 prmultlied 色彩中新增高色彩漸層和漸層的插補。 如需詳細資訊,請參閱 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 參考