我编写了一个非常简单的 WPF 应用程序来测试将具有关联像素着色器的控件呈现到 RenderTargetBitmap 的能力。然后我将位图写入文件(jpeg)。控件被渲染到位图上,但是像素着色器效果不应用于控件。
代码和 XAML 如下:
namespace TestPixelShader
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void OnSaveSnapshot(object sender, RoutedEventArgs e)
{
SaveFileDialog dlg = new SaveFileDialog();
dlg.DefaultExt = "jpg";
if ((bool)dlg.ShowDialog() == true)
{
String fileName = dlg.FileName;
int Height = (int)CanvasControl.ActualHeight;
int Width = (int)CanvasControl.ActualWidth;
RenderTargetBitmap bmp = new RenderTargetBitmap(
Width, Height, 96, 96, PixelFormats.Pbgra32);
bmp.Render(CanvasControl);
string Extension = System.IO.Path.GetExtension(fileName).ToLower();
BitmapEncoder encoder;
if (Extension == ".gif")
encoder = new GifBitmapEncoder();
else if (Extension == ".png")
encoder = new PngBitmapEncoder();
else if (Extension == ".jpg")
encoder = new JpegBitmapEncoder();
else
return;
encoder.Frames.Add(BitmapFrame.Create(bmp));
using (Stream stm = File.Create(fileName))
{
encoder.Save(stm);
}
}
}
}
}
XAML:
<Window x:Class="TestPixelShader.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestPixelShader"
Height="400"
Width="300"
Title="Test Pixel Shader">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Canvas Grid.Column="0" x:Name="CanvasControl" Margin="5"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" >
<Canvas.Effect>
<local:TestPixelShaderEffect />
</Canvas.Effect>
<Canvas.Background>
<ImageBrush ImageSource="/TestPixelShader;component/Images/DSCF0225.JPG" />
</Canvas.Background>
</Canvas>
<Button x:Name="SaveSnapshotButton" Grid.Row="1" Click="OnSaveSnapshot" Height="40"
Content="Take Snapshot" Margin="5"/>
</Grid>
</Window>