我有一个自定义的wpf控件来执行任意反向图像扭曲,使用Viewport3D和自定义矩阵,以及带有ImageBrush的网格...
我正试图将这个位图完全渲染到屏幕上。我能够渲染一个位图很好(我发现在渲染之前调用了.Measure()。Array(new Rectangle(...))和.UpdateLayout()),但绑定还没有完成,所以网格是不可见的(图像画笔源尚未加载)...
我错过了什么?是否存在等待绑定完成的阻止方式?
[我尝试处理“已加载”事件但未成功...]
示例代码如下。预期的输出是一个300x300的蓝色矩形,堆叠溢出徽标在钻石中压扁/旋转。 (尝试打开DiamondControl.xaml设计器,并更改代码以使图像URL硬编码...有趣的是,这种变化仍然不在渲染位图中,表明我的问题与图像网址绑定无关,但是图像尚未加载)
Program.cs(添加了对System.Windows.Presentation的引用的控制台应用程序)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace ConsoleApplication3 {
class Program {
[STAThread]
static void Main(string[] args) {
// try exporting a bitmap...
var content = new DiamondControl();
content.DataContext = new Uri("http://sstatic.net/so/img/logo.png");
//content.ApplyTemplate(); // this doesn't seem to work
int width = 300, height = 300;
var rect = new Rect(0, 0, width, height);
content.Measure(new Size(width, height));
content.Arrange(rect);
//content.UpdateLayout(); // not required in this case, seems to be required if I render the control more than once
PngBitmapEncoder encoder = new PngBitmapEncoder();
RenderTargetBitmap render = new RenderTargetBitmap(
width,
height,
96,
96,
PixelFormats.Pbgra32);
render.Render(content);
encoder.Frames.Add(BitmapFrame.Create(render));
using (Stream s = File.Open("outputfile.png", FileMode.Create)) {
encoder.Save(s);
}
}
}
}
DiamondControl.xaml:
<UserControl x:Class="ConsoleApplication3.DiamondControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<Grid>
<Rectangle Fill="CornflowerBlue" />
<Viewport3D>
<ModelVisual3D>
<ModelVisual3D.Content>
<Model3DGroup>
<GeometryModel3D>
<GeometryModel3D.Geometry>
<!-- simple diamond -->
<MeshGeometry3D x:Name="mesh"
Positions="-.5 0 0, 0 .5 0, 0 -.5 0, .5 0 0"
TextureCoordinates="0 1, 0 0, 1 1, 1 0"
TriangleIndices="0 2 1, 2 3 1" />
</GeometryModel3D.Geometry>
<GeometryModel3D.Material>
<DiffuseMaterial>
<DiffuseMaterial.Brush>
<!--<SolidColorBrush Color="Red" />-->
<ImageBrush ImageSource="{Binding}" />
<!--<ImageBrush ImageSource="http://sstatic.net/so/img/logo.png" />-->
</DiffuseMaterial.Brush>
</DiffuseMaterial>
</GeometryModel3D.Material>
</GeometryModel3D>
<!-- Light source. -->
<AmbientLight Color="White" />
</Model3DGroup>
</ModelVisual3D.Content>
</ModelVisual3D>
<!-- Camera. -->
<Viewport3D.Camera>
<OrthographicCamera Position="0 0 1"
LookDirection="0 0 -1"
UpDirection="0 1 0"
Width="1" />
</Viewport3D.Camera>
</Viewport3D>
</Grid>
</UserControl>
答案 0 :(得分:0)
如果您的位图对应于网址,则使用How to render an <image> in a background WPF process?
中的解决方案此外,还包括&lt; image&gt;控件中的元素(即使大小为0x0)。我不确定为什么会这样,而且看起来像是一个完全无用的东西。