XamlCompositionBrushBase 类

定义

提供一个基类,用于创建使用 CompositionBrush 绘制区域的 XAML 画笔。

public ref class XamlCompositionBrushBase : Brush
/// [Windows.Foundation.Metadata.ContractVersion(Windows.Foundation.UniversalApiContract, 262144)]
/// [Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
/// [Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
class XamlCompositionBrushBase : Brush
[Windows.Foundation.Metadata.ContractVersion(typeof(Windows.Foundation.UniversalApiContract), 262144)]
[Windows.Foundation.Metadata.MarshalingBehavior(Windows.Foundation.Metadata.MarshalingType.Agile)]
[Windows.Foundation.Metadata.Threading(Windows.Foundation.Metadata.ThreadingModel.Both)]
public class XamlCompositionBrushBase : Brush
Public Class XamlCompositionBrushBase
Inherits Brush
继承
Object Platform::Object IInspectable DependencyObject Brush XamlCompositionBrushBase
派生
属性

Windows 要求

设备系列
Windows 10 Creators Update (在 10.0.15063.0 中引入)
API contract
Windows.Foundation.UniversalApiContract (在 v4.0 中引入)

示例

此示例演示自定义画笔的定义,该自定义画笔绘制 UIElement 后面的模糊副本,其中使用 Win2D 模糊效果和 CompositionBackdropBrush 应用画笔:

public sealed class BackdropBlurBrush : XamlCompositionBrushBase
{
    public static readonly DependencyProperty BlurAmountProperty = DependencyProperty.Register(
        "BlurAmount",
        typeof(double),
        typeof(BackdropBlurBrush),
        new PropertyMetadata(0.0, new PropertyChangedCallback(OnBlurAmountChanged)
        )
    );

    public double BlurAmount
    {
        get { return (double)GetValue(BlurAmountProperty); }
        set { SetValue(BlurAmountProperty, value); }
    }

    private static void OnBlurAmountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var brush = (BackdropBlurBrush)d;
        // Unbox and set a new blur amount if the CompositionBrush exists.
        brush.CompositionBrush?.Properties.InsertScalar("Blur.BlurAmount", (float)(double)e.NewValue);            
    }

    public BackdropBlurBrush()
    {
    }

    protected override void OnConnected()
    {
        // Delay creating composition resources until they're required.
        if (CompositionBrush == null)
        {
            var backdrop = Window.Current.Compositor.CreateBackdropBrush();                

            // Use a Win2D blur affect applied to a CompositionBackdropBrush.
            var graphicsEffect = new GaussianBlurEffect
            {
                Name = "Blur",
                BlurAmount = (float)this.BlurAmount,
                Source = new CompositionEffectSourceParameter("backdrop")
            };

            var effectFactory = Window.Current.Compositor.CreateEffectFactory(graphicsEffect, new[] { "Blur.BlurAmount" });
            var effectBrush = effectFactory.CreateBrush();

            effectBrush.SetSourceParameter("backdrop", backdrop);

            CompositionBrush = effectBrush;
        }
    }

    protected override void OnDisconnected()
    {
        // Dispose of composition resources when no longer in use.
        if (CompositionBrush != null)
        {
            CompositionBrush.Dispose();
            CompositionBrush = null;
        }
    }
}
Public NotInheritable Class BackdropBlurBrush
    Inherits XamlCompositionBrushBase

    Public Shared ReadOnly BlurAmountProperty As DependencyProperty = DependencyProperty.Register(
            "BlurAmount",
            GetType(Double),
            GetType(BackdropBlurBrush),
            New PropertyMetadata(0.0, New PropertyChangedCallback(AddressOf OnBlurAmountChanged)
            )
        )

    Public Property BlurAmount As Double
        Get
            Return DirectCast(GetValue(BlurAmountProperty), Double)
        End Get
        Set
            SetValue(BlurAmountProperty, Value)
        End Set
    End Property

    Private Shared Sub OnBlurAmountChanged(d As DependencyObject, e As DependencyPropertyChangedEventArgs)
        Dim brush = DirectCast(d, BackdropBlurBrush)
        ' Unbox And set a New blur amount if the CompositionBrush exists.
        brush.CompositionBrush?.Properties.InsertScalar("Blur.BlurAmount", Convert.ToSingle(DirectCast(e.NewValue, Double)))
    End Sub

    Protected Overrides Sub OnConnected()
        If Me.CompositionBrush Is Nothing Then

            Dim backdrop As CompositionBackdropBrush = Window.Current.Compositor.CreateBackdropBrush()

            ' Use a Win2D blur affect applied to a CompositionBackdropBrush.
            Dim graphicsEffect As GaussianBlurEffect = New GaussianBlurEffect()
            graphicsEffect.Name = "Blur"
            graphicsEffect.BlurAmount = Me.BlurAmount
            graphicsEffect.Source = New CompositionEffectSourceParameter("backdrop")

            Dim effectFactory As CompositionEffectFactory = Window.Current.Compositor.CreateEffectFactory(graphicsEffect, New String() {"Blur.BlurAmount"})
            Dim effectBrush As CompositionEffectBrush = effectFactory.CreateBrush()

            effectBrush.SetSourceParameter("backdrop", backdrop)

            CompositionBrush = effectBrush
        End If
    End Sub

    Protected Overrides Sub OnDisconnected()
        ' Dispose of composition resources when no longer in use.
        If CompositionBrush IsNot Nothing Then
            CompositionBrush.Dispose()
            CompositionBrush = Nothing
        End If
    End Sub
End Class

对于下面的 C++/WinRT 代码示例,需要将 Midl 文件 (.idl) 文件添加到项目中。

// BackdropBlurBrush.idl
namespace MyApp
{
    [default_interface]
    runtimeclass BackdropBlurBrush : Windows.UI.Xaml.Media.XamlCompositionBrushBase
    {
        BackdropBlurBrush();
        static Windows.UI.Xaml.DependencyProperty BlurAmountProperty{ get; };
        Double BlurAmount;
    }
}
// pch.h
// You'll need to install the Microsoft Win2D NuGet package for this code example.
#include <winrt/Microsoft.Graphics.Canvas.Effects.h>
#include <winrt/Windows.Graphics.Effects.h>

// BackdropBlurBrush.h.
struct BackdropBlurBrush : BackdropBlurBrushT<BackdropBlurBrush>
{
    BackdropBlurBrush() = default;

    static Windows::UI::Xaml::DependencyProperty BlurAmountProperty() { return m_blurAmountProperty; }

    double BlurAmount()
    {
        return winrt::unbox_value<double>(GetValue(m_blurAmountProperty));
    }

    void BlurAmount(double value)
    {
        SetValue(m_blurAmountProperty, winrt::box_value(value));
    }

    void OnConnected();
    void OnDisconnected();

    static void OnBlurAmountChanged(Windows::UI::Xaml::DependencyObject const& d, Windows::UI::Xaml::DependencyPropertyChangedEventArgs const& e);

private:
    static Windows::UI::Xaml::DependencyProperty m_blurAmountProperty;
};

// WindowBlurBrush.cpp.
Windows::UI::Xaml::DependencyProperty BackdropBlurBrush::m_blurAmountProperty =
    Windows::UI::Xaml::DependencyProperty::Register(
        L"BlurAmount",
        winrt::xaml_typename<double>(),
        winrt::xaml_typename<MyApp::BackdropBlurBrush>(),
        Windows::UI::Xaml::PropertyMetadata{ winrt::box_value(0.), Windows::UI::Xaml::PropertyChangedCallback{ &BackdropBlurBrush::OnBlurAmountChanged } }
);

void BackdropBlurBrush::OnBlurAmountChanged(Windows::UI::Xaml::DependencyObject const& d, Windows::UI::Xaml::DependencyPropertyChangedEventArgs const& e)
{
    auto brush{ d.as<MyApp::BackdropBlurBrush>() };
    // Unbox and set a new blur amount if the CompositionBrush exists.
    if (brush.CompositionBrush() != nullptr)
    {
        brush.CompositionBrush().Properties().InsertScalar(L"Blur.BlurAmount", (float)winrt::unbox_value<double>(e.NewValue()));
    }
}

void BackdropBlurBrush::OnConnected()
{
    // Delay creating composition resources until they're required.
    if (!CompositionBrush())
    {
        auto backdrop{ Windows::UI::Xaml::Window::Current().Compositor().CreateBackdropBrush() };

        // Use a Win2D blur affect applied to a CompositionBackdropBrush.
        Microsoft::Graphics::Canvas::Effects::GaussianBlurEffect graphicsEffect{};
        graphicsEffect.Name(L"Blur");
        graphicsEffect.BlurAmount(this->BlurAmount());
        graphicsEffect.Source(Windows::UI::Composition::CompositionEffectSourceParameter(L"backdrop"));

        auto effectFactory{ Windows::UI::Xaml::Window::Current().Compositor().CreateEffectFactory(graphicsEffect, { L"Blur.BlurAmount" }) };
        auto effectBrush{ effectFactory.CreateBrush() };

        effectBrush.SetSourceParameter(L"backdrop", backdrop);

        CompositionBrush(effectBrush);
    }
}

void BackdropBlurBrush::OnDisconnected()
{
    // Dispose of composition resources when no longer in use.
    if (CompositionBrush())
    {
        CompositionBrush(nullptr);
    }
}
// WindowBlurBrush.h:
public ref class BackdropBlurBrush sealed :
    public Windows::UI::Xaml::Media::XamlCompositionBrushBase
{
public:
    BackdropBlurBrush();

    static property Windows::UI::Xaml::DependencyProperty^ BlurAmountProperty
    {
        Windows::UI::Xaml::DependencyProperty^ get() { return m_blurAmountProperty; }
    };

    property double BlurAmount
    {
        double get() 
        {
            return static_cast<double>(GetValue(BlurAmountProperty));
        }
        void set(double value) 
        {
            SetValue(BlurAmountProperty, value);
        }
    };

protected:
    virtual void OnConnected() override;
    virtual void OnDisconnected() override;	
    private:
    static Windows::UI::Xaml::DependencyProperty^ m_blurAmountProperty;
    static void OnBlurAmountChanged(Windows::UI::Xaml::DependencyObject^ d, Windows::UI::Xaml::DependencyPropertyChangedEventArgs^ e);
};

// WindowBlurBrush.cpp:
DependencyProperty^ BackdropBlurBrush::m_blurAmountProperty = DependencyProperty::Register(
    "BlurAmount",
    Platform::String::typeid,
    BackdropBlurBrush::typeid,
    ref new PropertyMetadata(0.0, ref new PropertyChangedCallback(OnBlurAmountChanged))
);

BackdropBlurBrush::BackdropBlurBrush()
{
}

void BackdropBlurBrush::OnBlurAmountChanged(DependencyObject^ d, DependencyPropertyChangedEventArgs^ e)
{
    auto brush = static_cast<BackdropBlurBrush^>(d);
    // Unbox and set a new blur amount if the CompositionBrush exists
    if (brush->CompositionBrush != nullptr)
    {
        brush->CompositionBrush->Properties->InsertScalar("Blur.BlurAmount", (float)static_cast<double>(e->NewValue));
    }
}

void BackdropBlurBrush::OnConnected()
{
    // Delay creating composition resources until they're required
    if (CompositionBrush == nullptr)
    {
        auto backdrop = Window::Current->Compositor->CreateBackdropBrush();

        // Use a Win2D blur affect applied to a CompositionBackdropBrush
        auto graphicsEffect = ref new GaussianBlurEffect();
        graphicsEffect->Name = "Blur";
        graphicsEffect->BlurAmount = static_cast<float>(this->BlurAmount);
        graphicsEffect->Source = ref new CompositionEffectSourceParameter("backdrop");

        auto animatableProperties = ref new Platform::Collections::Vector<Platform::String^>();
        animatableProperties->Append("Blur.BlurAmount");

        auto effectFactory = Window::Current->Compositor->CreateEffectFactory(graphicsEffect, animatableProperties);
        auto effectBrush = effectFactory->CreateBrush();

        effectBrush->SetSourceParameter("backdrop", backdrop);

        CompositionBrush = effectBrush;
    }
}

void BackdropBlurBrush::OnDisconnected()
{
    // Dispose of composition resources when no longer in use
    if (CompositionBrush != nullptr)
    {
        delete CompositionBrush;
        CompositionBrush = nullptr;
    }
}

然后,可以像使用任何其他 XAML 画笔类型一样使用上述画笔绘制 UIElement,例如:

对于 C++/WinRT,还应将 添加到 #include "BackdropBlurBrush.h"MainPage.h

<Ellipse Width="100" Height="100">
    <Ellipse.Fill>
        <local:BackdropBlurBrush BlurAmount="10" />
    </Ellipse.Fill>
</Ellipse>

注解

可以使用 XamlCompositionBrushBase 创建自定义画笔。

例如,它可用于创建一个画笔,该画笔使用 CompositionEffectBrush效果应用于 XAML UIElements,或者一个 SceneLightingEffect,该画笔控制由 XamlLight 点亮时元素的反射属性,或者一系列链接在一起以产生更复杂的效果。

创建画笔时,通常最好延迟创建 CompositionBrush 和任何相关资源,直到使用画笔。 当首次在屏幕上使用画笔绘制元素时,将调用 OnConnected 方法,因此可以替代 OnConnected ,以便仅在需要时才安全地创建资源。 这意味着可以在 ResourceDictionary 中创建画笔的实例,然后稍后从 UI 定义的其他部分引用该画笔资源,并且仅在实际使用画笔时支付创建合成资源的费用。

当组合资源不再使用时,处理组合资源也是一种很好的做法。 当画笔实例不再在屏幕上的任何位置使用时,将调用 OnDisconnected 方法,因此你可以替代 OnDisconnected 以安全地释放资源。 如果在断开连接后再次使用画笔,则将再次调用 OnConnected

构造函数

XamlCompositionBrushBase()

XamlCompositionBrushBase 派生类提供基类初始化行为。

属性

CompositionBrush

获取或设置此 XAML 画笔使用的 CompositionBrush

Dispatcher

获取与此 对象关联的 CoreDispatcherCoreDispatcher 表示可以访问 UI 线程上的 DependencyObject 的工具,即使代码是由非 UI 线程启动的。

(继承自 DependencyObject)
FallbackColor

无法呈现 CompositionBrush 时用于呈现的颜色。

FallbackColorProperty

标识 FallbackColor 依赖属性。

Opacity

获取或设置 Brush 的不透明度。

(继承自 Brush)
RelativeTransform

获取或设置使用相对坐标应用到画笔的转换。

(继承自 Brush)
Transform

获取或设置应用于画笔的转换。

(继承自 Brush)

方法

ClearValue(DependencyProperty)

清除依赖属性的本地值。

(继承自 DependencyObject)
GetAnimationBaseValue(DependencyProperty)

返回为依赖属性建立的任何基值,该基值适用于动画未处于活动状态的情况。

(继承自 DependencyObject)
GetValue(DependencyProperty)

DependencyObject 返回依赖属性的当前有效值。

(继承自 DependencyObject)
OnConnected()

在屏幕上首次使用画笔绘制元素时调用。

在派生类中实现时,可以创建 CompositionBrush 实例,并通过设置 CompositionBrush 属性将其提供给框架。

当画笔不再用于绘制任何元素时,将调用 OnDisconnected

OnDisconnected()

当画笔不再用于绘制任何元素时调用。

在派生类中实现时,可以安全地释放合成画笔和其他合成资源。

如果稍后使用画笔在断开连接后绘制任何元素,则将再次调用 OnConnected

PopulatePropertyInfo(String, AnimationPropertyInfo)

定义可进行动画处理的属性。

(继承自 Brush)
PopulatePropertyInfoOverride(String, AnimationPropertyInfo)

在派生类中重写时,定义可进行动画处理的属性。

(继承自 Brush)
ReadLocalValue(DependencyProperty)

如果设置了本地值,则返回依赖属性的本地值。

(继承自 DependencyObject)
RegisterPropertyChangedCallback(DependencyProperty, DependencyPropertyChangedCallback)

注册一个通知函数,用于侦听此 DependencyObject 实例上特定 DependencyProperty 的更改。

(继承自 DependencyObject)
SetValue(DependencyProperty, Object)

设置 DependencyObject 上依赖属性的本地值。

(继承自 DependencyObject)
UnregisterPropertyChangedCallback(DependencyProperty, Int64)

取消以前通过调用 RegisterPropertyChangedCallback 注册的更改通知。

(继承自 DependencyObject)

适用于

另请参阅