1

使用下面的代码,我试图Canvas用 UIElements 填充 a 并将其保存为 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();
}
4

2 回答 2

0

在这种情况下,控件永远不会呈现在屏幕上。我刚刚将画布添加到网格中,然后单击按钮调用了保存命令。它奏效了。

    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();
        }
    }
}

}

于 2010-02-05T05:36:03.563 回答
0

请参阅我原始帖子的第一条评论。

于 2010-03-22T21:10:10.760 回答