Для начала полезные ссылки:
Создаёшь библиотеку типа WPF User Control Library
, называешь её Controls
. Удаляешь из вновь созданного проекта UserControl
.
Создаёшь папку Shaders
. Добавляешь класс:
TintShaderEffect.cs
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
namespace Controls.Shaders
{
public class TintShaderEffect : ShaderEffect
{
public static readonly DependencyProperty InputProperty = ShaderEffect.RegisterPixelShaderSamplerProperty(
"Input", typeof(TintShaderEffect), 0);
public static readonly DependencyProperty TintColorProperty =
DependencyProperty.Register(
"TintColor",
typeof(Color),
typeof(TintShaderEffect),
new PropertyMetadata(Color.FromArgb(255, 230, 179, 77), PixelShaderConstantCallback(0)));
public Brush Input
{
get { return ((Brush)(GetValue(InputProperty))); }
set { SetValue(InputProperty, value); }
}
/// <summary>The tint color.</summary>
public Color TintColor
{
get { return ((Color)(this.GetValue(TintColorProperty))); }
set { SetValue(TintColorProperty, value); }
}
public TintShaderEffect()
{
string name = AssemblyHelper.GetExecutingAssemblyName();
Uri uri = new Uri("pack://application:,,,/" + name + ";component/Shaders/TintShaderEffect.ps", UriKind.RelativeOrAbsolute);
PixelShader pixelShader = new PixelShader();
pixelShader.UriSource = uri;
PixelShader = pixelShader;
UpdateShaderValue(InputProperty);
UpdateShaderValue(TintColorProperty);
}
}
}
Добавляешь в проект в папку Shaders
файл TintShader.fx
, который содержит:
TintShader.fx
/// <summary>The tint color.</summary>
/// <type>Color</type>
/// <minValue>0,0,0,0,</minValue>
/// <maxValue>1,1,1,1</maxValue>
/// <defaultValue>0.9,0.7,0.3,1</defaultValue>
float4 TintColor : register(C0);
// Sampler
sampler2D TextureSampler : register(S0);
// Shader
float4 main(float2 uv : TEXCOORD) : COLOR
{
// Sample the original color at the coordinate
float4 color = tex2D(TextureSampler, uv);
// Convert the color to gray
float gray = dot(color, float4(0.3, 0.59, 0.11, 0));
// Create the gray color with the original alpha value
float4 grayColor = float4(gray, gray, gray, color.a);
// Return the tinted pixel
return grayColor * TintColor;
}
Устанавливаешь Shazzam Shader Editor. Выбираешь в программе File -> New_Shader File
. Выбираешь место сохранения и называешь файл TintShader.fx
. Далее вставляешь в редакторе код шейдера, который показан выше. Выбираешь в меню Tools -> Compile Shader
. Далее выбираешь Tools -> Explore Compiled Shaders
. Ищешь и открываешь папку TintShaderEffect
(название зависит от того, как ты назвал файл шейдера). Копируешь в проект в папку Shaders
файл TintShaderEffect.ps
, у файла выставляешь Действие при построении
(Build Action)
в Resource
.
Добавляешь класс в корень проекта Controls
AssemblyHelper.cs
using System.Reflection;
namespace Controls
{
public static class AssemblyHelper
{
public static string GetExecutingAssemblyName()
{
return Assembly.GetExecutingAssembly().GetName().Name;
}
}
}
Далее добавляешь в проект Controls
класс
CustomWindow.cs
using Controls.Shaders;
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
namespace Controls
{
public class CustomWindow : Window
{
public CustomWindow()
{
Loaded += CustomWindow_Loaded;
}
private void CustomWindow_Loaded(object sender, RoutedEventArgs e)
{
ActivateDisabledEffect();
}
private void CustomWindow_Closed(object sender, EventArgs e)
{
DeactivateDisabledEffect();
}
public static readonly DependencyProperty IsAutoShadingEnabledProperty = DependencyProperty.Register(
"IsAutoShadingEnabled", typeof(bool), typeof(CustomWindow), new PropertyMetadata(true,
new PropertyChangedCallback(IsAutoShadingEnabledPropertyChanged)));
public static readonly DependencyProperty DisabledEffectProperty = DependencyProperty.Register(
"DisabledEffect", typeof(Effect), typeof(CustomWindow), new PropertyMetadata(
new TintShaderEffect() { TintColor = Colors.LightGray },
new PropertyChangedCallback(EffectPropertiesChanged)));
public static readonly DependencyProperty UseDisabledEffectProperty = DependencyProperty.Register(
"UseDisabledEffect", typeof(bool), typeof(CustomWindow), new PropertyMetadata(false,
new PropertyChangedCallback(EffectPropertiesChanged)));
public static readonly DependencyProperty UseDisabledEffectInternalProperty = DependencyProperty.Register(
"UseDisabledEffectInternal", typeof(bool), typeof(CustomWindow), new PropertyMetadata(false,
new PropertyChangedCallback(EffectPropertiesChanged)));
private bool UseDisabledEffectInternal
{
get { return (bool)GetValue(UseDisabledEffectInternalProperty); }
set { SetValue(UseDisabledEffectInternalProperty, value); }
}
public bool IsAutoShadingEnabled
{
get { return (bool)GetValue(IsAutoShadingEnabledProperty); }
set { SetValue(IsAutoShadingEnabledProperty, value); }
}
public bool UseDisabledEffect
{
get { return (bool)GetValue(UseDisabledEffectProperty); }
set { SetValue(UseDisabledEffectProperty, value); }
}
public Effect DisabledEffect
{
get { return (Effect)GetValue(DisabledEffectProperty); }
set { SetValue(DisabledEffectProperty, value); }
}
private static void IsAutoShadingEnabledPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = (CustomWindow)d;
if (control.UseDisabledEffectInternal)
{
control.UseDisabledEffectInternal = false;
}
}
private static void EffectPropertiesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = (CustomWindow)d;
SetEffect(control);
}
private static void SetEffect(CustomWindow control)
{
if (!control.UseDisabledEffectInternal && !control.UseDisabledEffect)
{
control.Effect = null;
}
else if (control.UseDisabledEffect)
{
control.Effect = control.DisabledEffect;
}
else if (control.UseDisabledEffectInternal)
{
control.Effect = control.DisabledEffect;
}
}
private void ActivateDisabledEffect()
{
if (Owner != null)
{
var window = Owner as CustomWindow;
if (window != null)
{
Closed -= CustomWindow_Closed;
Closed += CustomWindow_Closed;
if (window.IsAutoShadingEnabled)
{
window.UseDisabledEffectInternal = true;
}
}
}
}
private void DeactivateDisabledEffect()
{
var window = Owner as CustomWindow;
if (window != null)
{
if (window.IsAutoShadingEnabled)
{
window.UseDisabledEffectInternal = false;
}
}
}
}
}
Создаёшь основной проект, например, назвав его Wpf_Shaders.
Проект содержит в себе следующий код:
MainWindow.xaml
<controls:CustomWindow
x:Class="Wpf_Shaders.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:Controls;assembly=Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="525"
Height="350"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d">
<Grid>
<Ellipse
Width="100"
Height="100"
Margin="60,150,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Fill="#FFBD4566"
Stroke="Black" />
<Ellipse
Width="100"
Height="100"
Margin="353,150,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Fill="#FFA5E282"
Stroke="Black" />
<Ellipse
Width="70"
Height="70"
Margin="0,38,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Top"
Fill="#FF289ACF"
Stroke="Black" />
<Button
Padding="6,2,6,2"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Click="Button_Click"
Content="Новое окно" />
<StackPanel
Margin="24,10,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top">
<Button
Margin="0,0,0,0"
Padding="6,2,6,2"
HorizontalAlignment="Stretch"
VerticalAlignment="Top"
Click="OnEffectButton_Click"
Content="Включить эффект" />
<Button
Margin="0,3,0,0"
Padding="6,2,6,2"
HorizontalAlignment="Stretch"
VerticalAlignment="Top"
Click="OffEffectButton_Click"
Content="Выключить эффект" />
<ToggleButton
Margin="0,3,0,0"
Padding="6,2,6,2"
HorizontalAlignment="Stretch"
VerticalAlignment="Top"
Content="Автозатенение"
IsChecked="{Binding IsAutoShadingEnabled,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type controls:CustomWindow}}}" />
</StackPanel>
</Grid>
</controls:CustomWindow>
MainWindow.xaml.cs
using Controls;
using System.Windows;
namespace Wpf_Shaders
{
public partial class MainWindow : CustomWindow
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var window = new SomeWindow();
window.Owner = this;
window.ShowDialog();
}
private void OnEffectButton_Click(object sender, RoutedEventArgs e)
{
UseDisabledEffect = true;
}
private void OffEffectButton_Click(object sender, RoutedEventArgs e)
{
UseDisabledEffect = false;
}
}
}
SomeWindow.xaml
<controls:CustomWindow
x:Class="Wpf_Shaders.SomeWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:Controls;assembly=Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Wpf_Shaders"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="SomeWindow"
Width="300"
Height="300"
mc:Ignorable="d">
<Grid>
</Grid>
</controls:CustomWindow>
SomeWindow.xaml.cs
using Controls;
namespace Wpf_Shaders
{
public partial class SomeWindow : CustomWindow
{
public SomeWindow()
{
InitializeComponent();
}
}
}
Не забудь добавить ссылку на проект Controls
для проекта Wpf_Shaders
. Всё, запускаешь программу, открываешь окно нажав на кнопку "Новое окно". Появившееся окно автоматом затеняет родительское окно. Закрываешь, с родительского окна снимается шейдерный эффект. Этот эффект можно применять к любому наследнику от UIElement
.
Следует помнить, что это пример того, как не писать много кода для применения эффекта. Можно прописать всё намного гибче в CustomWindow и, к примеру, если какое-то свойство выставлено в True, то не применять эффект и т.д. Так же не забываем, что цвет можно прописать любой. Всё это дело работает очень быстро, так как это шейдеры.
