internal byte[] SaveChartAsBytes(UserControl barchart) { double width = barchart.Width; double height = barchart.Height; byte[] rval = null; Viewbox viewbox = new Viewbox(); viewbox.Child = barchart; viewbox.Measure(Size.Empty); viewbox.Measure(new System.Windows.Size(width, height)); viewbox.Arrange(new Rect(0, 0, width, height)); viewbox.UpdateLayout(); using (MemoryStream ms = new MemoryStream()) { RenderTargetBitmap render = new RenderTargetBitmap((int)width, (int)height, 1 / 300, 1 / 300, PixelFormats.Pbgra32); render.Render(viewbox); PngBitmapEncoder png = new PngBitmapEncoder(); png.Frames.Add(BitmapFrame.Create(render)); png.Save(ms); ms.Seek(0, SeekOrigin.Begin); rval = ms.ToArray(); ms.Close(); viewbox.Child = null; } return(rval); }
private void BuildPngOnClick(object sender, RoutedEventArgs e) { var myChart = new LiveCharts.Uwp.CartesianChart { DisableAnimations = true, Width = 600, Height = 200, Series = new SeriesCollection { new LineSeries { Values = new ChartValues <double> { 1, 6, 7, 2, 9, 3, 6, 5 } } } }; var viewbox = new Viewbox(); viewbox.Child = myChart; viewbox.Measure(myChart.RenderSize); viewbox.Arrange(new Rect(new Point(0, 0), myChart.RenderSize)); myChart.Update(true, true); //force chart redraw viewbox.UpdateLayout(); //SaveToPng(myChart, "chart.png"); //png file was created at the root directory. }
/// <summary> /// 基本的な設定を利用して <see cref="FrameworkElement"/> の <see cref="FixedDocument"/> を作成します。 /// </summary> /// <param name="v">ドキュメントに変換する要素のコレクション。</param> /// <param name="stretch">ドキュメントの伸縮。</param> public void UpdateTemplateDocuments(IEnumerable <FrameworkElement> v, Stretch stretch) { var fixedDocument = new FixedDocument(); foreach (var sv in v) { var page = CreatePage(); var size = page.PrintableSize; // 印刷データ var viewbox = new Viewbox { Width = size.Width, Height = size.Height, Stretch = stretch, }; viewbox.Child = sv; viewbox.Arrange(new Rect(new Point(0, 0), size)); viewbox.Measure(size); viewbox.UpdateLayout(); page.FinalizePage(viewbox); fixedDocument.Pages.Add(page.PageContent); } Document = fixedDocument; }
private static void RenderAppIconBitmap() { var grid = (Grid)Application.Current.FindResource("PhxLogoGrid"); if (grid == null) { throw new ArgumentException("Failed to find logo Grid", "PhxLogoGrid"); } var viewbox = new Viewbox(); viewbox.Child = grid; viewbox.Measure(new Size(512, 512)); viewbox.Arrange(new Rect(0, 0, 512, 512)); viewbox.UpdateLayout(); var viewbox_ps = PresentationSource.FromVisual(viewbox); double dpiX = 96.0, dpiY = 96.0; if (viewbox_ps != null) { dpiX *= viewbox_ps.CompositionTarget.TransformToDevice.M11; dpiY *= viewbox_ps.CompositionTarget.TransformToDevice.M22; } gAppIconBitmap = new RenderTargetBitmap((int)viewbox.ActualWidth, (int)viewbox.ActualHeight, dpiX, dpiY, PixelFormats.Pbgra32); gAppIconBitmap.Render(viewbox); }
public void SelfUpdateDocument(SampleOption option) { var page = CreatePage(); var size = page.PrintableSize; var viewbox = new Viewbox { Width = size.Width, Height = size.Height, Stretch = System.Windows.Media.Stretch.Uniform, // 縦横比を維持してサイズの最終調整 }; var v = new SamplePage(); var vm = option; viewbox.Child = v; v.DataContext = vm; viewbox.Arrange(new Rect(new Point(0, 0), size)); viewbox.Measure(size); viewbox.UpdateLayout(); page.FinalizePage(viewbox); // ドキュメントの作成 var fixedDocument = new FixedDocument(); fixedDocument.Pages.Add(page.PageContent); Document = fixedDocument; }
public static Viewbox makeImgFromControl(UIElement control, string count, int typ) { Viewbox viewbox; int xAxis = 0; Ellipse e = new Ellipse(); if (count.Length == 1) { xAxis = 147; } else if (count.Length == 2) { xAxis = 143; } else if (count.Length == 3) { xAxis = 141; } else if (count.Length == 4) { xAxis = 138; } viewbox = new Viewbox(); Grid grd = new Grid(); var parent = VisualTreeHelper.GetParent(control) as StackPanel; if (parent != null) { parent.Children.Remove(control); } grd.Children.Add(control); grd.Children.Add(CreateAnEllipse()); TextBlock txt = new TextBlock { Margin = new Thickness(xAxis, 168, 0, 0) }; // if(typ==0) // { // App.RunsetBFTextbox = txt; // } //else if(typ==1) // { // App.RunsetActivityTextbox = txt; // } // else // { // App.RunsetActionTextbox = txt; // } txt.Text = count.ToString(); grd.Children.Add(txt); viewbox.Child = grd; viewbox.Measure(new System.Windows.Size(400, 200)); viewbox.Arrange(new Rect(0, 0, 400, 200)); viewbox.UpdateLayout(); return(viewbox); }
public static void UpdateSize(FrameworkElement element, double availableWidth) { var vbox = new Viewbox { Child = element }; vbox.Measure(new Size(availableWidth, 2000)); vbox.Arrange(new Rect(0, 0, availableWidth, 2000)); vbox.UpdateLayout(); }
public void TakeTheChart() { var viewbox = new Viewbox(); viewbox.Child = chart; viewbox.Measure(chart.RenderSize); viewbox.Arrange(new Rect(new Point(0, 0), chart.RenderSize)); chart.Update(true, true); viewbox.UpdateLayout(); SaveToPng(chart, chart.Tag.ToString()); }
/// <summary> /// Loads the xaml into a Viewbox so that we can parse it and verify its working. /// </summary> /// <param name="xamlFilePath">The xaml file path.</param> public static void LoadXaml(string xamlFilePath) { String xamlFileStream = File.ReadAllText(xamlFilePath); if (xamlFileStream.IndexOf("x:Class=") != -1) { xamlFileStream = Regex.Replace(xamlFileStream, "x:Class=\\\".+([^\\\"])\\\"", ""); } object obj = XamlReader.Load(new MemoryStream(new System.Text.ASCIIEncoding().GetBytes(xamlFileStream)), XamlContext); _Viewbox = new Viewbox { Child = ((UIElement)obj) }; _Viewbox.UpdateLayout(); FlushDispatcher(); }
private static void RenderToLMap(Image li, string file) { Viewbox viewbox = new Viewbox { Child = li }; viewbox.Measure(new Size(li.Width, li.Height)); viewbox.Arrange(new Rect(0, 0, li.Width, li.Height)); viewbox.UpdateLayout(); RenderTargetBitmap rtb = new RenderTargetBitmap((int)li.Width, (int)li.Height, 96, 96, PixelFormats.Pbgra32); rtb.Render(viewbox); PngBitmapEncoder enc = new PngBitmapEncoder(); enc.Frames.Add(BitmapFrame.Create(rtb)); using (FileStream stm = File.Create(file)) { enc.Save(stm); } }
public System.Drawing.Bitmap ApplyShader(System.Drawing.Bitmap Source) { System.Drawing.Bitmap returnBitmap = null; try { returnBitmap = Source; img.BeginInit(); img.Width = Source.Width; img.Height = Source.Height; img.Source = BitmapToBitmapSource.ToBitmapSource(Source);; img.EndInit(); viewbox.Measure(new Size(img.Width * scale, img.Height * scale)); viewbox.Arrange(new Rect(0, 0, img.Width * scale, img.Height * scale)); viewbox.UpdateLayout(); MemoryStream outStream = new MemoryStream(); RenderOptions.SetBitmapScalingMode(img, BitmapScalingMode.HighQuality); RenderTargetBitmap rtBitmap = new RenderTargetBitmap(Convert.ToInt32(img.Width * scale), Convert.ToInt32(img.Height * scale), Convert.ToInt32(WPF_DPI_X), Convert.ToInt32(WPF_DPI_Y), PixelFormats.Pbgra32); rtBitmap.Render(viewbox); BitmapFrame frame = BitmapFrame.Create(rtBitmap); encoder = new JpegBitmapEncoder(); encoder.Frames.Add(frame); encoder.Save(outStream); returnBitmap = new System.Drawing.Bitmap(outStream); encoder = null; rtBitmap = null; frame = null; } catch (Exception ex) { returnBitmap = null; } return(returnBitmap); }
/// <summary> /// Render the frameworkElement to a BitmapSource /// </summary> /// <param name="frameworkElement">FrameworkElement</param> /// <param name="size">Size, using the bound as size by default</param> /// <param name="dpiX">Horizontal DPI settings</param> /// <param name="dpiY">Vertical DPI settings</param> /// <returns>BitmapSource</returns> public static BitmapSource ToBitmapSource(this FrameworkElement frameworkElement, Size?size = null, double dpiX = 96.0, double dpiY = 96.0) { if (frameworkElement == null) { throw new ArgumentNullException(nameof(frameworkElement)); } // Make sure we have a size if (!size.HasValue) { var bounds = VisualTreeHelper.GetDescendantBounds(frameworkElement); size = bounds != Rect.Empty ? bounds.Size : new Size(16, 16); } // Create a viewbox to render the frameworkElement in the correct size var viewbox = new Viewbox { //frameworkElement to render Child = frameworkElement }; viewbox.Measure(size.Value); viewbox.Arrange(new Rect(new Point(), size.Value)); viewbox.UpdateLayout(); var renderTargetBitmap = new RenderTargetBitmap((int)(size.Value.Width * dpiX / 96.0), (int)(size.Value.Height * dpiY / 96.0), dpiX, dpiY, PixelFormats.Pbgra32); var drawingVisual = new DrawingVisual(); using (var drawingContext = drawingVisual.RenderOpen()) { var visualBrush = new VisualBrush(viewbox); drawingContext.DrawRectangle(visualBrush, null, new Rect(new Point(), size.Value)); } renderTargetBitmap.Render(drawingVisual); // Disassociate the frameworkElement from the viewbox viewbox.RemoveChild(frameworkElement); return(renderTargetBitmap); }
public static string GenerateChart(List <string> GivenAwnsers, string chartType) { var awn = GivenAwnsers.Distinct().OrderBy(a => a).ToArray(); ChartValues <int> values = new ChartValues <int>(); foreach (var l in awn) { values.Add(GivenAwnsers.Where(x => x.Equals(l)).Count()); } Chart myChart; if (chartType == "Bar") { myChart = GenerateBar(awn, values); } else if (chartType == "Row") { myChart = GenerateRow(awn, values); } else { myChart = GeneratePie(awn, values); } var viewbox = new Viewbox(); viewbox.Child = myChart; viewbox.Measure(myChart.RenderSize); viewbox.Arrange(new Rect(new Point(0, 0), myChart.RenderSize)); myChart.Update(true, true); //force chart redraw viewbox.UpdateLayout(); var name = DateTime.Now.ToString("dd-mm-yyyy-hh-mm-ss-fff") + ".png"; SaveToPng(myChart, name); return(Location + name); }
/// <summary> /// Render a Visual to a render target of a fixed size. The visual is /// scaled uniformly to fit inside the specified size. /// </summary> /// <param name="visual"></param> /// <param name="height"></param> /// <param name="width"></param> /// <returns></returns> private static RenderTargetBitmap RenderVisual(Visual visual, double height, double width) { // Default dpi settings const double dpiX = 96; const double dpiY = 96; // We can only render UIElements...ContentPrensenter to // the rescue! var presenter = new ContentPresenter { Content = visual }; // Ensure the final visual is of the known size by creating a viewbox // and adding the visual as its child. var viewbox = new Viewbox { MaxWidth = width, MaxHeight = height, Stretch = Stretch.Uniform, Child = presenter }; // Force the viewbox to re-size otherwise we wont see anything. var sFinal = new Size(viewbox.MaxWidth, viewbox.MaxHeight); viewbox.Measure(sFinal); viewbox.Arrange(new Rect(sFinal)); viewbox.UpdateLayout(); // Render the final visual to a render target var renderTarget = new RenderTargetBitmap( (int)width, (int)height, dpiX, dpiY, PixelFormats.Pbgra32); renderTarget.Render(viewbox); // Return the render taget with the visual rendered on it. return(renderTarget); }
public static Canvas ToCanvas(this BookPage bookPage, PaperSize paperSize) { double width = paperSize.GetWidthPixel(); double height = paperSize.GetHeightPiexl(); Canvas canvas = new Canvas() { Width = width, Height = height }; canvas.Background = bookPage.Background == null ? (Brush)Brushes.White : new ImageBrush((BitmapSource) new ImageSourceConverter().ConvertFrom(bookPage.Background)) { Stretch = Stretch.Fill }; foreach (UIElement element in bookPage.ToUIElementCollection()) { canvas.Children.Add(element); } // Viewbox can render controls in code behind var viewbox = new Viewbox() { Child = canvas }; viewbox.Measure(new Size(width, height)); viewbox.Arrange(new Rect(0, 0, width, height)); viewbox.UpdateLayout(); viewbox.Child = null; return(canvas); }
//сохранение графика как картинку private void SaveFile(string _fileName, string pathForSave) { var save = DataContext as MainWindiwViewModel; ChartValues <double> valueLeft = null; ChartValues <double> valueRight = null; string titleAxisY = null; //выбор данных switch (_fileName) { case "График Вертикальных силы ": valueLeft = save.selectedForce.LeftVerticalForMovingAverage; valueRight = save.selectedForce.RightVerticalForMovingAverage; titleAxisY = "Вертикальные силы, кН"; break; case "График Боковых силы ": valueLeft = save.selectedForce.LeftLateralForMovingAverage; valueRight = save.selectedForce.RightLateralForMovingAverage; titleAxisY = "Боковых силы, кН"; break; case "График Коэффициента запаса от схода ": valueLeft = save.selectedForce.LeftSafetyFactorForMovingAverage; valueRight = save.selectedForce.RightSafetyFactorForMovingAverage; titleAxisY = "Коэффициент запаса от схода"; break; } //создавание графика if (save.selectedForce != null) { var myChart = new CartesianChart { DataTooltip = null, DisableAnimations = true, Hoverable = true, LegendLocation = LegendLocation.Bottom, Width = 1920, Height = 1080, Series = new SeriesCollection { new LineSeries { StrokeThickness = 1, LineSmoothness = 1, Title = "Левое колесо", Stroke = Brushes.Blue, Fill = Brushes.Transparent, PointGeometrySize = 6, PointForeground = Brushes.White, PointGeometry = null, Values = valueLeft }, new LineSeries { StrokeThickness = 1, LineSmoothness = 1, Title = "Правое колесо", Stroke = Brushes.Red, Fill = Brushes.Transparent, PointGeometrySize = 6, PointForeground = Brushes.Gold, PointGeometry = null, Values = valueRight } } }; var _AxisAbscissa = new Axis(); _AxisAbscissa.Title = "Время,сек"; _AxisAbscissa.Labels = save.selectedForce.TimeForMovingAverage; myChart.AxisX.Add(_AxisAbscissa); var _AxisOrdinate = new Axis(); _AxisOrdinate.Title = titleAxisY; myChart.AxisY.Add(_AxisOrdinate); var viewbox = new Viewbox(); viewbox.Child = myChart; viewbox.Measure(myChart.RenderSize); viewbox.Arrange(new Rect(new Point(0, 0), myChart.RenderSize)); myChart.Update(true, true); myChart.Background = Brushes.White; viewbox.UpdateLayout(); var allName = _fileName + save.selectedForce._NameSignal + ".png"; SaveToPng(myChart, allName, pathForSave); } }
public bool ExportCore(Project Project, string FileName) { // Create a new canvas and set its background. This is what we are going to be rendering to. Canvas TempCanvas = new Canvas(); MainWindow Xwindow = (MainWindow)Application.Current.MainWindow; BitmapImage Bitmap = new BitmapImage(); Bitmap.BeginInit(); Bitmap.UriSource = new Uri(Project.SelectedBasin.ImagePath, UriKind.RelativeOrAbsolute); Bitmap.EndInit(); // dumb hack (build 558) TempCanvas.Background = new ImageBrush(Bitmap); Point CanvasSize = ScaleUtilities.ScaleToQuality(Bitmap, Quality); TempCanvas.Width = CanvasSize.X; TempCanvas.Height = CanvasSize.Y; Project CurrentProject = Xwindow.CurrentProject; // //CurrentProject.SelectedBasin.RecalculateNodePositions(Direction.Larger, new Point(Xwindow.Width, Xwindow.Height), new Point(TempCanvas.Width, TempCanvas.Height)); //New scaling for picking up dev again - 2020-05-08 23:04 //Remove storm selection functionality, replace with layer selection functionality - 2020-09-12 17:24 //v462 - 2020-09-26 00:00 Xwindow.RenderContent(TempCanvas, new Point(Utilities.RoundNearest(8 * (TempCanvas.Width / Xwindow.Width) / 1.5, 8), Utilities.RoundNearest(8 * (TempCanvas.Height / Xwindow.Height) / 1.5, 8)), Project.SelectedBasin.GetFlatListOfStorms()); // Recalculate node positions on the currentbasin so they actually show up properly. TempCanvas.UpdateLayout(); // create a new rendertargetbitmap and render to it RenderTargetBitmap RenderTarget = new RenderTargetBitmap((int)TempCanvas.Width, (int)TempCanvas.Height, 96.0, 96.0, PixelFormats.Default); // force WPF to render it because optimization is not always a good idea Viewbox ViewBox = new Viewbox(); ViewBox.Child = TempCanvas; ViewBox.Measure(new Size(TempCanvas.Width, TempCanvas.Height)); ViewBox.Arrange(new Rect(new Point(0, 0), new Point(TempCanvas.Width, TempCanvas.Height))); ViewBox.UpdateLayout(); RenderTarget.Render(TempCanvas); // create a new PNG encoder and memory stream ImageFormats ImgFormat = ImageFormatDeterminer.FromString(FileName); // REFACTOR PROBABLY BitmapEncoder PNGEncoder = ImageFormatDeterminer.GetBitmapEncoder(ImgFormat); if (PNGEncoder == null) { Error.Throw("Warning", "Error: unable to determine image format", ErrorSeverity.Error, 361); return(false); } PNGEncoder.Frames.Add(BitmapFrame.Create(RenderTarget)); MemoryStream TempCanvasms_ = new MemoryStream(); // save the thing PNGEncoder.Save(TempCanvasms_); File.WriteAllBytes(FileName, TempCanvasms_.ToArray()); // clean up by restoring the basin //CurrentProject.SelectedBasin.RecalculateNodePositions(Direction.Smaller, new Point(Xwindow.Width, Xwindow.Height), new Point(TempCanvas.Width, TempCanvas.Height)); // on success GlobalState.SetCurrentOpenFile(FileName); return(true); // success }
private void Button_Click(object sender, RoutedEventArgs e) { Chart3.Height = 500; Chart3.Width = 1000; Chart3.AxisX[0].MinValue = double.NaN; Chart3.AxisX[0].MaxValue = double.NaN; Chart3.AxisY[0].MinValue = double.NaN; Chart3.AxisY[0].MaxValue = double.NaN; var myChart = new LiveCharts.Wpf.CartesianChart { DisableAnimations = true, Width = 1200, Height = 400, Series = new SeriesCollection { new LineSeries { Title = "Neutral", Values = cv_net3 }, new LineSeries { Title = "Anger", Values = cv_ang3 }, new LineSeries { Title = "Disgust", Values = cv_dis3 }, new LineSeries { Title = "Fear", Values = cv_fea3 }, new LineSeries { Title = "Happy", Values = cv_hap3 }, new LineSeries { Title = "Saddness", Values = cv_sad3 }, new LineSeries { Title = "Surprise", Values = cv_sur3 }, } }; var viewbox = new Viewbox(); viewbox.Child = myChart; viewbox.Measure(myChart.RenderSize); viewbox.Arrange(new Rect(new System.Windows.Point(0, 0), myChart.RenderSize)); myChart.Update(true, true); //force chart redraw viewbox.UpdateLayout(); SaveToPng(myChart, "chart.png"); //png file was created at the root directory. Chart3.Height = 178; Chart3.Width = 324; }