1

System.Windows.Controls.Canvas Control を .png Image に変換してディレクトリに保存するメソッドがあります。List <Canvas> に対してこの関数を呼び出すと、すべての画像がディレクトリ内に取得されます。正常に動作していますが、この関数がいくつかの画像を無作為に生成し、この関数を再度呼び出すと、すべての画像が完全に生成されることがあります。この誤動作の背後にある理由は何ですか? 以下は機能です

  public bool GenerateICards(Canvas surface)
        {
            bool retVal = false;
            try
            {
                // Save current canvas transform
                Transform transform = surface.LayoutTransform;
                // reset current transform (in case it is scaled or rotated)
                surface.LayoutTransform = null;

                // Get the size of canvas
                Size size = new Size(surface.Width, surface.Height);

                // Measure and arrange the surface
                // VERY IMPORTANT
                surface.Measure(size);
                surface.Arrange(new Rect(size));

                // Create a render bitmap and push the surface to it
                RenderTargetBitmap renderBitmap =
                  new RenderTargetBitmap(
                    (int)size.Width,
                    (int)size.Height,
                    96d,
                    96d,
                    PixelFormats.Pbgra32);
                renderBitmap.Render(surface);

                // Create a file stream for saving image
                using (FileStream outStream = new FileStream(SessionHelper.Path.PrintImage, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    // Use png encoder for our data
                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    // push the rendered bitmap to it
                    encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
                    // save the data to the stream
                    encoder.Save(outStream);
                }
                // Restore previously saved layout
                surface.LayoutTransform = transform;
                // i++;
                retVal = true;
            }
            //}
            catch (Exception)
            {
                ErrorLbl = "Error occured while generating temporary images.";
            }
            return retVal;
        }
4

1 に答える 1

1

交換したばかり

renderBitmap.Render(surface);

関数(上記の質問の関数)の行

 Rect bounds = VisualTreeHelper.GetDescendantBounds(surface);
                DrawingVisual dv = new DrawingVisual();
                using (DrawingContext ctx = dv.RenderOpen())
                {
                    VisualBrush vb = new VisualBrush(surface);
                    ctx.DrawRectangle(vb, null, new Rect(new Point(), bounds.Size));
                }

                renderBitmap.Render(dv);

これで私の問題は解決しました。詳細については、http://blogs.msdn.com/b/jaimer/archive/2009/07/03/rendertargetbitmap-tips.aspxをご覧ください。

このリンクは colinsmithによって提供されています(質問のコメント部分)。

于 2012-10-29T11:51:56.627 に答える