0
我目前正试图坚持一个画布到位图,我遇到了一些非常奇怪的行为。以下三种情况的源代码出现在帖子的末尾。令人困惑的WPF绘制行为
情况1:如预期的那样,输出文件(test.png)中出现红色矩形。
情况2:输出文件中不显示红色矩形。
情况3:输出文件中不显示红色矩形。
似乎将矩形添加到画布(即使该画布从未用于将矩形渲染到磁盘)是必要的。似乎按钮点击必须启动绘图 - 它不能出现在Window构造函数中。这些都对我没有意义,我认为我误解了一些东西。
此外,我很抱歉代码格式不正确。我摔了20分钟,但现在我放弃了。
由于提前,
- 布雷克Fresen
用于所有3例XAML:
<Window x:Class="ScanOutlineCreator.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="250" Width="250">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20" />
<RowDefinition />
</Grid.RowDefinitions>
<Button x:Name="btnGo" Grid.Row="0">
<TextBlock Text="Go" />
</Button>
<Canvas Grid.Row="1" x:Name="canvas" Width="200" Height="500"></Canvas>
</Grid>
</Window>
情况1:
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Common.Drawing;
namespace ScanOutlineCreator
{
public partial class Window1
{
static Rectangle r = new Rectangle { Width = 100, Height = 100, Fill = Brushes.Red };
public Window1()
{
InitializeComponent();
btnGo.Click += new RoutedEventHandler(btnGo_Click);
canvas.Children.Add(r);
}
static void btnGo_Click(object sender, RoutedEventArgs e)
{
using (Stream stm = File.Create("test.png"))
{
RenderTargetBitmap rtb = new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Pbgra32);
rtb.Render(r);
Util.RenderTargetBitmapToStream(rtb, stm);
}
}
}
}
情况2:
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Common.Drawing;
namespace ScanOutlineCreator
{
public partial class Window1
{
static Rectangle r = new Rectangle { Width = 100, Height = 100, Fill = Brushes.Red };
public Window1()
{
InitializeComponent();
btnGo.Click += new RoutedEventHandler(btnGo_Click);
}
static void btnGo_Click(object sender, RoutedEventArgs e)
{
using (Stream stm = File.Create("test.png"))
{
RenderTargetBitmap rtb = new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Pbgra32);
rtb.Render(r);
Util.RenderTargetBitmapToStream(rtb, stm);
}
}
}
}
案例3:
using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Common.Drawing;
namespace ScanOutlineCreator
{
public partial class Window1
{
static Rectangle r = new Rectangle { Width = 100, Height = 100, Fill = Brushes.Red };
public Window1()
{
InitializeComponent();
canvas.Children.Add(r);
using (Stream stm = File.Create("test.png"))
{
RenderTargetBitmap rtb = new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Pbgra32);
rtb.Render(r);
Util.RenderTargetBitmapToStream(rtb, stm);
}
}
}
}
谢谢。 Calling Measure并没有改变任何事情,但是安排似乎是在做伎俩。 – 2010-02-05 16:10:11