/// <summary> /// Exports the specified plot model to an xps file. /// </summary> /// <param name="model">The model.</param> /// <param name="fileName">The file name.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="background">The background color.</param> public static void Export(IPlotModel model, string fileName, double width, double height, OxyColor background) { using (var xpsPackage = Package.Open(fileName, FileMode.Create, FileAccess.ReadWrite)) { using (var doc = new XpsDocument(xpsPackage)) { var canvas = new Canvas { Width = width, Height = height, Background = background.ToBrush() }; canvas.Measure(new Size(width, height)); canvas.Arrange(new Rect(0, 0, width, height)); var rc = new ShapesRenderContext(canvas); #if !NET35 rc.TextFormattingMode = TextFormattingMode.Ideal; #endif model.Update(true); model.Render(rc, width, height); canvas.UpdateLayout(); var xpsdw = XpsDocument.CreateXpsDocumentWriter(doc); xpsdw.Write(canvas); } } }
void loader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { buff.UpdateLayout(); Canvas canvas = new Canvas(); canvas.Children.Add(buff); canvas.Width = 512 * 13; canvas.Height = 512 * 7; canvas.UpdateLayout(); canvas.Measure(new Size((int)canvas.Width, (int)canvas.Height)); canvas.Arrange(new Rect(new Size((int)canvas.Width, (int)canvas.Height))); int Height = ((int)(canvas.ActualHeight)); int Width = ((int)(canvas.ActualWidth)); RenderTargetBitmap _RenderTargetBitmap = new RenderTargetBitmap(Width, Height, 96, 96, PixelFormats.Pbgra32); _RenderTargetBitmap.Render(buff); Image img = new Image(); img.Source = _RenderTargetBitmap; Viewer.PanoramaImage = _RenderTargetBitmap; Title = "Demo.StreetView, enjoy! ;}"; }
private void RenderToRaster(IViewport viewport, ILayer layer, out IFeatures features) { var canvas = new Canvas(); MapRenderer.RenderLayer(canvas, viewport, layer); canvas.UpdateLayout(); var bitmap = BitmapRendering.BitmapConverter.ToBitmapStream(canvas, viewport.Width, viewport.Height); features = new Features { new Feature { Geometry = new Raster(bitmap, viewport.Extent) } }; }
/// <summary> /// Renders a UI control into an image. /// </summary> /// <param name="control"></param> /// <param name="isWideTile"></param> /// <returns></returns> public static void CreateImage(UIElement control, string imagePath, int width, int height, SolidColorBrush tileBackgroundColor) { // 1. Setup dimensions for wide tile. var bmp = new WriteableBitmap(width, height); // 2. Get the name of the background image based on theme var canvas = new System.Windows.Controls.Canvas(); canvas.Width = width; canvas.Height = height; canvas.Background = tileBackgroundColor; canvas.Children.Add(control); canvas.Measure(new Size(width, height)); canvas.Arrange(new Rect(0, 0, width, height)); canvas.UpdateLayout(); // 4. Now output the control as text. bmp.Render(canvas, null); bmp.Invalidate(); // 8. Now save the image to local folder. using (var store = IsolatedStorageFile.GetUserStoreForApplication()) { // FileMode.Open, FileAccess.Read, FileShare.Read, using (var st = new IsolatedStorageFileStream(imagePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite, store)) { bmp.SaveJpeg(st, width, height, 0, 100); st.Close(); } } try { bmp = null; canvas.Children.Clear(); GC.Collect(); GC.WaitForPendingFinalizers(); } catch (Exception ex) { Slate.Core.Logging.Logger.Error("Create image", "Warning, attempt to clear up memory for tile image failed", ex); } }
/// <summary> /// Exports the specified plot model to a stream. /// </summary> /// <param name="model">The plot model.</param> /// <param name="stream">The stream to write to.</param> /// <param name="width">The width of the export image.</param> /// <param name="height">The height of the exported image.</param> /// <param name="background">The background.</param> public static void Export(IPlotModel model, Stream stream, double width, double height, OxyColor background) { var canvas = new Canvas { Width = width, Height = height }; if (background.IsVisible()) { canvas.Background = background.ToBrush(); } canvas.Measure(new Size(width, height)); canvas.Arrange(new Rect(0, 0, width, height)); var rc = new SilverlightRenderContext(canvas); model.Update(true); model.Render(rc, width, height); canvas.UpdateLayout(); var image = canvas.ToImage(); image.WriteToStream(stream); }
public void MergeImages(string fl) { Canvas canvas = new Canvas(); if (zoom == 3) { canvas.Width = 512 * 6.5; canvas.Height = 512 * 3.25; } else if (zoom == 2) { canvas.Width = 512 * 3.25; canvas.Height = 512 * 1.625; } canvas.Measure(new Size((int)canvas.Width, (int)canvas.Height)); canvas.Arrange(new Rect(new Size((int)canvas.Width, (int)canvas.Height))); int Height = ((int)(canvas.ActualHeight)); int Width = ((int)(canvas.ActualWidth)); StackPanel mainPanel = new StackPanel(); mainPanel.Orientation = Orientation.Vertical; for (int j = 0; j < limitY; j++) { StackPanel ph = new StackPanel(); ph.Orientation = Orientation.Horizontal; for (int k = 0; k < limitX; k++) { Image stackImg = new Image(); stackImg.Source = FromStream(previousJumpBuffStream[j][k]); ph.Children.Add(stackImg); } mainPanel.Children.Add(ph); } mainPanel.UpdateLayout(); canvas.Children.Add(mainPanel); canvas.UpdateLayout(); RenderTargetBitmap _RenderTargetBitmap = new RenderTargetBitmap((int)Width, (int)Height, 96, 96, PixelFormats.Pbgra32); _RenderTargetBitmap.Render(mainPanel); ImageSource mergedImages = _RenderTargetBitmap; SaveImg(mergedImages, fl); Stream s = File.OpenRead(fl); buffStream.Add(s); }
/// <summary> /// Exports the specified plot model to a bitmap. /// </summary> /// <param name="model">The plot model.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="background">The background.</param> /// <param name="dpi">The resolution.</param> /// <returns>A bitmap.</returns> public static BitmapSource ExportToBitmap(PlotModel model, int width, int height, OxyColor background = null, int dpi = 96) { var canvas = new Canvas { Width = width, Height = height, Background = background.ToBrush() }; canvas.Measure(new Size(width, height)); canvas.Arrange(new Rect(0, 0, width, height)); var rc = new ShapesRenderContext(canvas) { RendersToScreen = false }; model.Update(); model.Render(rc, width, height); canvas.UpdateLayout(); var bmp = new RenderTargetBitmap(width, height, dpi, dpi, PixelFormats.Pbgra32); bmp.Render(canvas); return bmp; // alternative implementation: // http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.rendertargetbitmap.aspx // var dv = new DrawingVisual(); // using (var ctx = dv.RenderOpen()) // { // var vb = new VisualBrush(canvas); // ctx.DrawRectangle(vb, null, new Rect(new Point(), new Size(width, height))); // } // bmp.Render(dv); }
// ------------------------- CreateThirdVisual ------------------------ /// <summary> /// Creates content for the third visual sample.</summary> /// <param name="shouldMeasure"> /// true to remeasure the layout.</param> /// <returns> /// The canvas containing the visual.</returns> public Canvas CreateThirdVisual(bool shouldMeasure) { Canvas canvas = new Canvas(); RadialGradientBrush brush = new RadialGradientBrush(); brush.GradientStops.Add(new GradientStop(Colors.Black, 0)); brush.GradientStops.Add(new GradientStop(Colors.Yellow, 0.5)); brush.GradientStops.Add(new GradientStop(Colors.Red, 1)); brush.SpreadMethod = GradientSpreadMethod.Repeat; brush.Center = new Point(0.5, 0.5); brush.RadiusX = 0.2; brush.RadiusY = 0.2; brush.GradientOrigin = new Point(0.5, 0.5); Rectangle r = new Rectangle(); r.Fill = brush; Thickness thick = new Thickness(); thick.Left = 100; thick.Top = 100; r.Margin = thick; r.Width = 400; r.Height = 400; canvas.Children.Add(r); LinearGradientBrush linear = new LinearGradientBrush(); linear.GradientStops.Add(new GradientStop(Colors.Blue, 0)); linear.GradientStops.Add(new GradientStop(Colors.Yellow, 1)); linear.SpreadMethod = GradientSpreadMethod.Reflect; linear.StartPoint = new Point(0, 0); linear.EndPoint = new Point(0.06125, 0); linear.Opacity = 0.5; r = new Rectangle(); r.Fill = linear; thick = new Thickness(); thick.Left = 200; thick.Top = 200; r.Margin = thick; r.Width = 400; r.Height = 400; canvas.Children.Add(r); if (shouldMeasure) { Size sz = new Size(8.5 * 96, 11 * 96); canvas.Measure(sz); canvas.Arrange(new Rect(new Point(), sz)); canvas.UpdateLayout(); } return canvas; }
/// <summary> /// draw an exception /// </summary> /// <param name="canvas"></param> /// <param name="exception"></param> public static void DrawException(Canvas canvas, String exception) { canvas.Background = ProfileManager.ActiveProfile.BackgroundColor; double sixth = canvas.Height / 6; double tenth = canvas.Width / 10; canvas.Children.Clear(); TextBlock overallOperationTextBlock = new TextBlock(); overallOperationTextBlock.Text = exception; overallOperationTextBlock.Foreground = ProfileManager.ActiveProfile.PrimaryColor; overallOperationTextBlock.FontSize = sixth / 1.5; overallOperationTextBlock.Width = canvas.Width; overallOperationTextBlock.Margin = new Thickness(0, 3 * sixth, 0, 0); overallOperationTextBlock.FontFamily = new System.Windows.Media.FontFamily("Century Gothic"); overallOperationTextBlock.TextAlignment = TextAlignment.Center; canvas.Children.Add(overallOperationTextBlock); canvas.UpdateLayout(); canvas.Refresh(); }
BitmapImage InsertBackgroundData (Canvas ForecastFrame, String BackgroundName) { Image BackgroundImage = null; if (ForecastFrame.Children.Count > 0) BackgroundImage= (Image)ForecastFrame.Children [0]; if (BackgroundImage == null) { BackgroundImage = new Image (); BackgroundImage.Stretch = Stretch.UniformToFill; ForecastFrame.Children.Add (BackgroundImage); } String BackgroundPath = System.IO.Path.Combine (m_ProgrammRoot + "\\WeatherPictures", BackgroundName); if (!File.Exists (BackgroundPath)) return null; BitmapImage BackgroundBitmap = new BitmapImage (); BackgroundBitmap.BeginInit (); BackgroundBitmap.UriSource = new Uri (BackgroundPath); BackgroundBitmap.EndInit (); ForecastFrame.UpdateLayout (); BackgroundImage.Width = ForecastFrame.ActualWidth; BackgroundImage.Source = BackgroundBitmap; BackgroundImage.UpdateLayout (); double TopPosition = (ForecastFrame.ActualHeight - BackgroundImage.ActualHeight) / 2; Canvas.SetTop (BackgroundImage, TopPosition); return BackgroundBitmap; }
void InsertWeatherDetails (Canvas FramingCanvas, XmlNode Location, XmlNode ForecastNode, int LocationIndex, int WeatherIndex) { String [] PositionsTable = (String []) m_Districts [LocationIndex]; FramingCanvas.UpdateLayout (); foreach (String Entry in PositionsTable) { String [] Elements = Entry.Split (';'); double WidthPercentage = Convert.ToDouble (Elements [0]); double HeightPercentage = Convert.ToDouble (Elements [1]); double TextSizePercentage = Convert.ToDouble (Elements [3]); double IconWidthPercentage = Convert.ToDouble (Elements [4]); if (WeatherIndex == 0) SetAnimationParameter (FramingCanvas, (FrameworkElement)InsertCanvasPositionedText (FramingCanvas, Elements [2], WidthPercentage, HeightPercentage, TextSizePercentage, "Bold", "Black"), new PropertyPath (Image.OpacityProperty)); else { String WeatherName = "icon_" + ForecastNode.SelectSingleNode ("child::iconcode").InnerText + ".png"; SetAnimationParameter (FramingCanvas, (FrameworkElement)InsertCanvasPositionedIcons (FramingCanvas, WeatherName, WidthPercentage, HeightPercentage, IconWidthPercentage), new PropertyPath (Image.OpacityProperty)); } } String [] SymbolsTable = (String [])m_Symbole [LocationIndex]; foreach (String SymbolEntry in SymbolsTable) { String [] SymbolElements = SymbolEntry.Split (';'); double SymbolWidthPercentage = Convert.ToDouble (SymbolElements [0]); double SymbolHeightPercentage = Convert.ToDouble (SymbolElements [1]); String TypeOfEntry = SymbolElements [2]; double TextSizePercentage = Convert.ToDouble (SymbolElements [3]); double IconWidthPercentage = Convert.ToDouble (SymbolElements [4]); if (WeatherIndex == 0) continue; if (TypeOfEntry == "WindRose") { String WindDirName = "wind_" + ForecastNode.SelectSingleNode ("child::winddir_text").InnerText + ".png"; SetAnimationParameter (FramingCanvas, (FrameworkElement)InsertCanvasPositionedIcons (FramingCanvas, WindDirName, SymbolWidthPercentage, SymbolHeightPercentage, IconWidthPercentage), new PropertyPath (Image.OpacityProperty)); } if (TypeOfEntry == "WindGeschwindigkeit") { String WindSpeed = ForecastNode.SelectSingleNode ("child::windspeed").InnerText; String WindSpeedString = WindSpeed + " km/h"; SetAnimationParameter (FramingCanvas, (FrameworkElement)InsertCanvasPositionedText (FramingCanvas, WindSpeedString, SymbolWidthPercentage, SymbolHeightPercentage, TextSizePercentage, "Bold", WeatherTextColor), new PropertyPath (TextBlock.OpacityProperty)); } if (TypeOfEntry == "WindRichtung") { String WindDir = ForecastNode.SelectSingleNode ("child::winddir_text").InnerText; String WindDirText = "Wind aus " + WindDir; SetAnimationParameter (FramingCanvas, (FrameworkElement)InsertCanvasPositionedText (FramingCanvas, WindDirText, SymbolWidthPercentage, SymbolHeightPercentage, TextSizePercentage, "Bold", WeatherTextColor), new PropertyPath (TextBlock.OpacityProperty)); } if (TypeOfEntry == "Temperatur") { String TempMin = ForecastNode.SelectSingleNode ("child::temp_min").InnerText; String TempMax = ForecastNode.SelectSingleNode ("child::temp_max").InnerText; String TempString; if (String.Compare (TempMin, TempMax) != 0) TempString = "Temp: " + TempMin + "° - " + TempMax + "°"; else TempString = "Temp: " + TempMax + "°"; SetAnimationParameter (FramingCanvas, (FrameworkElement)InsertCanvasPositionedText (FramingCanvas, TempString, SymbolWidthPercentage, SymbolHeightPercentage, TextSizePercentage, "Bold", WeatherTextColor), new PropertyPath (TextBlock.OpacityProperty)); } } }
public Image InsertCanvasPositionedPicture (Canvas FramingCanvas, String Base64Input, double LeftPercentage, double TopPercentage, double ImageWidthPercentage, double ImageHeightPercentage) { Image PictureImage = new Image (); FramingCanvas.Children.Add (PictureImage); FramingCanvas.UpdateLayout (); double ActCanvasHeight = FramingCanvas.ActualHeight; double ActCanvasWidth = FramingCanvas.ActualWidth; byte [] ImageBytes = System.Convert.FromBase64String (Base64Input); MemoryStream ImageDataStream = new MemoryStream (); ImageDataStream.Write (ImageBytes, 0, ImageBytes.Length); ImageDataStream.Seek (0, SeekOrigin.Begin); BitmapImage DrawingBitmap = new BitmapImage (); //DrawingBitmap.CacheOption = BitmapCacheOption.OnLoad; DrawingBitmap.BeginInit (); DrawingBitmap.StreamSource = ImageDataStream; DrawingBitmap.EndInit (); if (ImageWidthPercentage > 0) { DrawingBitmap.DecodePixelWidth = (int)(ActCanvasWidth * ImageWidthPercentage / 100); PictureImage.Width = ActCanvasWidth * ImageWidthPercentage / 100; } if (ImageHeightPercentage > 0) { DrawingBitmap.DecodePixelHeight = (int)(ActCanvasHeight * ImageHeightPercentage / 100); PictureImage.Height = ActCanvasHeight * ImageHeightPercentage / 100; } PictureImage.Source = DrawingBitmap; //PictureImage.Width = ActCanvasWidth * ImageWidthPercentage / 100; PictureImage.UpdateLayout (); //double ActIconHeight = PictureImage.ActualHeight; //double ActIconWidth = PictureImage.ActualWidth; Canvas.SetTop (PictureImage, ((ActCanvasHeight * TopPercentage) / 100)); Canvas.SetLeft (PictureImage, ((ActCanvasWidth * LeftPercentage) / 100)); return PictureImage; }
private BitmapSource DrawLines(string transformedText, double scaleX, double scaleY) { var bitmap = new RenderTargetBitmap((int)(LayoutRoot.ActualWidth * scaleX), (int)(LayoutRoot.ActualHeight * scaleY), 96, 96, PixelFormats.Pbgra32); Rect? lastRect = null; var result = new byte[(int)(LayoutRoot.ActualWidth * scaleX) * 4 * (int)(LayoutRoot.ActualHeight * scaleY)]; foreach (var symbol in transformedText) { if (symbol < '1' || symbol > '9') continue; var rect = ConvertNumberToCellCoords(symbol - '1'); rect.X *= scaleX; rect.Y *= scaleY; rect.Width *= scaleX; rect.Height *= scaleY; var color = new Color { A = 255, R = LineColor.SelectedColor.Value.R, G = LineColor.SelectedColor.Value.G, B = LineColor.SelectedColor.Value.B }; if (lastRect != null) { if (lastRect == rect) { var canvas = new Canvas(); var circle = new Ellipse { Stroke = new SolidColorBrush(color), StrokeThickness = (LineSize.Value + 2) * (scaleX + scaleY) / 2 }; circle.Width = (LineSize.Value + 2) * 2 * scaleX; circle.Height = (LineSize.Value + 2) * 2 * scaleY; Canvas.SetLeft(circle, rect.Width / 2 - (LineSize.Value + 2) * scaleX + rect.Left); Canvas.SetTop(circle, rect.Height / 2 - (LineSize.Value + 2) * scaleY + rect.Top); canvas.Children.Add(circle); canvas.Measure(new Size(rect.Width, rect.Height)); canvas.Arrange(new Rect(new Size(rect.Width, rect.Height))); canvas.UpdateLayout(); bitmap.Render(canvas); } else { var lineLength = Math.Sqrt( Math.Abs(rect.Left - lastRect.Value.Left) * Math.Abs(rect.Left - lastRect.Value.Left) + Math.Abs(rect.Top - lastRect.Value.Top) * Math.Abs(rect.Top - lastRect.Value.Top)); var proportion = lineLength / Math.Sin(Math.PI / 180 * 90); var angle = Math.Asin(Math.Abs(rect.Top - lastRect.Value.Top) / proportion) * (180 / Math.PI); if (rect.Left > lastRect.Value.Left && rect.Top == lastRect.Value.Top) { angle += 90; } if (rect.Left < lastRect.Value.Left && rect.Top == lastRect.Value.Top) { angle -= 90; } if (rect.Left == lastRect.Value.Left && rect.Top > lastRect.Value.Top) { angle += 90; } if (rect.Left == lastRect.Value.Left && rect.Top < lastRect.Value.Top) { angle -= 90; } if (rect.Left > lastRect.Value.Left && rect.Top > lastRect.Value.Top) { angle += 90; } if (rect.Left > lastRect.Value.Left && rect.Top < lastRect.Value.Top) { angle = Math.Asin(Math.Abs(rect.Left - lastRect.Value.Left) / proportion) * (180 / Math.PI); } if (rect.Left < lastRect.Value.Left && rect.Top < lastRect.Value.Top) { angle -= 90; } if (rect.Left < lastRect.Value.Left && rect.Top > lastRect.Value.Top) { angle = Math.Asin(Math.Abs(rect.Left - lastRect.Value.Left) / proportion) * (180 / Math.PI); angle -= 180; } var canvas = new Canvas(); var line = new Line { Stroke = new SolidColorBrush(color), StrokeThickness = LineSize.Value * (scaleX + scaleY) / 2, StrokeStartLineCap = PenLineCap.Round, StrokeEndLineCap = PenLineCap.Round, }; line.X1 = rect.Width / 2; line.Y1 = rect.Height / 2; line.X2 = rect.Width / 2; line.Y2 = rect.Height / 2 + lineLength; canvas.Children.Add(line); canvas.RenderTransformOrigin = new Point(0.5, 0.5); var transformGroup = new TransformGroup(); transformGroup.Children.Add(new RotateTransform(angle)); transformGroup.Children.Add(new TranslateTransform(rect.Left, rect.Top)); canvas.RenderTransform = transformGroup; canvas.Measure(new Size(rect.Width, rect.Height)); canvas.Arrange(new Rect(new Size(rect.Width, rect.Height))); canvas.UpdateLayout(); bitmap.Render(canvas); } } lastRect = rect; } bitmap.CopyPixels( result, (int)(LayoutRoot.ActualWidth * scaleX) * 4, 0); for (var offset = 0; offset < result.Length; offset += 4) { if (result[offset + 3] == 0) continue; result[offset] = (byte)Math.Round(result[offset] / (result[offset + 3] / 255.0)); result[offset + 1] = (byte)Math.Round(result[offset + 1] / (result[offset + 3] / 255.0)); result[offset + 2] = (byte)Math.Round(result[offset + 2] / (result[offset + 3] / 255.0)); } for (var offset = 0; offset < result.Length; offset += 4) { if (result[offset + 3] == 0) continue; result[offset + 3] = Math.Min((byte)(result[offset + 3] * (LineColor.SelectedColor.Value.A / 255.0)), (byte)255); } return BitmapSource.Create( (int)(LayoutRoot.ActualWidth * scaleX), (int)(LayoutRoot.ActualHeight * scaleY), 96, 96, PixelFormats.Bgra32, null, result, (int)(LayoutRoot.ActualWidth * scaleX) * 4); }
/// <summary> /// Prints the specified plot model. /// </summary> /// <param name="model">The model.</param> public void Print(IPlotModel model) { PrintDocumentImageableArea area = null; var xpsDocumentWriter = PrintQueue.CreateXpsDocumentWriter(ref area); if (xpsDocumentWriter != null) { var width = this.Width; var height = this.Height; if (double.IsNaN(width)) { width = area.MediaSizeWidth; } if (double.IsNaN(height)) { height = area.MediaSizeHeight; } var canvas = new Canvas { Width = width, Height = height, Background = this.Background.ToBrush() }; canvas.Measure(new Size(width, height)); canvas.Arrange(new Rect(0, 0, width, height)); var rc = new ShapesRenderContext(canvas); #if !NET35 rc.TextFormattingMode = this.TextFormattingMode; #endif model.Update(true); model.Render(rc, width, height); canvas.UpdateLayout(); xpsDocumentWriter.Write(canvas); } }
/// <summary> /// Exports the specified <see cref="PlotModel" /> to the specified <see cref="Stream" />. /// </summary> /// <param name="model">The model.</param> /// <param name="stream">The stream.</param> public void Export(IPlotModel model, Stream stream) { using (var xpsPackage = Package.Open(stream)) { using (var doc = new XpsDocument(xpsPackage)) { var canvas = new Canvas { Width = this.Width, Height = this.Height, Background = this.Background.ToBrush() }; canvas.Measure(new Size(this.Width, this.Height)); canvas.Arrange(new Rect(0, 0, this.Width, this.Height)); var rc = new ShapesRenderContext(canvas); #if !NET35 rc.TextFormattingMode = this.TextFormattingMode; #endif model.Update(true); model.Render(rc, this.Width, this.Height); canvas.UpdateLayout(); var xpsdw = XpsDocument.CreateXpsDocumentWriter(doc); xpsdw.Write(canvas); } } }
/// <summary> /// Exports the specified plot model to a xml writer. /// </summary> /// <param name="model">The model.</param> /// <param name="writer">The xml writer.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <param name="background">The background.</param> private static void Export(IPlotModel model, XmlWriter writer, double width, double height, OxyColor background) { var c = new Canvas(); if (background.IsVisible()) { c.Background = background.ToBrush(); } c.Measure(new Size(width, height)); c.Arrange(new Rect(0, 0, width, height)); var rc = new CanvasRenderContext(c) { UseStreamGeometry = false }; rc.TextFormattingMode = TextFormattingMode.Ideal; model.Update(true); model.Render(rc, width, height); c.UpdateLayout(); XamlWriter.Save(c, writer); }
/// <summary> /// Create cursor for drag and drop. /// </summary> /// <param name="baseCursor">Base cursor that is show in the top left corner.</param> /// <returns>Create cursor.</returns> private System.Windows.Forms.Cursor _CreateCursor(System.Windows.Forms.Cursor baseCursor) { // Create cursor canvas. Canvas cursorCanvas = new Canvas(); // Get base cursor image. System.Drawing.Point hotSpotPoint; Image baseCursorImage = _CreateImageFromCursor(baseCursor, out hotSpotPoint); // Add base cursor. cursorCanvas.Children.Add(baseCursorImage); // Add adornment. cursorCanvas.Children.Add(_adornment.Adornment); // Move adornment below base cusor. cursorCanvas.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); // Get base cursor image last visible pixel. Point cursorLastVisiblePoint = _GetBitmapLastVisiblePixel(baseCursorImage.Source as BitmapSource); Canvas.SetTop(_adornment.Adornment, cursorLastVisiblePoint.Y + SPACE_SIZE); Canvas.SetLeft(_adornment.Adornment, cursorLastVisiblePoint.X + SPACE_SIZE); // Arrange cursor canvas to get its actual height and width. double cursorWidth = cursorLastVisiblePoint.X + SPACE_SIZE + _adornment.Adornment.Width; double cursorHeight = cursorLastVisiblePoint.Y + SPACE_SIZE + _adornment.Adornment.Height; Rect cursorRect = new Rect(0, 0, cursorWidth, cursorHeight); cursorCanvas.Arrange(cursorRect); cursorCanvas.UpdateLayout(); // Create cursor. System.Windows.Forms.Cursor cursor = _CreateCursorFromCanvas(cursorCanvas, hotSpotPoint); // Remove all canvas elements. cursorCanvas.Children.Clear(); return cursor; }
public Image InsertBackgroundImage (Canvas BackGroundFrame, String BackgroundFileName) { Image BackgroundImage = new Image (); BackgroundImage.Stretch = Stretch.UniformToFill; BackGroundFrame.Children.Insert (0, BackgroundImage); String BackgroundPath = BackgroundFileName; if (!System.IO.Path.IsPathRooted (BackgroundPath)) BackgroundPath = System.IO.Path.Combine (ProcessableDirectories [DirectoryToProcessIndex], BackgroundFileName); if (!File.Exists (BackgroundPath)) return null; BitmapImage BackgroundBitmap = new BitmapImage (); BackgroundBitmap.BeginInit (); BackgroundBitmap.UriSource = new Uri (BackgroundPath); BackgroundBitmap.EndInit (); BackgroundImage.Source = BackgroundBitmap; BackGroundFrame.UpdateLayout (); double CalculationWidth; double CalculationHeight; if (BackGroundFrame.ActualWidth > 1) CalculationWidth = BackGroundFrame.ActualWidth; else CalculationWidth = BackGroundFrame.Width; if (BackGroundFrame.ActualHeight > 1) CalculationHeight = BackGroundFrame.ActualHeight; else CalculationHeight = BackGroundFrame.Height; double SourceAspectRatio = BackgroundBitmap.Width / BackgroundBitmap.Height; double TargetAspectRatio = CalculationWidth / CalculationHeight; double TopPosition = 0; double LeftPosition = 0; if (SourceAspectRatio == TargetAspectRatio) { BackgroundImage.Width = CalculationWidth; } if (SourceAspectRatio < TargetAspectRatio) { BackgroundImage.Height = CalculationHeight; BackgroundImage.UpdateLayout (); LeftPosition = (CalculationWidth - (CalculationHeight * SourceAspectRatio)) / 2; } if (SourceAspectRatio > TargetAspectRatio) { BackgroundImage.Width = CalculationWidth; BackgroundImage.UpdateLayout (); TopPosition = (CalculationHeight - (CalculationWidth / SourceAspectRatio)) / 2; } Canvas.SetTop (BackgroundImage, TopPosition); Canvas.SetLeft (BackgroundImage, LeftPosition); return BackgroundImage; }
public TextBlock InsertCanvasPositionedTextBlock (Canvas FramingCanvas, String Text, double WidthPercentage, double HeightPercentage, double FontSizePercentage, double LeftPercentage, double TopPercentage, String Weight, String Color) { FontWeightConverter FWConverter = new FontWeightConverter (); BrushConverter BRConverter = new BrushConverter (); TextBlock BlockName = new TextBlock (); BlockName.Visibility = Visibility.Visible; FramingCanvas.Children.Add (BlockName); FramingCanvas.UpdateLayout (); double ActCanvasHeight = FramingCanvas.ActualHeight; if (ActCanvasHeight == 0) ActCanvasHeight = FramingCanvas.Height; double ActCanvasWidth = FramingCanvas.ActualWidth; if (ActCanvasWidth == 0) ActCanvasWidth = FramingCanvas.Width; Canvas.SetTop (BlockName, ((ActCanvasHeight * TopPercentage) / 100)); Canvas.SetLeft (BlockName, ((ActCanvasWidth * LeftPercentage) / 100)); double BlockNameWidth = (ActCanvasWidth * WidthPercentage) / 100; double BlockNameHeight = (ActCanvasHeight * HeightPercentage) / 100; Text = Text.Replace ("\r\n", " "); Text = Text.Replace ("\n", " "); Text = Text.Replace ("\r", " "); bool TextFit = false; double FontReduction = 1; while (!TextFit) { BlockName.FontSize = (ActCanvasHeight * FontSizePercentage / 100.0) * FontReduction; BlockName.FontWeight = (FontWeight)FWConverter.ConvertFromString (Weight); if (Color.IndexOf ('$') == -1) BlockName.Foreground = (Brush)BRConverter.ConvertFromString (Color); else BlockName.Foreground = (Brush)BRConverter.ConvertFromString (Color); BlockName.TextAlignment = TextAlignment.Left; BlockName.TextWrapping = TextWrapping.Wrap; BlockName.Text = Text; BlockName.UpdateLayout (); double ActTextHeight = BlockName.ActualHeight; double ActTextWidth = BlockName.ActualWidth; double NumberOfPossibleLines = (double)((int)(BlockNameHeight / ActTextHeight)); double RequiredNumberOfLines = (ActTextWidth * 1.10) / BlockNameWidth; if (RequiredNumberOfLines < NumberOfPossibleLines) { TextFit = true; } FontReduction -= 0.05; if (FontReduction < 0.30) TextFit = true; } BlockName.Width = BlockNameWidth; BlockName.Height = BlockNameHeight; return BlockName; }
public TextBlock InsertCanvasPositionedText (Canvas FramingCanvas, String Text, double WidthPercentage, double HeightPercentage, double FontSizePercentage, String Weight, String Color) { FontWeightConverter FWConverter = new FontWeightConverter (); BrushConverter BRConverter = new BrushConverter (); TextBlock BlockName = new TextBlock (); BlockName.Visibility = Visibility.Visible; FramingCanvas.Children.Add (BlockName); FramingCanvas.UpdateLayout (); double ActCanvasHeight = FramingCanvas.ActualHeight; double ActCanvasWidth = FramingCanvas.ActualWidth; BlockName.FontSize = ActCanvasHeight * FontSizePercentage / 100.0; BlockName.FontWeight = (FontWeight)FWConverter.ConvertFromString (Weight); BlockName.Foreground = (Brush)BRConverter.ConvertFromString (Color); BlockName.Text = Text; BlockName.TextAlignment = TextAlignment.Center; BlockName.UpdateLayout (); double ActTextHeight = BlockName.ActualHeight; double ActTextWidth = BlockName.ActualWidth; Canvas.SetTop (BlockName, (((ActCanvasHeight * HeightPercentage) / 100) - (ActTextHeight / 2))); Canvas.SetLeft (BlockName, (((ActCanvasWidth * WidthPercentage) / 100) - (ActTextWidth / 2))); return BlockName; }
/// <summary> /// Creates image from canvas with map background. /// </summary> /// <param name="mapImage">Map image.</param> /// <param name="canvas">Canvas to draw.</param> /// <returns>Created image.</returns> private Image _CreateImage(MapImage mapImage, SysControls.Canvas canvas) { Debug.Assert(null != mapImage); Debug.Assert(null != canvas); Image imageWithData = null; RenderTargetBitmap bmp = null; SysControls.Canvas outer = null; Image sourceImage = null; using (MemoryStream sourceStream = new MemoryStream((byte[])mapImage.ImageData)) sourceImage = Image.FromStream(sourceStream); try { var bitmap = sourceImage as Bitmap; Debug.Assert(null != bitmap); ImageBrush imageBrush = _CreateImageBrush(bitmap); outer = new SysControls.Canvas(); outer.Width = mapImage.ImageWidth; outer.Height = mapImage.ImageHeight; outer.Children.Add(canvas); outer.Background = (ImageBrush)imageBrush.GetCurrentValueAsFrozen(); outer.Arrange(new Rect(0, 0, outer.Width, outer.Height)); bmp = new RenderTargetBitmap((int)outer.Width, (int)outer.Height, mapImage.ImageDPI, mapImage.ImageDPI, PixelFormats.Pbgra32); bmp.Render(outer); var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); using (MemoryStream stream = new MemoryStream()) { encoder.Save(stream); imageWithData = Image.FromStream(stream); } } finally { // Clear and dispose all used stuff if (outer != null) { outer.UpdateLayout(); outer.Children.Clear(); } canvas.UpdateLayout(); foreach (object child in canvas.Children) { var symbolControl = child as SymbolControl; if (symbolControl != null) symbolControl.Template = null; } canvas.Children.Clear(); if (bmp != null) bmp.Clear(); if (sourceImage != null) sourceImage.Dispose(); } return imageWithData; }
public Image InsertCanvasPositionedIcons (Canvas FramingCanvas, String IconFileName, double WidthPercentage, double HeightPercentage, double ImageWidthPercentage) { if (!File.Exists (IconFileName)) return null; Image IconImage = new Image (); FramingCanvas.Children.Add (IconImage); FramingCanvas.UpdateLayout (); double ActCanvasHeight = FramingCanvas.ActualHeight; double ActCanvasWidth = FramingCanvas.ActualWidth; BitmapImage IconBitmap = new BitmapImage (); IconBitmap.BeginInit (); IconBitmap.UriSource = new Uri (IconFileName); IconBitmap.EndInit (); IconImage.Source = IconBitmap; IconImage.Width = ActCanvasWidth * ImageWidthPercentage / 100; IconImage.UpdateLayout (); double ActIconHeight = IconImage.ActualHeight; double ActIconWidth = IconImage.ActualWidth; Canvas.SetTop (IconImage, (((ActCanvasHeight * HeightPercentage) / 100) - (ActIconHeight / 2))); Canvas.SetLeft (IconImage, (((ActCanvasWidth * WidthPercentage) / 100) - (ActIconWidth / 2))); return IconImage; }
private void OnRenderToCanvasChanged() { if (grid == null) return; if (RenderToCanvas) { if (canvas == null) { canvas = new Canvas(); grid.Children.Insert(0, canvas); canvas.UpdateLayout(); } if (plotFrame != null) { grid.Children.Remove(plotFrame); grid.Children.Remove(plotAliasedFrame); plotFrame = null; plotAliasedFrame = null; } } else { if (plotFrame == null) { plotAliasedFrame = new PlotFrame(true); plotFrame = new PlotFrame(false); grid.Children.Insert(0, plotAliasedFrame); grid.Children.Insert(1, plotFrame); plotFrame.UpdateLayout(); plotAliasedFrame.UpdateLayout(); } if (canvas != null) { grid.Children.Remove(canvas); canvas = null; } } UpdateVisuals(); }
TextBlock InsertLineCenteredText (Canvas FramingCanvas, String Text, double FontSizePercentage, double TopPercentage, String Weight, String Color) { FontWeightConverter FWConverter = new FontWeightConverter (); BrushConverter BRConverter = new BrushConverter (); TextBlock BlockName = new TextBlock (); BlockName.Visibility = Visibility.Visible; FramingCanvas.Children.Add (BlockName); FramingCanvas.UpdateLayout (); double ActCanvasHeight = FramingCanvas.ActualHeight; double ActCanvasWidth = FramingCanvas.ActualWidth; BlockName.FontSize = FontSizePercentage * ActCanvasHeight / 100; BlockName.FontWeight = (FontWeight)FWConverter.ConvertFromString (Weight); BlockName.Foreground = (Brush)BRConverter.ConvertFromString (Color); BlockName.Text = Text; BlockName.TextAlignment = TextAlignment.Center; BlockName.UpdateLayout (); double ActHeadHeight = BlockName.ActualHeight; double ActHeadWidth = BlockName.ActualWidth; Canvas.SetTop (BlockName, (ActCanvasHeight * TopPercentage) / 100); Canvas.SetLeft (BlockName, ((ActCanvasWidth - ActHeadWidth) / 2)); return BlockName; }
public override void OnApplyTemplate() { base.OnApplyTemplate(); grid = GetTemplateChild(GridPartName) as Grid; if (grid == null) throw new InvalidOperationException($"A part named '{GridPartName}' must be present in the ControlTemplate, and must be of type '{typeof(Grid).FullName}'."); var canvas = new Canvas(); grid.Children.Add(canvas); canvas.UpdateLayout(); renderer = new CanvasRenderer(canvas); }
/// <summary> /// Creates image from canvas with map background. /// </summary> /// <param name="mapImage">Map image.</param> /// <param name="canvas">Canvas to draw.</param> /// <returns>Created image.</returns> private Image _CreateImage(MapImage mapImage, SysControls.Canvas canvas) { Debug.Assert(null != mapImage); Debug.Assert(null != canvas); Image imageWithData = null; RenderTargetBitmap bmp = null; SysControls.Canvas outer = null; Image sourceImage = null; using (MemoryStream sourceStream = new MemoryStream((byte[])mapImage.ImageData)) sourceImage = Image.FromStream(sourceStream); try { var bitmap = sourceImage as Bitmap; Debug.Assert(null != bitmap); ImageBrush imageBrush = _CreateImageBrush(bitmap); outer = new SysControls.Canvas(); outer.Width = mapImage.ImageWidth; outer.Height = mapImage.ImageHeight; outer.Children.Add(canvas); outer.Background = (ImageBrush)imageBrush.GetCurrentValueAsFrozen(); outer.Arrange(new Rect(0, 0, outer.Width, outer.Height)); bmp = new RenderTargetBitmap((int)outer.Width, (int)outer.Height, mapImage.ImageDPI, mapImage.ImageDPI, PixelFormats.Pbgra32); bmp.Render(outer); var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); using (MemoryStream stream = new MemoryStream()) { encoder.Save(stream); imageWithData = Image.FromStream(stream); } } finally { // Clear and dispose all used stuff if (outer != null) { outer.UpdateLayout(); outer.Children.Clear(); } canvas.UpdateLayout(); foreach (object child in canvas.Children) { var symbolControl = child as SymbolControl; if (symbolControl != null) { symbolControl.Template = null; } } canvas.Children.Clear(); if (bmp != null) { bmp.Clear(); } if (sourceImage != null) { sourceImage.Dispose(); } } return(imageWithData); }
/// <summary> /// Draw processing progress /// </summary> /// <param name="canvas">canvas where the progress will be drawn</param> /// <param name="pp">active processing progress</param> public static void DrawProgress(Canvas canvas, ProcessingProgress pp) { canvas.Background = ProfileManager.MinimalView ? System.Windows.Media.Brushes.Transparent : ProfileManager.ActiveProfile.BackgroundColor; String currentOperationName = pp.CurrentOperationName; Double currentOperation = ((Double)pp.CurrentOperationElement * 100 / (Double)pp.CurrentOperationTotalElements); String currentOperationProgress = String.Format("{0:00.00}", currentOperation) + " %"; String overallOperationName = pp.OverallOperationName; Double overallOperation = ((Double)pp.OverallOperationElement * 100 / (Double)pp.OverallOperationTotalElements); String overallOperationProgress = String.Format("{0:00.00}", overallOperation) + " %"; canvas.Children.Clear(); double sixth = canvas.Height / 6; double tenth = canvas.Width / 10; //current System.Windows.Shapes.Rectangle currentOperationOuterRect = new System.Windows.Shapes.Rectangle(); currentOperationOuterRect.Width = canvas.Width - tenth; currentOperationOuterRect.Height = sixth; currentOperationOuterRect.Stroke = ProfileManager.ActiveProfile.SecondaryColor; currentOperationOuterRect.StrokeThickness = 2; currentOperationOuterRect.Fill = ProfileManager.ActiveProfile.BackgroundColor; currentOperationOuterRect.Margin = new Thickness(tenth / 2, sixth, 0, 0); System.Windows.Shapes.Rectangle currentOperationInnerRect = new System.Windows.Shapes.Rectangle(); currentOperationInnerRect.Width = ((canvas.Width - tenth - 6) * currentOperation) / 100; currentOperationInnerRect.Height = sixth - 6; currentOperationInnerRect.Stroke = ProfileManager.ActiveProfile.BackgroundColor; currentOperationInnerRect.StrokeThickness = 2; currentOperationInnerRect.Fill = ProfileManager.ActiveProfile.SecondaryColor; currentOperationInnerRect.Margin = new Thickness((tenth + 6) / 2, sixth + 3, 0, 0); TextBlock currentOperationTextBlock = new TextBlock(); currentOperationTextBlock.Text = currentOperationName + " [ " + currentOperationProgress + " ]"; currentOperationTextBlock.Foreground = ProfileManager.ActiveProfile.SecondaryColor; currentOperationTextBlock.FontSize = sixth / 1.5; currentOperationTextBlock.Width = canvas.Width; currentOperationTextBlock.FontFamily = new System.Windows.Media.FontFamily("Century Gothic"); currentOperationTextBlock.TextAlignment = TextAlignment.Center; //overall System.Windows.Shapes.Rectangle overallOperationOuterRect = new System.Windows.Shapes.Rectangle(); overallOperationOuterRect.Width = canvas.Width - tenth; overallOperationOuterRect.Height = sixth; overallOperationOuterRect.Stroke = ProfileManager.ActiveProfile.PrimaryColor; overallOperationOuterRect.StrokeThickness = 2; overallOperationOuterRect.Fill = ProfileManager.ActiveProfile.BackgroundColor; overallOperationOuterRect.Margin = new Thickness(tenth / 2, 4 * sixth, 0, 0); System.Windows.Shapes.Rectangle overallOperationInnerRect = new System.Windows.Shapes.Rectangle(); overallOperationInnerRect.Width = ProfileManager.MinimalView ? ((canvas.Width - tenth) * overallOperation) / 100 : ((canvas.Width - tenth - 6) * overallOperation) / 100; overallOperationInnerRect.Height = ProfileManager.MinimalView ? sixth - 2 : sixth - 6; overallOperationInnerRect.Stroke = ProfileManager.ActiveProfile.BackgroundColor; overallOperationInnerRect.StrokeThickness = ProfileManager.MinimalView ? 0 : 2; overallOperationInnerRect.Fill = ProfileManager.ActiveProfile.PrimaryColor; overallOperationInnerRect.Margin = ProfileManager.MinimalView ? new Thickness(tenth / 2 + 1, 4 * sixth + 1, 0, 0) : new Thickness((tenth + 6) / 2, 4 * sixth + 3, 0, 0); TextBlock overallOperationTextBlock = new TextBlock(); overallOperationTextBlock.Text = overallOperationName + " [ " + overallOperationProgress + " ]"; overallOperationTextBlock.Foreground = ProfileManager.ActiveProfile.PrimaryColor; overallOperationTextBlock.FontSize = sixth / 1.5; overallOperationTextBlock.Width = canvas.Width; overallOperationTextBlock.Margin = new Thickness(0, 3 * sixth, 0, 0); overallOperationTextBlock.FontFamily = new System.Windows.Media.FontFamily("Century Gothic"); overallOperationTextBlock.TextAlignment = TextAlignment.Center; if (!ProfileManager.MinimalView) canvas.Children.Add(currentOperationTextBlock); if (!ProfileManager.MinimalView) canvas.Children.Add(currentOperationOuterRect); if (!ProfileManager.MinimalView) canvas.Children.Add(currentOperationInnerRect); if (!ProfileManager.MinimalView) canvas.Children.Add(overallOperationTextBlock); canvas.Children.Add(overallOperationOuterRect); canvas.Children.Add(overallOperationInnerRect); canvas.UpdateLayout(); canvas.Refresh(); }
/// <summary> /// Exports the specified plot model to a bitmap. /// </summary> /// <param name="model">The model to export.</param> /// <returns>A bitmap.</returns> public BitmapSource ExportToBitmap(IPlotModel model) { var scale = 96d / this.Resolution; var canvas = new Canvas { Width = this.Width * scale, Height = this.Height * scale, Background = this.Background.ToBrush() }; canvas.Measure(new Size(canvas.Width, canvas.Height)); canvas.Arrange(new Rect(0, 0, canvas.Width, canvas.Height)); var rc = new CanvasRenderContext(canvas) { RendersToScreen = false }; rc.TextFormattingMode = TextFormattingMode.Ideal; model.Update(true); model.Render(rc, canvas.Width, canvas.Height); canvas.UpdateLayout(); var bmp = new RenderTargetBitmap(this.Width, this.Height, this.Resolution, this.Resolution, PixelFormats.Pbgra32); bmp.Render(canvas); return bmp; // alternative implementation: // http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.rendertargetbitmap.aspx // var dv = new DrawingVisual(); // using (var ctx = dv.RenderOpen()) // { // var vb = new VisualBrush(canvas); // ctx.DrawRectangle(vb, null, new Rect(new Point(), new Size(width, height))); // } // bmp.Render(dv); }
// ------------------------- CreateFirstVisual ------------------------ /// <summary> /// Creates content for the first visual sample.</summary> /// <param name="shouldMeasure"> /// true to remeasure the layout.</param> /// <returns> /// The canvas containing the visual.</returns> public Canvas CreateFirstVisual(bool shouldMeasure) { Canvas canvas1 = new Canvas(); canvas1.Width = 96 * 8.5; canvas1.Height = 96 * 11; // Top-Left TextBlock label = new TextBlock(); label.Foreground = Brushes.DarkBlue; label.FontFamily = new System.Windows.Media.FontFamily("Arial"); label.FontSize = 36.0; label.Text = "TopLeft"; Canvas.SetTop(label, 0); Canvas.SetLeft(label, 0); canvas1.Children.Add(label); // Bottom-Right label = new TextBlock(); label.Foreground = Brushes.Bisque; label.Text = "BottomRight"; label.FontFamily = new System.Windows.Media.FontFamily("Arial"); label.FontSize = 56.0; Canvas.SetTop(label, 750); Canvas.SetLeft(label, 520); canvas1.Children.Add(label); // Top-Right label = new TextBlock(); label.Foreground = Brushes.BurlyWood; label.Text = "TopRight"; label.FontFamily = new System.Windows.Media.FontFamily("CASTELLAR"); label.FontSize = 32.0; Canvas.SetTop(label, 0); Canvas.SetLeft(label, 520); canvas1.Children.Add(label); // Bottom-Left label = new TextBlock(); label.Foreground = Brushes.Cyan; label.Text = "BottomLeft"; label.FontFamily = new System.Windows.Media.FontFamily("Arial"); label.FontSize = 18.0; Canvas.SetTop(label, 750); Canvas.SetLeft(label, 0); canvas1.Children.Add(label); // Adding a rectangle to the page Rectangle firstRectangle = new Rectangle(); firstRectangle.Fill = new SolidColorBrush(Colors.Red); Thickness thick = new Thickness(); thick.Left = 150; thick.Top = 150; firstRectangle.Margin = thick; firstRectangle.Width = 300; firstRectangle.Height = 300; canvas1.Children.Add(firstRectangle); //Add a button to the page Button firstButton = new Button(); firstButton.Background = Brushes.LightYellow; firstButton.BorderBrush = new SolidColorBrush(Colors.Black); firstButton.BorderThickness = new Thickness(4); firstButton.Content = "I am button 1..."; firstButton.FontSize = 16.0; thick.Left = 80; thick.Top = 250; firstButton.Margin = thick; canvas1.Children.Add(firstButton); // Add an Ellipse Ellipse firstEllipse = new Ellipse(); SolidColorBrush firstSolidColorBrush = new SolidColorBrush(Colors.DarkCyan); firstSolidColorBrush.Opacity = 0.7; firstEllipse.Fill = firstSolidColorBrush; SetEllipse(firstEllipse, 500, 350, 120, 250); canvas1.Children.Add(firstEllipse); // Add a Polygon Polygon polygon = new Polygon(); polygon.Fill = Brushes.Bisque; polygon.Opacity = 0.2; PointCollection points = new PointCollection(); points.Add(new Point(50, 0)); points.Add(new Point(10, 30)); points.Add(new Point(30, 170)); points.Add(new Point(90, 40)); points.Add(new Point(230, 180)); points.Add(new Point(200, 60)); points.Add(new Point(240, 10)); points.Add(new Point(70, 130)); polygon.Points = points; polygon.Stroke = Brushes.Navy; Canvas.SetTop(polygon, 300); Canvas.SetLeft(polygon, 160); canvas1.Children.Add(polygon); if (shouldMeasure) { Size sz = new Size(8.5 * 96, 11 * 96); canvas1.Measure(sz); canvas1.Arrange(new Rect(new Point(), sz)); canvas1.UpdateLayout(); } return canvas1; }
private void btSaveImage_Click(object sender, RoutedEventArgs e) { if (_collector == null) return; // Create new canvas and renderer var cnv = new Canvas() { Margin = cnvChart.Margin, Width = cnvChart.ActualWidth, Height = cnvChart.ActualHeight, Background = System.Windows.Media.Brushes.White }; var ch = new ChartRendering.ChartRenderer(cnv, _collector.Datas); cnv.Measure(new System.Windows.Size(double.PositiveInfinity, double.PositiveInfinity)); cnv.Arrange(new Rect(0, 0, cnv.DesiredSize.Width, cnv.DesiredSize.Height)); var cwidth = (int)cnv.RenderSize.Width; var cheight = (int)(cnv.RenderSize.Height + cnv.Margin.Top * 2); var rtb = new RenderTargetBitmap(cwidth, cheight, 96d, 96d, PixelFormats.Default); // Generate a white background var dv = new DrawingVisual(); var dvct = dv.RenderOpen(); dvct.DrawRectangle(System.Windows.Media.Brushes.White, null, new Rect(0, 0, rtb.Width, rtb.Height)); dvct.Close(); rtb.Render(dv); // Render chart and create Bitmap ch.Render(false); // Add additional informations overlays AddChartImageInfos(cnv); cnv.UpdateLayout(); rtb.Render(cnv); // Open file dialog and save image if OK var fd = new SaveFileDialog(); fd.Filter = "PNG Images|*.png"; fd.DefaultExt = ".png"; fd.InitialDirectory = Properties.Settings.Default.fdpath_img; if (true == fd.ShowDialog(this)) { Properties.Settings.Default.fdpath_img = Path.GetDirectoryName(fd.FileName); Properties.Settings.Default.Save(); var bf = BitmapFrame.Create(rtb); var pngEncoder = new PngBitmapEncoder(); pngEncoder.Frames.Add(bf); using (var st = System.IO.File.OpenWrite(fd.FileName)) { pngEncoder.Save(st); } var result = MessageBox.Show("Show generated file in Explorer ?", "Image successfully generated", MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) System.Diagnostics.Process.Start("explorer.exe", "/select, " + fd.FileName); } }
// ------------------------- CreateSecondVisual ----------------------- /// <summary> /// Creates content for the second visual sample.</summary> /// <param name="shouldMeasure"> /// true to remeasure the layout.</param> /// <returns> /// The canvas containing the visual.</returns> public Canvas CreateSecondVisual(bool shouldMeasure) { Canvas canvas = new Canvas(); Ellipse ellipse = new Ellipse(); ellipse.Fill = Brushes.LightSeaGreen; SetEllipse(ellipse, 130, 200, 100, 70); ellipse.Stroke = Brushes.Black; canvas.Children.Add(ellipse); Rectangle rectangle = new Rectangle(); rectangle.Fill = Brushes.PowderBlue; rectangle.Opacity = 0.8; rectangle.RadiusX = 5; rectangle.RadiusY = 5; rectangle.Stroke = Brushes.Orange; rectangle.Height = 200; rectangle.Width = 350; Canvas.SetTop(rectangle, 50); Canvas.SetLeft(rectangle, 100); canvas.Children.Add(rectangle); Polygon polygon = new Polygon(); polygon.Fill = Brushes.MediumVioletRed; polygon.Opacity = 0.7; PointCollection points = new PointCollection(); points.Add(new Point(50, 0)); points.Add(new Point(10, 30)); points.Add(new Point(30, 170)); points.Add(new Point(90, 40)); points.Add(new Point(230, 180)); points.Add(new Point(200, 60)); points.Add(new Point(240, 10)); points.Add(new Point(70, 130)); polygon.Points = points; polygon.Stroke = Brushes.Navy; Canvas.SetTop(polygon, 150); Canvas.SetLeft(polygon, 250); canvas.Children.Add(polygon); TextBlock scribble = new TextBlock(); scribble.Foreground = Brushes.Green; scribble.FontFamily = new System.Windows.Media.FontFamily("Courier New"); scribble.FontSize = 18; scribble.Opacity = 0.5; Canvas.SetLeft(scribble, 96 * 3.7); Canvas.SetTop(scribble, 96 * 10.3); canvas.Children.Add(scribble); TextBlock para = new TextBlock(); para.Text = "This is a piece of text content."; para.FontSize = 16; para.FontFamily = new System.Windows.Media.FontFamily("Comic Sans MS"); para.Foreground = Brushes.Orange; Canvas.SetTop(para, 96 * 6); Canvas.SetLeft(para, 15); canvas.Children.Add(para); para = new TextBlock(); para.Text = "This is the second piece of text content."; para.FontSize = 16; para.FontFamily = new System.Windows.Media.FontFamily("Comic Sans MS"); para.Foreground = Brushes.Blue; Canvas.SetTop(para, 96 * 7.2); Canvas.SetLeft(para, 15); canvas.Children.Add(para); para = new TextBlock(); para.Text = "This is the last text section."; para.FontSize = 16; para.FontFamily = new System.Windows.Media.FontFamily("Comic Sans MS"); para.Foreground = Brushes.Red; Canvas.SetTop(para, 96 * 8.4); Canvas.SetLeft(para, 15); canvas.Children.Add(para); if (shouldMeasure) { Size sz = new Size(8.5 * 96, 11 * 96); canvas.Measure(sz); canvas.Arrange(new Rect(new Point(), sz)); canvas.UpdateLayout(); } return canvas; }