Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > .NET для новичков > Сохранение схемы графа в формат PNG (JPG)


Автор: Karta 3.4.2014, 21:04
Добрый день, у меня такая проблема.
У меня есть программа, которая рисует граф из xml документа. Для рисования я использую GraphSharp.
И мне нужно добавить кнопку на главное окно MainWindow, которая будет сохранять эту схему(которая получилась в результате)в один из форматов JPG/PNG. 
Нашла простой примерhttp://graphsharp.codeplex.com/discussions/63915
решила воспользоваться... Но, что то видимо не правильно пишу в представлении. Создаю клас, как описанно в примере:
Код

class Model
    {
        //Set resolution of image.
        const double dpi = 96d;

        //Set pixelformat of image.
        PixelFormat pixelFormat = PixelFormats.Pbgra32;

        /// <summary>
        /// Method exports the graphlayout to an png image.
        /// </summary>
        /// <param name="path">destination of image</param>
        /// <param name="surface">graphlayout you want to print</param>
        public void ExportToPng(GraphSharp.Controls.GraphLayout surface, Uri path)
        {
            //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.ActualWidth, surface.ActualHeight);
            
            //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,
                dpi,
                dpi,
                pixelFormat);

            //Render the graphlayout onto the bitmap.
            renderBitmap.Render(surface);

            //Create a file stream for saving image
            using (FileStream outStream = new FileStream(path.LocalPath, FileMode.Create))
            {
                //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;
        }
    }


Далее прописываю в представлении обработчик кнопки:
Код

 Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
           dlg.Title = "Export";
           dlg.DefaultExt = ".png"; 
           dlg.Filter = "Image (.png)|*.png"; 

           // Show save file dialog box
           Nullable<bool> result = dlg.ShowDialog();

         Model graphToImage = new Model();
         graphToImage.ExportToPng(surface, new Uri(((SaveFileDialog)sender).FileName));



Но что то неправильно, выдает ошибку в строке
Код

 graphToImage.ExportToPng(surface, new Uri(((SaveFileDialog)sender).FileName));


Помогите довести до ума работу, я уже второй день мучаюсь..

Спасибо

Автор: jonie 4.4.2014, 20:04
Цитата

Но что то неправильно, выдает ошибку в строке
а какую ошибку мы сейчас все дружно будем угадыаать?

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)