重新定位画布控件 [英] Re positioning canvas control

查看:35
本文介绍了重新定位画布控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三列网格,布局就像

I have Grid with three columns and layout is like

单选按钮 |画布控制 |单选按钮

radio button | Canvas Control | radio button

对于我的应用程序的某些功能,我需要截取画布功能当前视图的屏幕截图并保存到文件中.

For some feature of my application I need to take a screenshot of current view of canvas feature and save into a file.

我正在使用以下方法将画布保存到 bmp,在那里我测量和排列画布.我的问题是图像保存后,原始网格中的画布位置向左移动,如何将我的画布重新定位回网格中更早了.

I am using following method to save canvas to bmp,where I measure and arrange canvas.My problem is after image is saved ,canvas position in original grid is shifted to left,how can I re position my canvas back in grid as it was earlier.

 private void SaveCanvasContentToImage(string path, Canvas canvasControl)
    {
        if (path == null && canvasControl != null) return;

        // Save current canvas transform
        Transform transform = canvasControl.LayoutTransform;
        // reset current transform (in case it is scaled or rotated)
        canvasControl.LayoutTransform = null;

        // Get the size of canvas
        Size size = new Size(canvasControl.Width, canvasControl.Height);
        // Measure and arrange the canvas

        canvasControl.Measure(size);
        canvasControl.Arrange(new Rect(size));

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


        renderBitmap.Render(canvasControl);


        // Create a file stream for saving image
        using (FileStream outStream = new FileStream(path, FileMode.CreateNew,FileAccess.ReadWrite))
        {
            // Use bitmap encoder for our data
            BitmapEncoder encoder = new BmpBitmapEncoder();

            // push the rendered bitmap to it
            encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
            // save the data to the stream
            encoder.Save(outStream);

            outStream.Close();
            outStream.Dispose();

        }

        // Restore previously saved layout
        canvasControl.LayoutTransform = transform;
    }

推荐答案

您可以通过使用中间DrawingVisual 来避免布局问题:

You may avoid the layout problem by using an intermediate DrawingVisual:

var renderTargetBitmap = new RenderTargetBitmap(
    (int)canvasControl.ActualWidth, (int)canvasControl.ActualHeight,
    96, 96, PixelFormats.Default);

var visual = new DrawingVisual();

using (var dc = visual.RenderOpen())
{
    dc.DrawRectangle(
        new VisualBrush(canvasControl),
        null,
        new Rect(0, 0, canvasControl.ActualWidth, canvasControl.ActualHeight));
}

renderTargetBitmap.Render(visual);

这篇关于重新定位画布控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆