创建 VisualBrush 而不显示它所代表的 Visual
使用下面的代码,我尝试用 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();
}
Using the code below, I am attempting to fill a Canvas
with UIElements and save it as a tif Image
. However, my Image
is always blank. It is because the Canvas
is never displayed on the screen and some sort of initialization and drawing never took place? How can I make this work?
The Canvas
creation would go something like this:
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);
To create the Image
and save it:
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();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这种情况下,控件永远不会呈现在屏幕上。我刚刚将画布添加到网格中,然后单击按钮,调用了保存命令。它奏效了。
}
In this case control is never rendered on the screen. I just added the canvas to a grid and on a button click I called the save command. And it worked.
}
请参阅我的原始帖子的第一条评论。
See first comment on my original post.