/// <summary> /// Renders the ui element into a bitmap frame using the specified scale. /// </summary> /// <param name = "element">The UI element.</param> /// <param name = "scale">The scale (default: 1).</param> /// <returns>The created bitmap frame</returns> public static BitmapSource RenderToBitmap(this UIElement element, double scale) { var renderWidth = (int) (element.RenderSize.Width * scale); var renderHeight = (int) (element.RenderSize.Height * scale); var renderTarget = new RenderTargetBitmap(renderWidth, renderHeight, 96, 96, PixelFormats.Pbgra32); var sourceBrush = new VisualBrush(element); var drawingVisual = new DrawingVisual(); using (var drawingContext = drawingVisual.RenderOpen()) { drawingContext.PushTransform(new ScaleTransform(scale, scale)); drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(element.RenderSize.Width, element.RenderSize.Height))); } renderTarget.Render(drawingVisual); return renderTarget; }
/*private async void Train(string personGroupId) * { * await faceServiceClient.TrainPersonGroupAsync(personGroupId); * * TrainingStatus trainingStatus = null; * while (true) * { * trainingStatus = await faceServiceClient.GetPersonGroupTrainingStatusAsync(personGroupId); * * if (trainingStatus.Status.ToString() != "running") * { * break; * } * * await Task.Delay(1000); * } * * string testImageFile = @"D:\Pictures\detection2.jpg"; * * using (Stream s = File.OpenRead(testImageFile)) * { * var faces = await faceServiceClient.DetectAsync(s); * var faceIds = faces.Select(face => face.FaceId).ToArray(); * * var results = await faceServiceClient.IdentifyAsync(personGroupId, faceIds); * foreach (var identifyResult in results) * { * Console.WriteLine("Result of face: {0}", identifyResult.FaceId); * if (identifyResult.Candidates.Length == 0) * { * Console.WriteLine("No one identified"); * } * else * { * // Get top 1 among all candidates returned * var candidateId = identifyResult.Candidates[0].PersonId; * var person = await faceServiceClient.GetPersonAsync(personGroupId, candidateId); * Console.WriteLine("Identified as {0}", person.Name); * } * } * } * * * } */ private async void button_MouseDoubleClick(object sender, MouseButtonEventArgs e) { var openDlg = new Microsoft.Win32.OpenFileDialog(); openDlg.Filter = "JPEG Image(*.jpg)|*.jpg"; bool?result = openDlg.ShowDialog(this); if (!(bool)result) { return; } string filePath = openDlg.FileName; Uri fileUri = new Uri(filePath); BitmapImage bitmapSource = new BitmapImage(); bitmapSource.BeginInit(); bitmapSource.CacheOption = BitmapCacheOption.None; bitmapSource.UriSource = fileUri; bitmapSource.EndInit(); FacePhoto.Source = bitmapSource; Title = "Detecting..."; FaceRectangle[] faceRects = await UploadAndDetectFaces(filePath); Title = String.Format("Detection Finished. {0} face(s) detected", faceRects.Length); if (faceRects.Length > 0) { DrawingVisual visual = new DrawingVisual(); DrawingContext drawingContext = visual.RenderOpen(); drawingContext.DrawImage(bitmapSource, new Rect(0, 0, bitmapSource.Width, bitmapSource.Height)); double dpi = bitmapSource.DpiX; double resizeFactor = 96 / dpi; foreach (var faceRect in faceRects) { drawingContext.DrawRectangle( Brushes.Transparent, new Pen(Brushes.Red, 2), new Rect( faceRect.Left * resizeFactor, faceRect.Top * resizeFactor, faceRect.Width * resizeFactor, faceRect.Height * resizeFactor ) ); } drawingContext.Close(); RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap( (int)(bitmapSource.PixelWidth * resizeFactor), (int)(bitmapSource.PixelHeight * resizeFactor), 96, 96, PixelFormats.Pbgra32); faceWithRectBitmap.Render(visual); FacePhoto.Source = faceWithRectBitmap; } }
private async Task UpdateMergerPreview() { AddImages_Button.IsEnabled = false; RemoveImage_Button.IsEnabled = false; ClearImages_Button.IsEnabled = false; ImagesPerRow_Slider.IsEnabled = false; OpenImage_Button.IsEnabled = false; SaveImage_Button.IsEnabled = false; if ((_imagePath != null && _imagePath.Count > 0) || ImagesListBox.Items.Count > 0) { _imagePath = new List <string>(); for (int i = 0; i < ImagesListBox.Items.Count; ++i) { _imagePath.Add(((ListBoxItem)ImagesListBox.Items[i]).ContentStringFormat); } } int imageCount = _imagePath.Count; int numperrow = Convert.ToInt32(ImagesPerRow_Slider.Value); await Task.Run(() => { DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext drawingContext = drawingVisual.RenderOpen()) { //INITIALIZATION drawingContext.DrawRectangle(Brushes.Transparent, null, new Rect(new Point(0, 0), new Size(515, 515))); var w = 520 * numperrow; if (imageCount * 520 < 520 * numperrow) { w = imageCount * 520; } int h = int.Parse(Math.Ceiling(double.Parse(imageCount.ToString()) / numperrow).ToString(CultureInfo.InvariantCulture)) * 520; int num = 1; int curW = 0; int curH = 0; int maxHeight = 0; for (int i = 0; i < imageCount; i++) { int percentage = (i + 1) * 100 / imageCount; BitmapImage source = new BitmapImage(new Uri(_imagePath[i])); source.DecodePixelWidth = 515; double width = source.Width; double height = source.Height; if (height > maxHeight) { maxHeight = Convert.ToInt32(height); } drawingContext.DrawImage(source, new Rect(new Point(curW, curH), new Size(width, height))); if (num % numperrow == 0) { curW = 0; curH += maxHeight + 5; num += 1; maxHeight = 0; //reset max height for each new row } else { curW += Convert.ToInt32(width) + 5; num += 1; } } } if (drawingVisual != null) { RenderTargetBitmap RTB = new RenderTargetBitmap((int)Math.Floor(drawingVisual.DescendantBounds.Width), (int)Math.Floor(drawingVisual.DescendantBounds.Height), 96, 96, PixelFormats.Pbgra32); RTB.Render(drawingVisual); RTB.Freeze(); //We freeze to apply the RTB to our imagesource from the UI Thread this.Dispatcher.InvokeAsync(() => { MergerPreview_Image.Source = BitmapFrame.Create(RTB); //thread safe and fast af }); } }).ContinueWith(TheTask => { TasksUtility.TaskCompleted(TheTask.Exception); }); GC.Collect(); GC.WaitForPendingFinalizers(); AddImages_Button.IsEnabled = true; RemoveImage_Button.IsEnabled = true; ClearImages_Button.IsEnabled = true; ImagesPerRow_Slider.IsEnabled = true; OpenImage_Button.IsEnabled = true; SaveImage_Button.IsEnabled = true; }
private bool SaveImageFile(Drawing drawing, string fileName, string imageFileName) { string outputExt = this.GetImageFileExtention(); string outputFileName = null; if (String.IsNullOrEmpty(imageFileName)) { string fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName); string workingDir = Path.GetDirectoryName(fileName); outputFileName = Path.Combine(workingDir, fileNameWithoutExt + outputExt); } else { string fileExt = Path.GetExtension(imageFileName); if (String.IsNullOrEmpty(fileExt)) { outputFileName = imageFileName + outputExt; } else if (!String.Equals(fileExt, outputExt, StringComparison.OrdinalIgnoreCase)) { outputFileName = Path.ChangeExtension(imageFileName, outputExt); } else { outputFileName = imageFileName; } } string outputFileDir = Path.GetDirectoryName(outputFileName); if (!Directory.Exists(outputFileDir)) { Directory.CreateDirectory(outputFileDir); } BitmapEncoder bitampEncoder = this.GetBitmapEncoder(outputExt); // The image parameters... Rect drawingBounds = drawing.Bounds; int pixelWidth = (int)drawingBounds.Width; int pixelHeight = (int)drawingBounds.Height; double dpiX = 96; double dpiY = 96; // The Visual to use as the source of the RenderTargetBitmap. DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); drawingContext.DrawDrawing(drawing); drawingContext.Close(); // The BitmapSource that is rendered with a Visual. RenderTargetBitmap targetBitmap = new RenderTargetBitmap( pixelWidth, pixelHeight, dpiX, dpiY, PixelFormats.Pbgra32); targetBitmap.Render(drawingVisual); // Encoding the RenderBitmapTarget as an image file. bitampEncoder.Frames.Add(BitmapFrame.Create(targetBitmap)); using (FileStream stream = File.Create(outputFileName)) { bitampEncoder.Save(stream); } return(true); }
/// <summary> /// Exporting png pictures /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void TakeScreenShotButton_Click(object sender, RoutedEventArgs e) { string path = (DataContext as ColorbarViewModel).AppConfiguration.ScreenshotDirectory; var filename = string.Empty; try { if (path.Contains(@"MyDocuments\CapFrameX\Screenshots")) { var documentFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); path = Path.Combine(documentFolder, @"CapFrameX\Screenshots"); } filename = Path.Combine(path, "Screenshot" + "_" + DateTime.Now.ToString("yyyy-dd-M_HH-mm-ss") + "_CX_Analysis.png"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } var screenShotArea = (DataContext as ColorbarViewModel).Shell.GlobalScreenshotArea; if (screenShotArea == null) { return; } VisualBrush visualBrush = new VisualBrush(screenShotArea); // Gets the size of the images (I assume each image has the same size) int imageWidth = (int)screenShotArea.ActualWidth; int imageHeight = (int)screenShotArea.ActualHeight; // Draws the images into a DrawingVisual component DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext drawingContext = drawingVisual.RenderOpen()) { drawingContext.DrawRectangle(visualBrush, null, new Rect(new System.Windows.Point(0, 0), new System.Windows.Point(imageWidth, imageHeight))); } // Converts the Visual (DrawingVisual) into a BitmapSource RenderTargetBitmap rtb = new RenderTargetBitmap( imageWidth, imageHeight, 96, 96, PixelFormats.Pbgra32); rtb.Render(drawingVisual); using (MemoryStream stream = new MemoryStream()) { BitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(rtb)); encoder.Save(stream); Bitmap bitmap = new Bitmap(stream); System.Drawing.Image logoName = (System.Drawing.Image)Properties.Resources.ResourceManager.GetObject("CX_Screen_Logo_Name"); System.Drawing.Image logoDescription = (System.Drawing.Image)Properties.Resources.ResourceManager.GetObject("CX_Screen_Logo_Description"); // Add fill rectangle AddFillRectangle(bitmap, new System.Drawing.Point(0, imageHeight - logoDescription.Height), new System.Drawing.Size(imageWidth, logoDescription.Height), new SolidBrush(System.Drawing.Color.FromArgb(255, 32, 141, 228))); // Add frame AddRectangle(bitmap, new System.Drawing.Point(1, 1), new System.Drawing.Size(imageWidth - 2, imageHeight), new SolidBrush(System.Drawing.Color.FromArgb(255, 32, 141, 228))); // Add CX logos AddLogo(bitmap, logoName, new System.Drawing.Point(0, imageHeight - logoName.Height)); AddLogo(bitmap, logoDescription, new System.Drawing.Point(imageWidth - logoDescription.Width, imageHeight - logoDescription.Height)); bitmap.Save(filename); } } catch (Exception ex) { var logger = (DataContext as ColorbarViewModel).Logger; logger.LogError(ex, "Screenshot {filename} could not be created", filename); } }
private DrawingVisual CreateDrawingVisualPlot() { //const double dashTickLength = 10; const double marginX = 10; const double marginY = 10; double xmin = marginX; double xmax = rectBounds.Width - marginX; //double ymin = marginY; double ymax = rectBounds.Height - marginY; double step = Math.Round((xmax - xmin) / (24 * 6)); double dotsPerSecond = (xmax - xmin) / SecondsInADay; int intSecondsPerDot = (int)(SecondsInADay / (xmax - xmin)); double dotsPerVolt = 100 * step / 100; DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); Pen pen = new Pen(Brushes.Blue, 1.0); int numSec = 0; short intAssembled; double realValueOfFunction; double peakAtInterval = Int32.MinValue; //максимальное значение функции на интервале double bottomAtInterval = Int32.MaxValue; //минимальное значение функции на интервале Point begPoint = new Point(xmin, ymax); Point endPoint = new Point(xmin, ymax); for ( int iParam = (int)parameterName / (Constants.ParameterData[(int)(parameterName)].parameterType == ParameterType.аналоговый ? 1:10) + (int)Globals.startOfParameterOutput.TotalSeconds * Constants.ParamsBlockLengthInBytes; iParam < this.unpackedParameters.inflatedParameters.Length; iParam = iParam + Constants.ParamsBlockLengthInBytes) { if (Constants.ParameterData[(int)(parameterName)].parameterType == ParameterType.аналоговый) { intAssembled = BitConverter.ToInt16(unpackedParameters.inflatedParameters, iParam); realValueOfFunction = (double)intAssembled / 10; } else { throw new Exception(); } if (peakAtInterval < realValueOfFunction) { peakAtInterval = realValueOfFunction; } if (bottomAtInterval > realValueOfFunction) { bottomAtInterval = realValueOfFunction; } if (numSec % intSecondsPerDot == 0) { //отмечать в графике МАКСИМАЛЬЕОЕ значение на интервале //но надо отмечать и МИНИМАЛЬНОЕ ! // points.Add( new Point(xmin +(numSec)*dotsPerSecond,ymax - dotsPerVolt*peakAtInterval)); //points.Add( new Point(xmin +(numSec)*dotsPerSecond,ymax - dotsPerVolt*bottomAtInterval)); //endPoint = new Point(xmin +(numSec)*dotsPerSecond,ymax - dotsPerVolt*peakAtInterval); //drawingContext.DrawLine(pen,begPoint,endPoint); endPoint = new Point(xmin + (numSec) * dotsPerSecond, ymax - dotsPerVolt * (bottomAtInterval + peakAtInterval) / 2); drawingContext.DrawLine(pen, begPoint, endPoint); begPoint = new Point(xmin + (numSec) * dotsPerSecond, ymax - dotsPerVolt * bottomAtInterval); endPoint = new Point(xmin + (numSec) * dotsPerSecond, ymax - dotsPerVolt * peakAtInterval); drawingContext.DrawLine(pen, begPoint, endPoint); begPoint = new Point((begPoint.X + endPoint.X) / 2, (begPoint.Y + endPoint.Y) / 2); peakAtInterval = 0; bottomAtInterval = Int32.MaxValue; } numSec++; //if(numSec>15000)break; } drawingContext.Close(); return(drawingVisual); }
private void RenderMosaicImage(BitmapSource source) { var panelSize = CellSize * Columns + SeparationSize * Columns; if (source.Width < panelSize || source.Height < panelSize) { throw new Exception(string.Format("Image too small for aberration inspector. Must be at least {0}x{0}", panelSize)); } var widthOffset = (source.Width - Columns * CellSize) / (Columns - 1); var heightOffset = (source.Height - Columns * CellSize) / (Columns - 1); DrawingVisual drawingVisual = new DrawingVisual(); var pen = new Pen() { Brush = Brushes.Black, Thickness = SeparationSize }; using (DrawingContext drawingContext = drawingVisual.RenderOpen()) { for (int column = 0; column < Columns; column++) { for (int row = 0; row < Columns; row++) { var rect = new Int32Rect( (int)(column * widthOffset + column * CellSize), (int)(row * heightOffset + row * CellSize), CellSize, CellSize ); var crop = new WriteableBitmap(new CroppedBitmap(source, rect)); var panelRectangle = new System.Windows.Rect( column * CellSize + column * SeparationSize, row * CellSize + row * SeparationSize, CellSize, CellSize ); drawingContext.DrawImage( crop, panelRectangle ); if (column < Columns - 1) { //Vertical Line drawingContext.DrawLine( pen, new Point( panelRectangle.X + CellSize + SeparationSize / 2d, panelRectangle.Y ), new Point( panelRectangle.X + CellSize + SeparationSize / 2d, panelRectangle.Y + CellSize ) ); } if (row < Columns - 1) { //Horizontal Line drawingContext.DrawLine( pen, new Point( panelRectangle.X, panelRectangle.Y + CellSize + SeparationSize / 2d ), new Point( panelRectangle.X + CellSize, panelRectangle.Y + CellSize + SeparationSize / 2d ) ); } } } } RenderTargetBitmap bmp = new RenderTargetBitmap(panelSize, panelSize, 96, 96, PixelFormats.Pbgra32); bmp.Render(drawingVisual); bmp.Freeze(); this.MosaicImage = bmp; }
/// <summary> /// Creates an arrow drawing. /// </summary> /// <param name="selected">Sets whether the arrow should be highlighted.</param> /// <returns></returns> private DrawingVisual CreateArrowVisual(bool selected) { // Start drawing DrawingVisual drawing = new DrawingVisual(); DrawingContext drawingContext = drawing.RenderOpen(); // Derive style by branch type Brush brush = Brushes.Gray; Pen linePen = new Pen(Brushes.Gray, 2); if (TraceFileEntry.BranchType == BranchTypes.Call) { // Solid blue line if (TraceFileId == 1) { brush = Brushes.Blue; linePen = new Pen(Brushes.Blue, 2); } else if (TraceFileId == 2) { brush = Brushes.Firebrick; linePen = new Pen(Brushes.Firebrick, 2); } } else if (TraceFileEntry.BranchType == BranchTypes.Ret) { // Dashed blue line if (TraceFileId == 1) { brush = Brushes.Blue; linePen = new Pen(Brushes.Blue, 2) { DashStyle = DashStyles.Dash }; } else if (TraceFileId == 2) { brush = Brushes.Firebrick; linePen = new Pen(Brushes.Firebrick, 2) { DashStyle = DashStyles.Dash }; } } else // Jump { // Solid red line if (TraceFileId == 1) { brush = Brushes.RoyalBlue; linePen = new Pen(Brushes.RoyalBlue, 2); } else if (TraceFileId == 2) { brush = Brushes.Red; linePen = new Pen(Brushes.Red, 2); } } // Highlight? if (selected) { linePen.Thickness = 4; } // Draw arrows for non-function internal branches, else boxes if (From != To) { // Prepare arrow head Point arrowTipPosition = new Point(To.CenterXPosition - From.CenterXPosition, ArrowTipSideLength / 2); Point p1 = new Point(arrowTipPosition.X > 0 ? arrowTipPosition.X - ArrowTipSideLength : arrowTipPosition.X + ArrowTipSideLength, arrowTipPosition.Y - ArrowTipSideLength / 2); Point p2 = new Point(arrowTipPosition.X > 0 ? arrowTipPosition.X - ArrowTipSideLength : arrowTipPosition.X + ArrowTipSideLength, arrowTipPosition.Y + ArrowTipSideLength / 2); Point p3 = new Point(arrowTipPosition.X, arrowTipPosition.Y); StreamGeometry arrowTip = new StreamGeometry(); using (StreamGeometryContext geometryContext = arrowTip.Open()) { geometryContext.BeginFigure(p1, true, true); geometryContext.PolyLineTo(new PointCollection { p2, p3 }, true, true); } arrowTip.Freeze(); // Draw arrow (line is slightly shorter that needed, to prevent it from distorting the arrow tip) double lineLength = To.CenterXPosition - From.CenterXPosition + (arrowTipPosition.X > 0 ? -ArrowTipSideLength / 2 : ArrowTipSideLength / 2); drawingContext.DrawLine(linePen, new Point(0, ArrowTipSideLength / 2), new Point(lineLength, ArrowTipSideLength / 2)); drawingContext.DrawGeometry(brush, new Pen(brush, 1), arrowTip); } else { // Draw filled rectangle drawingContext.DrawRectangle(brush, linePen, new Rect(-ArrowTipSideLength, 0, 2 * ArrowTipSideLength, ArrowTipSideLength)); } // Finish drawing drawingContext.Close(); return(drawing); }
/// <summary> /// Créer un mappage des caractères sous forme d'image pour la police et taille donnée /// </summary> /// <param name="typeface"></param> /// <param name="width"></param> /// <param name="height"></param> /// <returns></returns> private static CharacterMapEntry[] GetCharactersMap(Typeface typeface, int width, int height) { var param = new CacheEntry(typeface, width, height); if (m_fontCache.ContainsKey(param)) { return(m_fontCache[param]); } var result = new CharacterMapEntry[PRINTEABLE_CHARS.Length]; // pour chaque caractère possible ... int i = 0; foreach (var character in PRINTEABLE_CHARS) { double proportion; var visual = new DrawingVisual(); using (DrawingContext drawingContext = visual.RenderOpen()) { // taille usuelle d'un caractère (ex : 12 par défaut sur word) // on fait en sorte de mettre le plus gros caractère dans le cadre donné var size = height * 96.0 / 72.0; var text = new FormattedText(character.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture, FlowDirection.LeftToRight, typeface, size, Brushes.White); var geom = text.BuildGeometry(new Point(0, 0)); // dessine un fond blanc drawingContext.DrawRectangle(Brushes.White, null, new Rect(0, 0, width, height)); // on enleve les contours blancs var translateTransform = new TranslateTransform(); translateTransform.X = -geom.Bounds.Left; translateTransform.Y = -geom.Bounds.Top; proportion = geom.Bounds.Width / geom.Bounds.Height; // applique une homotétie pour adapter le caractère à la taille imposé var scaleTransform = new ScaleTransform(width / geom.Bounds.Width, height / geom.Bounds.Height); drawingContext.PushTransform(scaleTransform); drawingContext.PushTransform(translateTransform); // dessine le caractère en noir avec les transformations précédentes drawingContext.DrawGeometry(Brushes.Black, null, geom); } // dessine le caractère sur une image var resizedImage = new RenderTargetBitmap( width, height, // Resized dimensions 96, 96, // Default DPI values PixelFormats.Default); // Default pixel format resizedImage.Render(visual); var stride = 4 * width; var buffer = new byte[stride * height]; // on récupère les pixels de l'image pour les comparer resizedImage.CopyPixels(buffer, stride, 0); result[i++] = new CharacterMapEntry(character, buffer, proportion); } // pour réduire la mémoire GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); m_fontCache.Add(param, result); return(result); }
//打印 private void btPrint_Click(object sender, RoutedEventArgs e) { Cursor = Cursors.Wait; if (lvList.Items.Count > 0) { Drug[] ds = lvList.ItemsSource as Drug[]; PrintDialog pd = new PrintDialog(); DrawingVisual dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { double space_X = 20; double space_Y = 10; double size_G = 16; double size_L = 14; double wide_Col = 40; //标题 FormattedText title = new FormattedText("加药清单-" + DateTime.Now.ToString(), CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Microsoft YaHei"), size_G, Brushes.Black); dc.DrawText(title, new Point((pd.PrintableAreaWidth - title.Width) / 2, space_Y));//居中 space_Y += title.Height; //横线 dc.DrawLine(new Pen(Brushes.Black, 1), new Point(space_X, space_Y), new Point(pd.PrintableAreaWidth - space_X, space_Y)); //列标题 FormattedText col_1 = new FormattedText("缺药", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Microsoft YaHei"), size_L, Brushes.Black); dc.DrawText(col_1, new Point(space_X + (wide_Col - col_1.Width) / 2, space_Y)); FormattedText col_2 = new FormattedText("名称/规格/厂家", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Microsoft YaHei"), size_L, Brushes.Black); dc.DrawText(col_2, new Point(space_X + wide_Col + 10, space_Y)); //3条竖线 dc.DrawLine(new Pen(Brushes.Black, 1), new Point(space_X, space_Y), new Point(space_X, space_Y + col_2.Height)); dc.DrawLine(new Pen(Brushes.Black, 1), new Point(space_X + wide_Col, space_Y), new Point(space_X + wide_Col, space_Y + col_2.Height)); dc.DrawLine(new Pen(Brushes.Black, 1), new Point(pd.PrintableAreaWidth - space_X, space_Y), new Point(pd.PrintableAreaWidth - space_X, space_Y + col_2.Height)); space_Y += col_2.Height; //横线 dc.DrawLine(new Pen(Brushes.Black, 1), new Point(space_X, space_Y), new Point(pd.PrintableAreaWidth - space_X, space_Y)); //循环 foreach (Drug d in ds) { //名称 FormattedText name = new FormattedText(d.DrugName, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Microsoft YaHei"), size_L, Brushes.Black); dc.DrawText(name, new Point(space_X + wide_Col + 10, space_Y)); dc.DrawLine(new Pen(Brushes.Black, 1), new Point(space_X + wide_Col, space_Y), new Point(pd.PrintableAreaWidth - space_X, space_Y)); //规格 FormattedText spec = new FormattedText(d.DrugSpec, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Microsoft YaHei"), size_L, Brushes.Black); dc.DrawText(spec, new Point(space_X + wide_Col + 10, space_Y + name.Height)); dc.DrawLine(new Pen(Brushes.Black, 1), new Point(space_X + wide_Col, space_Y + name.Height), new Point(pd.PrintableAreaWidth - space_X, space_Y + name.Height)); //厂家 FormattedText fac = new FormattedText(d.DrugFactory, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Microsoft YaHei"), size_L, Brushes.Black); dc.DrawText(fac, new Point(space_X + wide_Col + 10, space_Y + name.Height * 2)); dc.DrawLine(new Pen(Brushes.Black, 1), new Point(space_X + wide_Col, space_Y + name.Height * 2), new Point(pd.PrintableAreaWidth - space_X, space_Y + name.Height * 2)); //缺药 FormattedText num = new FormattedText(d.Short.ToString(), CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Microsoft YaHei"), 30, Brushes.Black); dc.DrawText(num, new Point(space_X + (wide_Col - num.Width) / 2, space_Y + (name.Height * 3 - num.Height) / 2)); //三条竖线 dc.DrawLine(new Pen(Brushes.Black, 1), new Point(space_X, space_Y), new Point(space_X, space_Y + name.Height * 3)); dc.DrawLine(new Pen(Brushes.Black, 1), new Point(space_X + wide_Col, space_Y), new Point(space_X + wide_Col, space_Y + name.Height * 3)); dc.DrawLine(new Pen(Brushes.Black, 1), new Point(pd.PrintableAreaWidth - space_X, space_Y), new Point(pd.PrintableAreaWidth - space_X, space_Y + name.Height * 3)); //横线 dc.DrawLine(new Pen(Brushes.Black, 1), new Point(space_X, space_Y + name.Height * 3), new Point(pd.PrintableAreaWidth - space_X, space_Y + name.Height * 3)); space_Y += name.Height * 3; } //空白 FormattedText n = new FormattedText(".", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Microsoft YaHei"), size_L, Brushes.Black); dc.DrawText(n, new Point(space_X, space_Y + n.Height)); dc.DrawText(n, new Point(space_X, space_Y + n.Height * 2)); } pd.PrintVisual(dv, ""); } Cursor = null; }
private WriteableBitmap DrawChar(int x_offset, Rect rect, TextContext context) { // Create the outline strategy which is going to shift blit diagonally var strategyOutline = TextDesignerWpf.Canvas.TextOutline(MaskColor.Blue, MaskColor.Blue, 4); WriteableBitmap canvas = TextDesignerWpf.Canvas.GenImage((int)(image1.Width), (int)(image1.Height), Colors.White, 0); // the single mask outline WriteableBitmap maskOutline = TextDesignerWpf.Canvas.GenMask(strategyOutline, (int)(image1.Width), (int)(image1.Height), new Point(0, 0), context); // the mask to store all the single mask blitted diagonally WriteableBitmap maskOutlineAll = TextDesignerWpf.Canvas.GenImage((int)(image1.Width) + 10, (int)(image1.Height) + 10); RenderTargetBitmap bmp = new RenderTargetBitmap((int)(maskOutlineAll.Width), (int)(maskOutlineAll.Height), 96, 96, PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); // blit diagonally for (int i = 0; i < 8; ++i) { drawingContext.DrawImage(maskOutline, new Rect((double)(-i), (double)(-i), maskOutline.Width, maskOutline.Height - 0.0)); } drawingContext.Close(); bmp.Render(drawingVisual); maskOutlineAll = new WriteableBitmap(bmp); // Measure the dimension of the big mask in order to generate the correct sized gradient image //============================================================================================= uint top = 0; uint bottom = 0; uint left = 0; uint right = 0; TextDesignerWpf.Canvas.MeasureMaskLength(maskOutlineAll, MaskColor.Blue, ref top, ref left, ref bottom, ref right); right += 2; bottom += 2; // Generate the gradient image for the diagonal outline //======================================================= WriteableBitmap gradImage = TextDesignerWpf.Canvas.GenImage((int)(right - left), (int)(bottom - top)); List <Color> listColors = new List <Color>(); listColors.Add(Colors.Purple); listColors.Add(Colors.MediumPurple); DrawGradient.Draw(ref gradImage, listColors, false); // Because Canvas::ApplyImageToMask requires all image to have same dimensions, // we have to blit our small gradient image onto a temp image as big as the canvas //=================================================================================== WriteableBitmap gradBlitted = TextDesignerWpf.Canvas.GenImage((int)(image1.Width), (int)(image1.Height)); byte[] pixels2 = new byte[gradImage.PixelHeight * gradImage.PixelWidth * gradImage.Format.BitsPerPixel / 8]; gradImage.CopyPixels(pixels2, gradImage.BackBufferStride, 0); gradBlitted.WritePixels(new Int32Rect((int)left, (int)top, (int)(gradImage.Width), (int)(gradImage.Height)), pixels2, gradImage.BackBufferStride, 0); TextDesignerWpf.Canvas.ApplyImageToMask(gradBlitted, maskOutlineAll, canvas, MaskColor.Blue, false); // Create strategy and mask image for the text body //=================================================== var strategyText = TextDesignerWpf.Canvas.TextNoOutline(MaskColor.Blue); WriteableBitmap maskText = TextDesignerWpf.Canvas.GenMask(strategyText, (int)(image1.Width), (int)(image1.Height), new Point(0, 0), context); // Measure the dimension required for text body using the mask //============================================================= top = 0; bottom = 0; left = 0; right = 0; TextDesignerWpf.Canvas.MeasureMaskLength(maskText, MaskColor.Blue, ref top, ref left, ref bottom, ref right); top -= 2; left -= 2; right += 2; bottom += 2; GradientStopCollection coll = new GradientStopCollection(); GradientStop stop = new GradientStop(Colors.DeepPink, 0.0); coll.Add(stop); stop = new GradientStop(Colors.LightPink, 1.0); coll.Add(stop); // Create the gradient brush for the text body LinearGradientBrush gradTextbrush = new LinearGradientBrush(coll, 90.0); // Create the actual strategy for the text body used for rendering, with the gradient brush var strategyText2 = TextDesignerWpf.Canvas.TextNoOutline(gradTextbrush); // Draw the newly created strategy onto the canvas TextDesignerWpf.Canvas.DrawTextImage(strategyText2, ref canvas, new Point(0, 0), context); return(canvas); }
public MainWindow() { InitializeComponent(); //WriteableBitmap main_canvas = TextDesignerWpf.Canvas.GenImage((int)(image1.Width), (int)(image1.Height), Colors.White, 0); RenderTargetBitmap main_canvas = new RenderTargetBitmap((int)(image1.Width), (int)(image1.Height), 96, 96, PixelFormats.Pbgra32); // Text context to store string and font info to be sent as parameter to Canvas methods TextContext context = new TextContext(); FontFamily fontFamily = new FontFamily(new Uri("pack://application:,,,/resources/"), "./#Airbus Special"); context.fontFamily = fontFamily; context.fontStyle = FontStyles.Normal; context.fontWeight = FontWeights.Regular; context.nfontSize = 40; context.pszText = ""; context.ptDraw = new Point(8, 12); string text = "PENTHOUSE"; int x_offset = 0; float y_offset = 0.0f; for (int i = 0; i < text.Length; ++i) { string str = ""; str += text[i]; context.pszText = str; WriteableBitmap canvas = DrawChar(x_offset, new Rect(0.0, 0.0, (double)(image1.Width), (double)(image1.Height)), context); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); TranslateTransform trans_mat = new TranslateTransform(0.0f, y_offset); y_offset += 7.3f; drawingContext.PushTransform(trans_mat); ScaleTransform scale_mat = new ScaleTransform(0.75f, 1.0f); drawingContext.PushTransform(scale_mat); RotateTransform rot_mat = new RotateTransform(-9.8f); drawingContext.PushTransform(rot_mat); drawingContext.DrawImage(canvas, new Rect((double)(x_offset), (double)(0.0), image1.Width, image1.Height - 0.0)); drawingContext.Close(); main_canvas.Render(drawingVisual); if (i == 0) { x_offset += 42; } else if (i == 2) { x_offset += 46; } else if (i == 3) { x_offset += 43; } else if (i == 4 || i == 5 || i == 6) { x_offset += 46; } else { x_offset += 41; } } // Finally blit the rendered image onto the window by assigning canvas to the image control image1.Source = main_canvas; }
protected override RequestedAction BuildJob(ImageJob job) { if (!"wpf".Equals(job.Settings["builder"])) { return(RequestedAction.None); } // Estrazione delle ResizeSettings ResizeSettings settings = job.Settings; Stream s = null; bool disposeStream = !(job.Source is Stream); long originalPosition = 0; bool restoreStreamPosition = false; string path; s = c.CurrentImageBuilder.GetStreamFromSource(job.Source, job.Settings, ref disposeStream, out path, out restoreStreamPosition); if (s == null) { return(RequestedAction.None); //We don't support the source object! } if (job.ResetSourceStream) { restoreStreamPosition = true; } job.SourcePathData = path; // Instanzio uno stream locale per le operazioni WPF using (MemoryStream localStream = (s is MemoryStream) ? (MemoryStream)s : StreamExtensions.CopyToMemoryStream(s)) { if (s != null && restoreStreamPosition && s.CanSeek) { s.Seek(originalPosition, SeekOrigin.Begin); } if (disposeStream) { s.Dispose(); } /* ? ? ? */ IEncoder managedEncoder = c.Plugins.GetEncoder(job.Settings, job.SourcePathData); bool supportsTransparency = managedEncoder.SupportsTransparency; // Recupero le dimensioni originali var frame = BitmapFrame.Create(StreamExtensions.CopyToMemoryStream(localStream)); System.Windows.Size originalSize = new System.Windows.Size(frame.PixelWidth, frame.PixelHeight); // Resetto lo stream locale alla posizione iniziale, dopo aver letto i metadata localStream.Position = 0; // Uhm... sono costretto a referenziare le System.Drawing (GDI) per questo, // TODO: chiedere al tipo se si può prevedere un costruttore di ImageState che non preveda un System.Drawing.Size come parametro System.Drawing.Size orig = new System.Drawing.Size((int)originalSize.Width, (int)originalSize.Height); using (ImageState imageState = new ImageState(settings, orig, true)) { c.CurrentImageBuilder.Process(imageState); Rectangle imageDest = PolygonMath.ToRectangle(PolygonMath.GetBoundingBox(imageState.layout["image"])); BitmapSource finalImage; BitmapImage bi = new BitmapImage(); bi.CacheOption = BitmapCacheOption.OnLoad; bi.BeginInit(); bi.StreamSource = localStream; WpfImageSettings wpfImageSettings = imageState.WpfDestinationImageSettings(settings); bi.DecodePixelWidth = Convert.ToInt32(wpfImageSettings.DestinationImageWidth); bi.DecodePixelHeight = Convert.ToInt32(wpfImageSettings.DestinationImageHeight); bi.EndInit(); // Creation of the encoder WpfEncoderPlugin wpfEncoder = new WpfEncoderPlugin(settings, job.SourcePathData); RenderTargetBitmap final = new RenderTargetBitmap(imageState.finalSize.Width, imageState.finalSize.Height, settings.Get <int>("dpi", 96), settings.Get <int>("dpi", 96), PixelFormats.Default); DrawingVisual dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { string ARGBBackgroundColor = String.Format("#{0:X2}{1:X2}{2:X2}{3:X2}", wpfEncoder.MimeType.Equals("image/jpeg") ? 255 : settings.BackgroundColor.A, settings.BackgroundColor.R, settings.BackgroundColor.G, settings.BackgroundColor.B); System.Windows.Media.Brush BrushBackgroundColor = new System.Windows.Media.SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(ARGBBackgroundColor)); /* todo: verificare */ dc.DrawRectangle(BrushBackgroundColor, null, new Rect(0, 0, wpfImageSettings.DestinationImageWidth, wpfImageSettings.DestinationImageHeight)); Rect rect = new Rect(wpfImageSettings.OffsetX, wpfImageSettings.OffsetY, wpfImageSettings.DestinationImageWidth, wpfImageSettings.DestinationImageHeight); //dc.PushTransform(new RotateTransform(settings.Rotate, (double)imageState.finalSize.Width / 2, (double)imageState.finalSize.Height / 2)); dc.DrawImage(bi, rect); } final.Render(dv); finalImage = final; // Write the image to the output stream wpfEncoder.Write(finalImage, (Stream)job.Dest); } } return(RequestedAction.None); }
private DrawingVisual DrawMapLayerByTiles(Map aMap, int aLayerNumber) { DrawingVisual _visual = new DrawingVisual(); using (DrawingContext _context = _visual.RenderOpen()) { for (int i = 0; i < aMap.WORLD_SIZE; i++) { for (int j = 0; j < aMap.WORLD_SIZE; j++) { if (i + j > 3 * aMap.WORLD_SIZE / 2 || i + j < aMap.WORLD_SIZE / 2 || i - j > aMap.WORLD_SIZE / 2 || i - j < -aMap.WORLD_SIZE / 2) { continue; } MapElement _element = aMap.Elementes[aMap.WORLD_SIZE * j + i]; LevelNode.TileIndex[] _indexes = _element.pLevelNodes[aLayerNumber].tileIndexes; for (int _index = 0; _index < _indexes.Length; _index++) { if (_indexes.Length > _index) { LevelNode.TileIndex _tileIndex = _indexes[_index]; int _subIndex = _tileIndex.usTypeSubIndex - 1; if (aMap.MapTileSet.Length > _tileIndex.ubType) { StciIndexed _sti = aMap.MapTileSet[_tileIndex.ubType].Sti; if (_sti != null && _sti.Images.Length > _subIndex) { List <Color> _palette = _sti.ColorPalette .Select(z => new Color() { A = 255, R = z.Red, G = z.Green, B = z.Blue }) .ToList(); StciSubImage _subImage = _sti.Images[_subIndex]; StructureImage _image = new StructureImage(_subImage, _palette); int _x = (i - j) * StructureImage.TileWidth + _subImage.Header.OffsetX; int _y = (i + j) * StructureImage.TileHeight + _subImage.Header.OffsetY; // Надо поднимать всё кроме клифов. Как пока не понятно. //if (aLayerNumber == 1 && _element.sHeight > 0) //{ // int _heigthLevel = _element.sHeight % 256; // int _heigth = _element.sHeight / 256; // _y -= _heigthLevel + _heigth; //} if (aLayerNumber > 3) // крыша { _y -= 50; } Point point = new Point( _x + aMap.WORLD_SIZE * StructureImage.TileWidth / 2, _y - aMap.WORLD_SIZE * StructureImage.TileHeight / 2 ); Rect _rect = new Rect( point, new Size(_subImage.Header.Width, _subImage.Header.Height)); _context.DrawImage(_image.Bitmap, _rect); this.FDrewElementsCount++; this.FProgress.Progress = FDrewElementsCount * 100 / this.FTotalElementsCount; } } } } } } } return(_visual); }
public override DocumentPage GetPage(int pageNumber) { DocumentPage page = m_Paginator.GetPage(pageNumber); // Create a wrapper visual for transformation and add extras ContainerVisual newpage = new ContainerVisual(); DrawingVisual title = new DrawingVisual(); using (DrawingContext ctx = title.RenderOpen()) { if (m_Typeface == null) { m_Typeface = new Typeface("Times New Roman"); } FormattedText text = new FormattedText("Page " + (pageNumber + 1), System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, m_Typeface, 14, Brushes.Black); // ctx.DrawText(text, new Point(0, -96 / 4)); // 1/4 inch above page content } DrawingVisual background = new DrawingVisual(); using (DrawingContext ctx = background.RenderOpen()) { // ctx.DrawRectangle(new SolidColorBrush(Color.FromRgb(240, 240, 240)), null, page.ContentBox); } newpage.Children.Add(background); // Scale down page and center ContainerVisual smallerPage = new ContainerVisual(); smallerPage.Children.Add(page.Visual); smallerPage.Transform = new MatrixTransform(0.95, 0, 0, 0.95, 0.025 * page.ContentBox.Width, 0.025 * page.ContentBox.Height); newpage.Children.Add(smallerPage); newpage.Children.Add(title); newpage.Transform = new TranslateTransform(m_Margin.Width, m_Margin.Height); return(new DocumentPage(newpage, m_PageSize, Move(page.BleedBox), Move(page.ContentBox))); }
private void Draw(DrawingGroup group, DrawingGroup main) { DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); _offsetX = 0; _offsetY = 0; _displayTransform = Transform.Identity; TranslateTransform offsetTransform = null; Rect rectBounds = group.Bounds; if (!rectBounds.IsEmpty) { // Return the new size //double diaWidth = rectBounds.Width; if (rectBounds.X > 0) { //diaWidth += rectBounds.X; _offsetX = rectBounds.X; } //double diaHeight = rectBounds.Height; if (rectBounds.Y > 0) { //diaHeight += rectBounds.Y; _offsetY = rectBounds.Y; } _bounds = rectBounds; if (_offsetX > 0 || _offsetY > 0) { offsetTransform = new TranslateTransform(-_offsetX, -_offsetY); _displayTransform = new TranslateTransform(_offsetX, _offsetY); // the inverse... } } //Canvas.SetTop(this, -_offsetX); //Canvas.SetLeft(this, -_offsetY); //if (offsetTransform != null) //{ // drawingContext.PushTransform(offsetTransform); //} drawingContext.DrawDrawing(group); //if (offsetTransform != null) //{ // drawingContext.Pop(); //} drawingVisual.Opacity = group.Opacity; //Transform transform = group.Transform; //if (transform == null) //{ // transform = offsetTransform; //} if (offsetTransform != null) { drawingVisual.Transform = offsetTransform; } Geometry clipGeometry = group.ClipGeometry; if (clipGeometry != null) { drawingVisual.Clip = clipGeometry; } drawingContext.Close(); this.AddVisual(drawingVisual); if (_drawForInteractivity) { if (main == null) { main = group; } this.EnumerateDrawings(main); } }
private void InvokeUpdateKeyboardPreview(object sender, ElapsedEventArgs e) { if (_blurProgress > 2) { _blurProgress = 0; } _blurProgress = _blurProgress + 0.025; BlurRadius = (Math.Sin(_blurProgress * Math.PI) + 1) * 10 + 10; if (SelectedProfile == null || _deviceManager.ActiveKeyboard == null) { var preview = new DrawingImage(); preview.Freeze(); KeyboardPreview = preview; return; } var keyboardRect = _deviceManager.ActiveKeyboard.KeyboardRectangle(4); var visual = new DrawingVisual(); using (var drawingContext = visual.RenderOpen()) { // Setup the DrawingVisual's size drawingContext.PushClip(new RectangleGeometry(keyboardRect)); drawingContext.DrawRectangle(new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)), null, keyboardRect); // Draw the layers var drawLayers = SelectedProfile.GetRenderLayers <ProfilePreviewDataModel>( new ProfilePreviewDataModel(), false, false, true); foreach (var layer in drawLayers) { layer.Draw(null, drawingContext, true, false); } // Get the selection color var accentColor = ThemeManager.DetectAppStyle(Application.Current)?.Item2?.Resources["AccentColor"]; if (accentColor == null) { return; } var pen = new Pen(new SolidColorBrush((Color)accentColor), 0.4); // Draw the selection outline and resize indicator if (SelectedLayer != null && SelectedLayer.MustDraw()) { var layerRect = ((KeyboardPropertiesModel)SelectedLayer.Properties).GetRect(); // Deflate the rect so that the border is drawn on the inside layerRect.Inflate(-0.2, -0.2); // Draw an outline around the selected layer drawingContext.DrawRectangle(null, pen, layerRect); // Draw a resize indicator in the bottom-right drawingContext.DrawLine(pen, new Point(layerRect.BottomRight.X - 1, layerRect.BottomRight.Y - 0.5), new Point(layerRect.BottomRight.X - 1.2, layerRect.BottomRight.Y - 0.7)); drawingContext.DrawLine(pen, new Point(layerRect.BottomRight.X - 0.5, layerRect.BottomRight.Y - 1), new Point(layerRect.BottomRight.X - 0.7, layerRect.BottomRight.Y - 1.2)); drawingContext.DrawLine(pen, new Point(layerRect.BottomRight.X - 0.5, layerRect.BottomRight.Y - 0.5), new Point(layerRect.BottomRight.X - 0.7, layerRect.BottomRight.Y - 0.7)); } // Remove the clip drawingContext.Pop(); } var drawnPreview = new DrawingImage(visual.Drawing); drawnPreview.Freeze(); KeyboardPreview = drawnPreview; }
protected override void OnRender(DrawingContext drawingContext) { var textformat = new FormattedText( string.IsNullOrEmpty(Text) ? "" : Text, CultureInfo.CurrentCulture, FlowDirection, Typeface, FontSize, Foreground); if (SelectionAreas == null || SelectionAreas.Count == 0) { drawingContext.DrawText(textformat, new Point(0, 0)); return; } var chunks = new Dictionary <FormattedText, bool>(); var startPosition = 0; foreach (var selectionArea in SelectionAreas) { var selection = Text.Substring(selectionArea.Start, selectionArea.Length); var textBefore = Text.Substring(startPosition, Math.Abs(selectionArea.Start - startPosition)); startPosition = selectionArea.Start + selectionArea.Length; var formatTextBefore = new FormattedText(textBefore, CultureInfo.CurrentCulture, FlowDirection, Typeface, FontSize, Foreground); var formatTextSelect = new FormattedText(selection, CultureInfo.CurrentCulture, FlowDirection, Typeface, FontSize, StyleSelection == StyleSelection.Rectangle ? Brushes.White : Foreground); chunks.Add(formatTextBefore, false); chunks.Add(formatTextSelect, true); } var textAfter = Text.Substring(startPosition); var formatTextAfter = new FormattedText(textAfter, CultureInfo.CurrentCulture, FlowDirection, Typeface, FontSize, Foreground); chunks.Add(formatTextAfter, false); var startPoint = new Point(Padding.Left, Padding.Top); foreach (var chunk in chunks) { if (!chunk.Value) { drawingContext.DrawText(chunk.Key, startPoint); } else { switch (StyleSelection) { case StyleSelection.Rectangle: var visualRect = new DrawingVisual(); visualRect.SetValue(UseLayoutRoundingProperty, true); visualRect.SetValue(SnapsToDevicePixelsProperty, true); visualRect.SetValue(RenderOptions.EdgeModeProperty, EdgeMode.Aliased); using (var context = visualRect.RenderOpen()) { context.DrawRectangle(Brushes.Black, null, new Rect(startPoint, new Size(chunk.Key.WidthIncludingTrailingWhitespace, chunk.Key.Height))); } drawingContext.DrawRectangle(new VisualBrush(visualRect), null, visualRect.ContentBounds); drawingContext.DrawText(chunk.Key, startPoint); break; case StyleSelection.Underline: var startPointLine = new Point(startPoint.X, textformat.Height - .5); var endPointLine = new Point( startPoint.X + chunk.Key.WidthIncludingTrailingWhitespace, textformat.Height - .5); var visual = new DrawingVisual(); visual.SetValue(UseLayoutRoundingProperty, true); visual.SetValue(SnapsToDevicePixelsProperty, true); visual.SetValue(RenderOptions.EdgeModeProperty, EdgeMode.Unspecified); using (var context = visual.RenderOpen()) { context.DrawLine(new Pen(Brushes.Black, 1), startPointLine, endPointLine); } drawingContext.DrawRectangle(new VisualBrush(visual), null, visual.ContentBounds); drawingContext.DrawText(chunk.Key, startPoint); break; default: throw new ArgumentOutOfRangeException(); } } startPoint.X += chunk.Key.WidthIncludingTrailingWhitespace; } drawingContext.DrawRectangle(Brushes.Transparent, null, new Rect(new Point(0, 0), new Size(textformat.WidthIncludingTrailingWhitespace, textformat.Height))); base.OnRender(drawingContext); }
private DrawingVisual CreateDrawingVisualPlot() { const double dashTickLength = 10; double xmin = rectBounds.X; double xmax = rectBounds.Width; double ymin = rectBounds.X; double ymax = rectBounds.Height; double LowerLimitForCurrentOnYAxis = 0; double UpperLimitForCurrentOnYAxis = Convert.ToDouble(scull_Furnaces_Main_Window.maxValueForCurrentOnYAxis.Text); double LowerLimitForTimeOnXAxis = Int32.Parse(scull_Furnaces_Main_Window.begTimeOnXAxis.Ticks.Text); double UpperLimitForTimeOnXAxis = Int32.Parse(scull_Furnaces_Main_Window.endTimeOnXAxis.Ticks.Text); WriteLine("LowerLimitForTimeOnXAxis = {0}", LowerLimitForTimeOnXAxis); WriteLine("UpperLimitForTimeOnXAxis = {0}", UpperLimitForTimeOnXAxis); double step = Math.Round((xmax - xmin) / (24 * 6)); PrepareTransformations ( LowerLimitForTimeOnXAxis, UpperLimitForTimeOnXAxis, LowerLimitForCurrentOnYAxis, UpperLimitForCurrentOnYAxis, xmin, xmax, ymin, ymax ); string unitOfMeasure; // double dotsPerSecond = (xmax - xmin)/SecondsInADay; // int intSecondsPerDot = (int)(SecondsInADay/(xmax - xmin)); double dotsPerSecond = (xmax - xmin) / (UpperLimitForTimeOnXAxis - LowerLimitForTimeOnXAxis); int intSecondsPerDot = (int)((UpperLimitForTimeOnXAxis - LowerLimitForCurrentOnYAxis) / (xmax - xmin)); double dotsPerVolt = UpperLimitForCurrentOnYAxis * step / UpperLimitForCurrentOnYAxis; dotsPerVolt = (ymax - ymin) / (UpperLimitForCurrentOnYAxis - LowerLimitForCurrentOnYAxis); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); Pen pen = new Pen(Brushes.Blue, 1.0); int numSec = 0; short intAssembled; double realValueOfFunction; double peakAtInterval = Int32.MinValue; //максимальное значение функции на интервале double bottomAtInterval = Int32.MaxValue; //минимальное значение функции на интервале Point begPoint = WtoD(new Point(xmin, ymax)); //What should be put here?! Point endPoint; // = WtoD(new Point(xmin,ymax)); WriteLine("LowerLimitForCurrentOnYAxis = {0}", LowerLimitForCurrentOnYAxis); int iParam; for ( int currSec = (int)LowerLimitForCurrentOnYAxis; currSec < (UpperLimitForTimeOnXAxis - LowerLimitForCurrentOnYAxis); currSec++ ) { iParam = (int)parameterName + currSec * Constants.ParamsBlockLengthInBytes; if (Constants.ParameterData[(int)(parameterName)].parameterType == ParameterType.аналоговый) { intAssembled = BitConverter.ToInt16(unpackedParameters.inflatedParameters, iParam); realValueOfFunction = (double)intAssembled / 10; switch (Constants.ParameterData[(int)(parameterName)].parameterUnit) { case ParameterUnit._: unitOfMeasure = ""; break; case ParameterUnit.м3_ч: unitOfMeasure = "м3/ч"; break; case ParameterUnit.мм_рт_ст: if (intAssembled < 0) { unitOfMeasure = "мм рт.ст"; intAssembled &= 0x777; } else { unitOfMeasure = "мк"; } break; } } else { throw new Exception(); } //* if (peakAtInterval < realValueOfFunction) { peakAtInterval = realValueOfFunction; } if (bottomAtInterval > realValueOfFunction) { bottomAtInterval = realValueOfFunction; } if (numSec % intSecondsPerDot == 0) //intSecondsPerDot обращается в 0! { //отмечать в графике МАКСИМАЛЬЕОЕ значение на интервале //но надо отмечать и МИНИМАЛЬНОЕ ! endPoint = WtoD(new Point(currSec, (bottomAtInterval + peakAtInterval) / 2)); drawingContext.DrawLine(pen, begPoint, endPoint); begPoint = WtoD(new Point(currSec, bottomAtInterval)); endPoint = WtoD(new Point(currSec, peakAtInterval)); drawingContext.DrawLine(pen, begPoint, endPoint); begPoint = new Point((begPoint.X + endPoint.X) / 2, (begPoint.Y + endPoint.Y) / 2); peakAtInterval = 0; bottomAtInterval = Int32.MaxValue; } numSec++; //if(numSec>15000)break; } drawingContext.Close(); return(drawingVisual); }
/// <summary> /// 保存控件为图片格式 /// </summary> /// <param name="control"></param> public static void SaveImage(FrameworkElement control) { //对话框 SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "PNG文件(*.png)|*.png|JPG文件(*.jpg)|*.jpg|BMP文件(*.bmp)|*.bmp|GIF文件(*.gif)|*.gif|TIF文件(*.tif)|*.tif"; if (dialog.ShowDialog() == true) { var fileName = dialog.FileName; //第一步:建立DrawingVisual,将Control转换为DrawingVisual DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext context = drawingVisual.RenderOpen()) { VisualBrush brush = new VisualBrush(control) { Stretch = Stretch.None }; context.DrawRectangle(brush, null, new Rect(0, 0, control.ActualWidth, control.ActualHeight)); context.Close(); } //第二步:建立RenderTargetBitmap,将DrawingVisual转化为RenderTargetBitmap //--获取Dpi-- float dpiX, dpiY; using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromHwnd(IntPtr.Zero)) { dpiX = graphics.DpiX; dpiY = graphics.DpiY; } RenderTargetBitmap bitmap = new RenderTargetBitmap((int)control.ActualWidth + 1, (int)control.ActualHeight + 1, dpiX, dpiY, PixelFormats.Pbgra32); bitmap.Render(drawingVisual); string extensionString = System.IO.Path.GetExtension(fileName); BitmapEncoder encoder = null; switch (extensionString) { case ".jpg": encoder = new JpegBitmapEncoder(); break; case ".png": encoder = new PngBitmapEncoder(); break; case ".bmp": encoder = new BmpBitmapEncoder(); break; case ".gif": encoder = new GifBitmapEncoder(); break; case ".tif": encoder = new TiffBitmapEncoder(); break; default: throw new InvalidOperationException(); } encoder.Frames.Add(BitmapFrame.Create(bitmap)); using (Stream stm = File.Create(fileName)) { encoder.Save(stm); } MessageBox.Show(string.Format("成功保存到{0}!", fileName), "提示", MessageBoxButton.OK, MessageBoxImage.Information); } }
// Formats entire document into pages. void Format() { // Store each line of the document as with LineWithFlag object. List <PrintLine> listLines = new List <PrintLine>(); // Use this for some basic calculations. FormattedText formtxtSample = GetFormattedText("W"); // Width of printed line. double width = PageSize.Width - Margins.Left - Margins.Right; // Serious problem: Abandon ship. if (width < formtxtSample.Width) { return; } string strLine; Pen pn = new Pen(Brushes.Black, 2); StringReader reader = new StringReader(txt); // Call ProcessLine to store each line in listLines. while (null != (strLine = reader.ReadLine())) { ProcessLine(strLine, width, listLines); } reader.Close(); // Now start getting ready to print pages. double heightLine = formtxtSample.LineHeight + formtxtSample.Height; double height = PageSize.Height - Margins.Top - Margins.Bottom; int linesPerPage = (int)(height / heightLine); // Serious problem: Abandon ship. if (linesPerPage < 1) { return; } int numPages = (listLines.Count + linesPerPage - 1) / linesPerPage; double xStart = Margins.Left; double yStart = Margins.Top; // Create the List to store each DocumentPage object. listPages = new List <DocumentPage>(); for (int iPage = 0, iLine = 0; iPage < numPages; iPage++) { // Create the DrawingVisual and open the DrawingContext. DrawingVisual vis = new DrawingVisual(); DrawingContext dc = vis.RenderOpen(); // Display header at top of page. if (Header != null && Header.Length > 0) { FormattedText formtxt = GetFormattedText(Header); formtxt.SetFontWeight(FontWeights.Bold); Point ptText = new Point(xStart, yStart - 2 * formtxt.Height); dc.DrawText(formtxt, ptText); } // Display footer at bottom of page. if (numPages > 1) { FormattedText formtxt = GetFormattedText("Page " + (iPage + 1) + " of " + numPages); formtxt.SetFontWeight(FontWeights.Bold); Point ptText = new Point( (PageSize.Width + Margins.Left - Margins.Right - formtxt.Width) / 2, PageSize.Height - Margins.Bottom + formtxt.Height); dc.DrawText(formtxt, ptText); } // Look through the lines on the page. for (int i = 0; i < linesPerPage; i++, iLine++) { if (iLine == listLines.Count) { break; } // Set up information to display the text of the line. string str = listLines[iLine].String; FormattedText formtxt = GetFormattedText(str); Point ptText = new Point(xStart, yStart + i * heightLine); dc.DrawText(formtxt, ptText); // Possibly display the little arrow flag. if (listLines[iLine].Flag) { double x = xStart + width + 6; double y = yStart + i * heightLine + formtxt.Baseline; double len = face.CapsHeight * em; dc.DrawLine(pn, new Point(x, y), new Point(x + len, y - len)); dc.DrawLine(pn, new Point(x, y), new Point(x, y - len / 2)); dc.DrawLine(pn, new Point(x, y), new Point(x + len / 2, y)); } } dc.Close(); // Create DocumentPage object based on visual. DocumentPage page = new DocumentPage(vis); listPages.Add(page); } reader.Close(); }
/// <inheritdoc/> public void DrawTexts(IList <Point> points, Color color, IList <string> texts, FontFamily fontFamily, double fontSize, FontWeight fontWeight, HorizontalAlignment hAlign, VerticalAlignment vAlign, bool isHitTestVisible) { if (points == null) { throw new ArgumentNullException(nameof(points)); } if (texts == null) { throw new ArgumentNullException(nameof(texts)); } if (points.Count != texts.Count) { throw new ArgumentException($"{nameof(points)} and {nameof(texts)} must have the same number of elements."); } var brush = GetBrush(color); var typeFace = new Typeface(fontFamily, FontStyles.Normal, fontWeight, FontStretches.Normal); var visual = new DrawingVisual(); var context = visual.RenderOpen(); for (var i = 0; i < points.Count; ++i) { var text = texts[i]; var point = points[i]; var formatted = new FormattedText(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, typeFace, fontSize, brush); var dx = 0.0; var dy = 0.0; if (hAlign != HorizontalAlignment.Left || vAlign != VerticalAlignment.Top) { var size = new Size(formatted.Width, formatted.Height); if (hAlign == HorizontalAlignment.Center) { dx = -size.Width / 2; } if (hAlign == HorizontalAlignment.Right) { dx = -size.Width; } if (vAlign == VerticalAlignment.Center) { dy = -size.Height / 2; } if (vAlign == VerticalAlignment.Bottom) { dy = -size.Height; } } point.Offset(dx, dy); context.DrawText(formatted, point); } context.Close(); var host = Create <VisualHost>(isHitTestVisible); host.AddChild(visual); }
private Stream CreateThumbNailImage() { if (this.EditorCanvas == null) { return(null); } try { //Get real height and width property of image bound box //double minleft = double.MaxValue; //double mintop = double.MaxValue; double maxRight = double.MinValue; double maxBottom = double.MinValue; DesignerCanvas DeCanvas = _editorCanvas as DesignerCanvas; if (DeCanvas.AllWidgetItems.Count() <= 0) { return(null); } IEnumerable <BaseWidgetItem> SortedWidgets = DeCanvas.AllWidgetItems.OrderBy(i => (i.DataContext as WidgetViewModelDate).ZOrder); foreach (BaseWidgetItem element in SortedWidgets) { WidgetViewModelDate vm = element.DataContext as WidgetViewModelDate; Rect rec = new Rect(vm.Left, vm.Top, element.ActualWidth, element.ActualHeight); if (vm.RotateAngle != 0) { //Point offset = element.TransformToAncestor(parent).Transform(new Point(0, 0)); rec = new Rect(0, 0, element.ActualWidth, element.ActualHeight); rec = element.TransformToAncestor(DeCanvas).TransformBounds(rec); } maxRight = Math.Max(maxRight, rec.Left + rec.Width); maxBottom = Math.Max(maxBottom, rec.Top + rec.Height); } maxRight = maxRight + 10d; maxBottom = maxBottom + 10d; double scale = 80 / Math.Max(maxRight, maxBottom); scale = Math.Min(scale, 1d); //scale = 1; //map all widget into a DrawingVisual, make output image ready DrawingVisual tDrawingVisual = new DrawingVisual(); ScaleTransform stf = new ScaleTransform(); stf.ScaleX = scale; stf.ScaleY = scale; tDrawingVisual.Transform = stf; using (DrawingContext context = tDrawingVisual.RenderOpen()) { foreach (BaseWidgetItem element in SortedWidgets) { VisualBrush tVisualBrush = new VisualBrush(element); tVisualBrush.Stretch = Stretch.Fill; tVisualBrush.AlignmentX = 0; tVisualBrush.AlignmentY = 0; WidgetViewModelDate vm = element.DataContext as WidgetViewModelDate; Rect rec = new Rect(vm.Left, vm.Top, element.ActualWidth, element.ActualHeight); if (vm.RotateAngle != 0) { //Point offset = element.TransformToAncestor(parent).Transform(new Point(0, 0)); rec = new Rect(0, 0, element.ActualWidth, element.ActualHeight); rec = element.TransformToAncestor(DeCanvas).TransformBounds(rec); } context.DrawRectangle(tVisualBrush, null, rec); } context.Close(); } RenderTargetBitmap bmp = new RenderTargetBitmap((int)(maxRight * scale), (int)(maxBottom * scale), 96, 96, PixelFormats.Pbgra32); bmp.Render(tDrawingVisual); //Output the image stream. BitmapEncoder encoder; encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); ////using (Stream stm = File.Create(@"d:\123.png")) ////{ //// encoder.Save(stm); ////} ////return; MemoryStream stream = new MemoryStream(); encoder.Save(stream); return(stream); } catch { return(null); } }
/// <summary> /// Called when the Ddl property has changed. /// </summary> void DdlUpdated() { if (_ddl != null) { _document = DdlReader.DocumentFromString(_ddl); _renderer = new DocumentRenderer(_document); //this.renderer.PrivateFonts = this.privateFonts; _renderer.PrepareDocument(); //IDocumentPaginatorSource source = this.documentViewer.Document; //IDocumentPaginatorSource source = this.documentViewer.Document; int pageCount = _renderer.FormattedDocument.PageCount; if (pageCount == 0) { return; } // HACK: hardcoded A4 size //double pageWidth = XUnit.FromMillimeter(210).Presentation; //double pageHeight = XUnit.FromMillimeter(297).Presentation; //Size a4 = new Size(pageWidth, pageHeight); XUnit pageWidth, pageHeight; Size size96 = GetSizeOfPage(1, out pageWidth, out pageHeight); FixedDocument fixedDocument = new FixedDocument(); fixedDocument.DocumentPaginator.PageSize = size96; for (int pageNumber = 1; pageNumber <= pageCount; pageNumber++) { try { size96 = GetSizeOfPage(1, out pageWidth, out pageHeight); DrawingVisual dv = new DrawingVisual(); DrawingContext dc = dv.RenderOpen(); //XGraphics gfx = XGraphics.FromDrawingContext(dc, new XSize(XUnit.FromMillimeter(210).Point, XUnit.FromMillimeter(297).Point), XGraphicsUnit.Point); XGraphics gfx = XGraphics.FromDrawingContext(dc, new XSize(pageWidth.Point, pageHeight.Presentation), XGraphicsUnit.Point); _renderer.RenderPage(gfx, pageNumber, PageRenderOptions.All); dc.Close(); // Create page content PageContent pageContent = new PageContent(); pageContent.Width = size96.Width; pageContent.Height = size96.Height; FixedPage fixedPage = new FixedPage(); fixedPage.Background = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0xFE, 0xFE, 0xFE)); UIElement visual = new DrawingVisualPresenter(dv); FixedPage.SetLeft(visual, 0); FixedPage.SetTop(visual, 0); fixedPage.Width = size96.Width; fixedPage.Height = size96.Height; fixedPage.Children.Add(visual); fixedPage.Measure(size96); fixedPage.Arrange(new Rect(new Point(), size96)); fixedPage.UpdateLayout(); ((IAddChild)pageContent).AddChild(fixedPage); fixedDocument.Pages.Add(pageContent); } catch (Exception) { // eat exception } viewer.Document = fixedDocument; } } else { viewer.Document = null; } }
/// <summary> /// Create thumbNail for custom widget. /// </summary> /// <param name="bAllWidget">true: all widgets in the page, false: selected widgets in the page</param> /// <returns>ThumbNail icon</returns> private Stream CreateIconImage(bool bAllWidget) { if (this.EditorCanvas == null) { return(null); } //Get real height and width property of image bound box double minleft = double.MaxValue; double mintop = double.MaxValue; double maxRight = double.MinValue; double maxBottom = double.MinValue; DesignerCanvas DeCanvas = _editorCanvas as DesignerCanvas; IEnumerable <BaseWidgetItem> widgets; if (bAllWidget) { if (DeCanvas.AllWidgetItems.Count() <= 0) { return(null); } widgets = DeCanvas.AllWidgetItems.OrderBy(i => (i.DataContext as WidgetViewModelDate).ZOrder); } else { if (DeCanvas.SelectedItemAndChildren.Count() <= 0) { return(null); } widgets = DeCanvas.SelectedItemAndChildren.OrderBy(i => (i.DataContext as WidgetViewModelDate).ZOrder); } foreach (BaseWidgetItem element in widgets) { WidgetViewModelDate vm = element.DataContext as WidgetViewModelDate; Rect rec = new Rect(vm.Left, vm.Top, element.ActualWidth, element.ActualHeight); if (vm.RotateAngle != 0) { //Point offset = element.TransformToAncestor(parent).Transform(new Point(0, 0)); rec = new Rect(0, 0, element.ActualWidth, element.ActualHeight); rec = element.TransformToAncestor(DeCanvas).TransformBounds(rec); } minleft = Math.Min(minleft, rec.Left); mintop = Math.Min(mintop, rec.Top); maxRight = Math.Max(maxRight, rec.Left + rec.Width); maxBottom = Math.Max(maxBottom, rec.Top + rec.Height); } double nBoundWdith = maxRight - minleft; double nBoundHeight = maxBottom - mintop; //map all widget into a DrawingVisual, make output image ready DrawingVisual tDrawingVisual = new DrawingVisual(); ScaleTransform stf = new ScaleTransform(); double scale; if (nBoundWdith > nBoundHeight) { scale = 74d / nBoundWdith; } else { scale = 74d / nBoundHeight; } stf.ScaleX = Math.Min(1d, scale); stf.ScaleY = Math.Min(1d, scale); tDrawingVisual.Transform = stf; using (DrawingContext context = tDrawingVisual.RenderOpen()) { foreach (BaseWidgetItem element in widgets) { VisualBrush tVisualBrush = new VisualBrush(element); tVisualBrush.Stretch = Stretch.Fill; tVisualBrush.AlignmentX = 0; tVisualBrush.AlignmentY = 0; WidgetViewModelDate vm = element.DataContext as WidgetViewModelDate; double x = vm.Left - minleft; double y = vm.Top - mintop; Rect rec = new Rect(x, y, element.ActualWidth, element.ActualHeight); if (vm.RotateAngle != 0) { //Point offset = element.TransformToAncestor(parent).Transform(new Point(0, 0)); rec = new Rect(0, 0, element.ActualWidth, element.ActualHeight); rec = element.TransformToAncestor(DeCanvas).TransformBounds(rec); rec.X = rec.X - minleft; rec.Y = rec.Y - mintop; } context.DrawRectangle(tVisualBrush, null, rec); } context.Close(); } RenderTargetBitmap bmp = new RenderTargetBitmap((int)(nBoundWdith * scale), (int)(nBoundHeight * scale), 96, 96, PixelFormats.Pbgra32); bmp.Render(tDrawingVisual); //Output the image stream. BitmapEncoder encoder; encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); MemoryStream stream = new MemoryStream(); encoder.Save(stream); return(stream); }
public static bool Draw(ref System.Windows.Media.Imaging.WriteableBitmap bmp, List <Color> colors, bool horizontal) { if (colors.Count == 0) { return(false); } if (colors.Count == 1) { Rect rect = new Rect(); rect.Width = bmp.Width; rect.Height = bmp.Height; SolidColorBrush brush = new SolidColorBrush(colors[0]); RenderTargetBitmap bmp1 = new RenderTargetBitmap((int)(bmp.Width), (int)(bmp.Height), 96, 96, PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); Pen pen = new Pen(brush, 1.0); drawingContext.DrawRectangle(brush, pen, rect); drawingContext.Close(); bmp1.Render(drawingVisual); bmp = new System.Windows.Media.Imaging.WriteableBitmap(bmp1); } else if (horizontal) { int gradRectNum = colors.Count - 1; Rect rect = new Rect(); rect.Width = bmp.Width; rect.Height = bmp.Height; GradientStopCollection coll = new GradientStopCollection(); double step = 1.0 / gradRectNum; double x = 0.0; LinearGradientBrush brush = new LinearGradientBrush(); brush.StartPoint = new Point(0, 0); brush.EndPoint = new Point(1, 1); for (int j = 0; j < colors.Count(); ++j) { GradientStop stop = new GradientStop(colors[j], x); //coll.Add(stop); brush.GradientStops.Add(stop); x += step; } //LinearGradientBrush brush = new LinearGradientBrush(coll, 180.0); RenderTargetBitmap bmp1 = new RenderTargetBitmap((int)(bmp.Width), (int)(bmp.Height), 96, 96, PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); Pen pen = new Pen(brush, 1.0); drawingContext.DrawRectangle(brush, pen, rect); drawingContext.Close(); bmp1.Render(drawingVisual); bmp = new System.Windows.Media.Imaging.WriteableBitmap(bmp1); } else { int gradRectNum = colors.Count - 1; Rect rect = new Rect(); rect.Width = bmp.Width; rect.Height = bmp.Height; GradientStopCollection coll = new GradientStopCollection(); double step = 1.0 / gradRectNum; double x = 0.0; for (int j = 0; j < colors.Count(); ++j) { GradientStop stop = new GradientStop(colors[j], x); coll.Add(stop); x += step; } LinearGradientBrush brush = new LinearGradientBrush(coll, 90.0); RenderTargetBitmap bmp1 = new RenderTargetBitmap((int)(bmp.Width), (int)(bmp.Height), 96, 96, PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); Pen pen = new Pen(brush, 1.0); drawingContext.DrawRectangle(brush, pen, rect); drawingContext.Close(); bmp1.Render(drawingVisual); bmp = new System.Windows.Media.Imaging.WriteableBitmap(bmp1); } return(true); }
private BitmapSource Render(int index) { var currentFrame = _frames[index]; FrameInfo previousFrame = null; BitmapSource previousRendered = null; BitmapSource previousPreviousRendered = null; if (index > 0) { if (_renderedFrames[index - 1] == null) { _renderedFrames[index - 1] = Render(index - 1); } previousFrame = _frames[index - 1]; previousRendered = _renderedFrames[index - 1]; } // when saying APNGDisposeOpPrevious, we need to find the last frame not having APNGDisposeOpPrevious. // Only [index-2] is not correct here since that frame may also have APNGDisposeOpPrevious. if (index > 1) { previousPreviousRendered = _renderedFrames[_lastEffectivePreviousPreviousFrameIndex]; } if (_frames[index].DisposeOp != DisposeOps.APNGDisposeOpPrevious) { _lastEffectivePreviousPreviousFrameIndex = Math.Max(_lastEffectivePreviousPreviousFrameIndex, index); } var visual = new DrawingVisual(); using (var context = visual.RenderOpen()) { // protect region if (currentFrame.BlendOp == BlendOps.APNGBlendOpSource) { var freeRegion = new CombinedGeometry(GeometryCombineMode.Xor, new RectangleGeometry(currentFrame.FrameRect), new RectangleGeometry(currentFrame.FrameRect)); context.PushOpacityMask( new DrawingBrush(new GeometryDrawing(Brushes.Transparent, null, freeRegion))); } if (previousFrame != null) { switch (previousFrame.DisposeOp) { case DisposeOps.APNGDisposeOpNone: if (previousRendered != null) { context.DrawImage(previousRendered, currentFrame.FullRect); } break; case DisposeOps.APNGDisposeOpPrevious: if (previousPreviousRendered != null) { context.DrawImage(previousPreviousRendered, currentFrame.FullRect); } break; case DisposeOps.APNGDisposeOpBackground: // do nothing break; } } // unprotect region and draw current frame if (currentFrame.BlendOp == BlendOps.APNGBlendOpSource) { context.Pop(); } context.DrawImage(currentFrame.Pixels, currentFrame.FrameRect); } var bitmap = new RenderTargetBitmap( (int)currentFrame.FullRect.Width, (int)currentFrame.FullRect.Height, Math.Floor(currentFrame.Pixels.DpiX), Math.Floor(currentFrame.Pixels.DpiY), PixelFormats.Pbgra32); bitmap.Render(visual); bitmap.Freeze(); return(bitmap); }
private void UpdateSpectrogramDisplay_RTB() { if (mMainViewModel.SpectrumAreaViewModel.LastSpectrumData == null) { return; } this.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() => { double[] data = mMainViewModel.SpectrumAreaViewModel.LastSpectrumData; double dContainerWidth = this.SpectrogramViewPortContainer.ActualWidth; double dContainerHeight = this.SpectrogramViewPortContainer.ActualHeight; double dPixelWidth = dContainerWidth / data.Length; double dCellHeight = 1; double dCellWidth = 1; DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); if (this.PreviousBitmap != null) { drawingContext.DrawImage(this.PreviousBitmap, new Rect(0, dCellHeight, dContainerWidth, dContainerHeight - 1)); } for (int i = 0; i < data.Length; i++) { double dCellX = Math.Round(i * dPixelWidth); double dY = data[i]; Color oColor = this.GetColor(dY); //drawingContext.DrawRectangle(new SolidColorBrush(oColor), // new Pen(), new Rect(dCellX, 0, dCellWidth, dCellHeight)); LinearGradientBrush lineBrush = new LinearGradientBrush(); lineBrush.GradientStops.Add(new GradientStop(Colors.Transparent, 0)); lineBrush.GradientStops.Add(new GradientStop(oColor, 0.25)); lineBrush.GradientStops.Add(new GradientStop(oColor, 0.5)); lineBrush.GradientStops.Add(new GradientStop(oColor, 0.75)); lineBrush.GradientStops.Add(new GradientStop(Colors.Transparent, 1)); drawingContext.DrawRectangle(lineBrush, new Pen(), new Rect(dCellX - 1, 0, dCellWidth + 2, dCellHeight)); } drawingContext.Close(); RenderTargetBitmap rtbCurrent = new RenderTargetBitmap((int)(dContainerWidth), (int)dContainerHeight, 96, 96, PixelFormats.Pbgra32); rtbCurrent.Render(drawingVisual); this.SpectrogramImageViewport.Source = rtbCurrent; this.PreviousBitmap = rtbCurrent; })); }
private static void setScrollBars(double width, double height) { Type GraphicsWindowType = typeof(GraphicsWindow); try { Window _window = (Window)GraphicsWindowType.GetField("_window", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); Canvas _mainCanvas = (Canvas)GraphicsWindowType.GetField("_mainCanvas", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null); RenderTargetBitmap _renderBitmap = (RenderTargetBitmap)GraphicsWindowType.GetField("_renderBitmap", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); DrawingGroup _mainDrawing = (DrawingGroup)GraphicsWindowType.GetField("_mainDrawing", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.NonPublic).GetValue(null); InvokeHelper ret = delegate { try { Object content = _window.Content; ScrollViewer scrollViewer; if (content.GetType() == typeof(ScrollViewer)) { scrollViewer = (ScrollViewer)content; } else { scrollViewer = new ScrollViewer(); _window.Content = null; scrollViewer.Content = content; scrollViewer.ScrollChanged += new ScrollChangedEventHandler(_ScrollChangedEvent); _window.Content = scrollViewer; //Replace SB Window SizeChanged event EventInfo eventInfo = _window.GetType().GetEvent("SizeChanged", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); Delegate methodDelegate = Delegate.CreateDelegate(eventInfo.EventHandlerType, GraphicsWindowType, "WindowSizeChanged"); eventInfo.RemoveEventHandler(_window, methodDelegate); _window.SizeChanged += new SizeChangedEventHandler(_WindowSizeChanged); } scrollViewer.HorizontalScrollBarVisibility = width > 0 ? ScrollBarVisibility.Auto : ScrollBarVisibility.Hidden; scrollViewer.VerticalScrollBarVisibility = height > 0 ? ScrollBarVisibility.Auto : ScrollBarVisibility.Hidden; width = System.Math.Max(width, _mainCanvas.ActualWidth); height = System.Math.Max(height, _mainCanvas.ActualHeight); Grid grid = (Grid)(scrollViewer.Content); grid.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; grid.VerticalAlignment = System.Windows.VerticalAlignment.Top; grid.Width = width; grid.Height = height; //These GraphicsWindow events fail with scrollbars so have to add new ones grid.MouseDown += new System.Windows.Input.MouseButtonEventHandler(_MouseDownEvent); //grid.MouseUp += new System.Windows.Input.MouseButtonEventHandler(_MouseUpEvent); //grid.MouseMove += new System.Windows.Input.MouseEventHandler(_MouseMoveEvent); grid.MouseWheel += new System.Windows.Input.MouseWheelEventHandler(_MouseWheelEvent); scrollViewer.PreviewKeyDown += new System.Windows.Input.KeyEventHandler(_KeyDownEvent); //grid.KeyUp += new System.Windows.Input.KeyEventHandler(_KeyUpEvent); //grid.TextInput += new System.Windows.Input.TextCompositionEventHandler(_TextInputEvent); Image _bitmapContainer = (Image)grid.Children[0]; _bitmapContainer.HorizontalAlignment = HorizontalAlignment.Left; _bitmapContainer.VerticalAlignment = VerticalAlignment.Top; _bitmapContainer.Width = width; _bitmapContainer.Height = height; FrameworkElement _visualContainer = (FrameworkElement)grid.Children[1]; _visualContainer.HorizontalAlignment = HorizontalAlignment.Left; _visualContainer.VerticalAlignment = VerticalAlignment.Top; _visualContainer.Width = width; _visualContainer.Height = height; if (rasterize) { //GraphicsWindowType.GetMethod("Rasterize", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, new object[] { }); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); drawingContext.DrawImage(_renderBitmap, new Rect(0.0, 0.0, _renderBitmap.Width, _renderBitmap.Height)); drawingContext.Close(); RenderTargetBitmap _renderBitmapNew = new RenderTargetBitmap((int)width + 120, (int)height + 120, 96.0, 96.0, PixelFormats.Default); _renderBitmapNew.Render(drawingVisual); GraphicsWindowType.GetField("_renderBitmap", BindingFlags.IgnoreCase | BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, _renderBitmapNew); _bitmapContainer.Source = _renderBitmapNew; } } catch (Exception ex) { Utilities.OnError(Utilities.GetCurrentMethod(), ex); } }; FastThread.Invoke(ret); } catch (Exception ex) { Utilities.OnError(Utilities.GetCurrentMethod(), ex); } }
private ImageSource PlatedImage(BitmapImage image) { if (!string.IsNullOrEmpty(BackgroundColor)) { string currentBackgroundColor; if (BackgroundColor == "transparent") { // Using InvariantCulture since this is internal currentBackgroundColor = SystemParameters.WindowGlassBrush.ToString(CultureInfo.InvariantCulture); } else { currentBackgroundColor = BackgroundColor; } var padding = 8; var width = image.Width + (2 * padding); var height = image.Height + (2 * padding); var x = 0; var y = 0; var group = new DrawingGroup(); var converted = ColorConverter.ConvertFromString(currentBackgroundColor); if (converted != null) { var color = (Color)converted; var brush = new SolidColorBrush(color); var pen = new Pen(brush, 1); var backgroundArea = new Rect(0, 0, width, height); var rectangleGeometry = new RectangleGeometry(backgroundArea, 8, 8); var rectDrawing = new GeometryDrawing(brush, pen, rectangleGeometry); group.Children.Add(rectDrawing); var imageArea = new Rect(x + padding, y + padding, image.Width, image.Height); var imageDrawing = new ImageDrawing(image, imageArea); group.Children.Add(imageDrawing); // http://stackoverflow.com/questions/6676072/get-system-drawing-bitmap-of-a-wpf-area-using-visualbrush var visual = new DrawingVisual(); var context = visual.RenderOpen(); context.DrawDrawing(group); context.Close(); var bitmap = new RenderTargetBitmap( Convert.ToInt32(width), Convert.ToInt32(height), _dpiScale100, _dpiScale100, PixelFormats.Pbgra32); bitmap.Render(visual); return(bitmap); } else { ProgramLogger.Exception($"Unable to convert background string {BackgroundColor} to color for {Package.Location}", new InvalidOperationException(), GetType(), Package.Location); return(new BitmapImage(new Uri(Constant.ErrorIcon))); } } else { // todo use windows theme as background return(image); } }
/* * Displays the image and calls Detect Faces */ private async void BrowseButton_Click(object sender, RoutedEventArgs e) { // Get the image file to scan from the user - allowed jpg, png, jpeg var openDlg = new Microsoft.Win32.OpenFileDialog { Filter = "Image Files|*.jpg;*.png;*.jpeg" }; var result = openDlg.ShowDialog(this); // Return if canceled if (!(bool)result) { return; } // Display the image file var filePath = openDlg.FileName; var fileUri = new Uri(filePath); var bitmapSource = new BitmapImage(); bitmapSource.BeginInit(); bitmapSource.CacheOption = BitmapCacheOption.None; bitmapSource.UriSource = fileUri; bitmapSource.EndInit(); FacePhoto.Source = bitmapSource; // Detect any faces in the image Title = "Detecting..."; _faces = await UploadAndDetectFaces(filePath); Title = $"Detection Finished. {_faces.Length} face(s) detected"; if (_faces.Length <= 0) { return; } // Prepare to draw rectangles around the faces var visual = new DrawingVisual(); var drawingContext = visual.RenderOpen(); drawingContext.DrawImage(bitmapSource, new Rect(0, 0, bitmapSource.Width, bitmapSource.Height)); var dpi = bitmapSource.DpiX; _resizeFactor = 96 / dpi; _faceDescriptions = new string[_faces.Length]; for (var i = 0; i < _faces.Length; ++i) { var face = _faces[i]; // Draw a rectangle on the face drawingContext.DrawRectangle( Brushes.Transparent, new Pen(Brushes.Red, 2), new Rect( face.FaceRectangle.Left * _resizeFactor, face.FaceRectangle.Top * _resizeFactor, face.FaceRectangle.Width * _resizeFactor, face.FaceRectangle.Height * _resizeFactor ) ); // Store the face description _faceDescriptions[i] = FaceDescription(face); } drawingContext.Close(); // Display the image with the rectangle around the face var faceWithRectBitmap = new RenderTargetBitmap((int)(bitmapSource.PixelWidth * _resizeFactor), (int)(bitmapSource.PixelHeight * _resizeFactor), 96, 96, PixelFormats.Pbgra32); faceWithRectBitmap.Render(visual); FacePhoto.Source = faceWithRectBitmap; // Set the status bar text faceDescriptionStatusBar.Text = "Place the mouse pointer over a face to see the face description."; }