Green screen in WPF
We have a video that we need to show in a button, but we want the background of the button to show, and we can't put the background in the video because the button can change the size, and the background needs to stretch to the size of the button, but not the video. The video has to keep its size ratio, so I'm wondering if there is a way to do something like a green screen in WPF, so we can put a green background on the video, and have the butt开发者_高级运维on ignore it to show its own background.
I know this is a long shot but any suggestion is very welcome.
Thanks!
Ok, I found the solution. 4 easy steps.
1) Download and install Shader Effects BuildTask and Templates
2) Download WPF Pixel Shader library. Open the solution in the MainSolution folder, and right click on the WPFShaderEffectLibrary to compile it, then add a reference to the compiled DLL to your project. NOTE: Only compile WPFShaderEffectLibrary, if you try to compile the whole solution it probably won't work.
3) Use the pixel shader as follows (I used it in the MainWindow constructor but that doesn't really matter):
public MainWindow()
{
InitializeComponent();
ColorKeyAlphaEffect effect = new ColorKeyAlphaEffect();
Brush brush = Effect.ImplicitInput;
effect.Input = brush;
// This is the Image control in your xaml. It should contain
// the image in which you want the green screen effect
imageControl.Effect = effect;
}
You'll need this libraries:
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Effects;
using ShaderEffectLibrary;
4) The shader only works with black, so there is something you need to change to make it work with green (or any other color you like), in my case, I was looking to make it work with green (like a greenscreen), so I changed the value of the effect. In the solution you downloaded from Codeplex, you have to go to the WPFShaderEffectLibrary project -> ShaderSource folder ColorKeyAlpha.fx file. In there, you have to change the following code:
float4 main(float2 uv : TEXCOORD) : COLOR
{
float4 color = tex2D( implicitInputSampler, uv );
// FROM THIS
if( color.r + color.g + color.b < 0.3 ) {
color.rgba = 0;
}
return color;
}
To this
float4 main(float2 uv : TEXCOORD) : COLOR
{
float4 color = tex2D( implicitInputSampler, uv );
// TO THIS
if( color.r == 0 && color.g == 1.0 && color.b == 0 ) {
color.rgba = 0;
}
return color;
}
Once that is done, recompile the WPFShaderEffectLibrary project, and update the reference in your project (the one in step #2). Once the reference is updated, the PixelShader will start making the green value (R = 0, G = 255, B = 0) completely transparent. And it'll work with both images and videos.
I really had a hard time achieving this, I hope it useful to anyone who reads this :).
Thanks!
Do a search for "chromakey wpf effect" for a variety of examples
精彩评论