使用下面的代码,我尝试使用UIElements填充Canvas
并将其另存为tif Image
。但是,我的Image
始终为空。这是因为Canvas
从未在屏幕上显示,并且从未进行某种初始化和绘图?我怎样才能做到这一点?
Canvas
创建将会是这样的:
Canvas theCanvas = new Canvas();
theCanvas.Width = 2740;
theCanvas.Height = 2280;
...
Button button = new Button();
button.Content = "Push Me.";
button.Height = 50;
button.Width = 200;
Canvas.SetTop(button, 200);
Canvas.SetLeft(button, 300);
theCanvas.Children.Add(button);
创建Image
并保存:
using (System.IO.FileStream fs =
new System.IO.FileStream(path, System.IO.FileMode.Create))
{
RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
(int)inWidth,
(int)inHeight, 1 / 300, 1 / 300,
PixelFormats.Pbgra32);
DrawingVisual visual = new DrawingVisual();
using (DrawingContext context = visual.RenderOpen())
{
VisualBrush brush = new VisualBrush(inCanvas);
context.DrawRectangle(
brush,
null,
new Rect(new Point(), new Size(inWidth, inHeight)));
}
renderBitmap.Render(visual);
BitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
encoder.Save(fs);
fs.Close();
}
答案 0 :(得分:0)
在这种情况下,控件永远不会在屏幕上呈现。我刚刚将画布添加到网格中,然后在按钮上单击我调用了save命令。它起作用了。
private void Window_Loaded(object sender, RoutedEventArgs e)
{
theCanvas.Width = 2740;
theCanvas.Height = 2280;
Button button = new Button();
button.Content = "Push Me.";
button.Height = 50;
button.Width = 200;
Canvas.SetTop(button, 200);
Canvas.SetLeft(button, 300);
theCanvas.Children.Add(button);
mainGri.Children.Add(theCanvas);
}
private void mainGri_MouseDown(object sender, MouseButtonEventArgs e)
{
}
private void button1_Click(object sender, RoutedEventArgs e)
{
String path = @"c:\\a.jpg";
using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create))
{
int inWidth = 300;
int inHeight = 400;
RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)inWidth,
(int)inHeight, 1 / 300, 1 / 300, PixelFormats.Pbgra32);
DrawingVisual visual = new DrawingVisual();
using (DrawingContext context = visual.RenderOpen())
{
VisualBrush brush = new VisualBrush(theCanvas);
context.DrawRectangle(brush,
null,
new Rect(new Point(), new Size(inWidth, inHeight)));
}
renderBitmap.Render(visual);
BitmapEncoder encoder = new TiffBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
encoder.Save(fs);
fs.Close();
}
}
}
}
答案 1 :(得分:0)
请参阅我原来帖子的第一条评论。