/// <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 Image_Click(object sender, RoutedEventArgs e) { // Create dlg type OpenFileDialog Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); // sert default Text dlg.DefaultExt = ".jpg"; dlg.Filter = "Image files (*.jpg, *.png, *.bmp, *.gif) | *.jpg; *.png; *.bmp; *.gif"; // show dialog // C# 6.0 Question Mark mean null exception -> default constructor bool?result = dlg.ShowDialog(); if (!(bool)result) { return; } // Display image string filePath = dlg.FileName; Uri fileUri = new Uri(filePath); BitmapImage bitmapSource = new BitmapImage(); bitmapSource.BeginInit(); bitmapSource.CacheOption = BitmapCacheOption.None; bitmapSource.UriSource = fileUri; bitmapSource.EndInit(); // upload original photo LipstickDisp.Source = bitmapSource; using (var fStream = File.OpenRead(filePath)) { try { MainWindow mainWindow = Window.GetWindow(this) as MainWindow; string subscriptionKey = mainWindow._scenariosControl.SubscriptionKey; string endpoint = mainWindow._scenariosControl.SubscriptionEndpoint; lbl_text.Content = "Waitting!"; var faceServiceClient = new FaceServiceClient(subscriptionKey, endpoint); ProjectOxford.Face.Contract.Face[] faces = await faceServiceClient.DetectAsync(fStream, false, true, new FaceAttributeType[] { FaceAttributeType.Gender, FaceAttributeType.Age, FaceAttributeType.Smile, FaceAttributeType.Glasses, FaceAttributeType.HeadPose, FaceAttributeType.FacialHair, FaceAttributeType.Emotion, FaceAttributeType.Hair, FaceAttributeType.Makeup, FaceAttributeType.Occlusion, FaceAttributeType.Accessories, FaceAttributeType.Noise, FaceAttributeType.Exposure, FaceAttributeType.Blur }); if (faces.Length > 0) { //Drawing around the lip DrawingVisual visual = new DrawingVisual(); DrawingContext drawingContext = visual.RenderOpen(); drawingContext.DrawImage(bitmapSource, new Rect(0, 0, bitmapSource.Width, bitmapSource.Height)); double dpi = bitmapSource.DpiX; // Set DPI image double resizeFactor = (dpi == 0) ? 1 : 96 / dpi; foreach (var face in faces) { //face.FaceAttributes.Makeup.LipMakeup.ToString() double UpperLipTop_X = face.FaceLandmarks.UpperLipTop.X; double UpperLipTop_Y = face.FaceLandmarks.UpperLipTop.Y; double UpperLipBottom_X = face.FaceLandmarks.UpperLipBottom.X; double UpperLipBottom_Y = face.FaceLandmarks.UpperLipBottom.Y; double UnderLipTop_X = face.FaceLandmarks.UnderLipTop.X; double UnderLipTop_Y = face.FaceLandmarks.UnderLipTop.Y; double UnderLipBottom_X = face.FaceLandmarks.UnderLipBottom.X; double UnderLipBottom_Y = face.FaceLandmarks.UnderLipBottom.Y; // lbl_text.Content = faces.Length.ToString() + ' ' + UpperLipTop_X.ToString() + ' ' + UpperLipTop_Y.ToString() + ' ' + UnderLipTop_X.ToString() + ' ' + UnderLipTop_Y.ToString(); //lbl_text.Content = face.FaceAttributes.Makeup.LipMakeup.ToString(); // Draw a rectangle on the lip drawingContext.DrawRectangle(Brushes.Transparent, new Pen(Brushes.Red, 2), new Rect( UpperLipTop_X * resizeFactor, UpperLipTop_Y * resizeFactor, (UpperLipBottom_X - UpperLipTop_X) * resizeFactor, (UpperLipBottom_Y - UpperLipTop_Y) * resizeFactor ) ); // Loop through the images pixels to reset color. //lbl_text.Content = UpperLipTop_X; //* resizeFactor; //drawingContext.DrawRectangle(Brushes.Red, null, // new Rect( // UpperLipTop_X * resizeFactor - 50, UpperLipTop_Y * resizeFactor, 50, 20 // ) //); //int i = Int32.Parse((UpperLipTop_X * resizeFactor - 100) * 100); //for (double Y = UpperLipTop_Y * resizeFactor - 100; Y <= UnderLipBottom_Y * resizeFactor + 100; Y++) //{ // for (double X = UpperLipTop_X * resizeFactor - 100; X < UpperLipTop_X * resizeFactor + 100; X++) // { // drawingContext.DrawRectangle(Brushes.Red, null, new Rect(Y, X, 1, 1)); // } //} //lbl_text.Content = count.ToString() + ' ' + bitmapSource.Width.ToString() + ' ' + bitmapSource.Height.ToString(); } // Close drawing drawingContext.Close(); // Display the image with the rectangle around the face RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap( (int)(bitmapSource.PixelWidth * resizeFactor), (int)(bitmapSource.PixelHeight * resizeFactor), 96, 96, PixelFormats.Pbgra32); faceWithRectBitmap.Render(visual); lipstickDisplay.Source = faceWithRectBitmap; } } catch (FaceAPIException ex) { MainWindow.Log("Response: {0}. {1}", ex.ErrorCode, ex.ErrorMessage); GC.Collect(); return; } } }
public DataGridPaginator(DrawingVisual source, Size printSize, Thickness pageMargins, PrintTableDefination printTableDefination) : base(source, printSize, pageMargins, printTableDefination) { }
/// <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 bool SaveImageFile(string fileName, string imageFileName, ImageEncoderType encoderType) { if (_drawing == null) { throw new InvalidOperationException( "There is no converted drawing for the saving operation."); } string outputExt = GetImageFileExtention(encoderType); string outputFileName = null; if (string.IsNullOrWhiteSpace(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.IsNullOrWhiteSpace(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 = GetBitmapEncoder(encoderType); // 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(); if (this.Background != null) { drawingContext.DrawRectangle(this.Background, null, _drawing.Bounds); } 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); } _imageFile = outputFileName; return(true); }
private void CreateActioners(bool OnlyAdornAsSelected, Rect PointingHeadingArea, Rect WorkingHeadingRectangle) { double PosX; double PosY; var CanShowActioners = !(Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl) || Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift) || Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)); if (!OnlyAdornAsSelected) { FrmMarkingZones.Clear(); var ZoneBrush = Brushes.Transparent; // FrmStrokeEdit (too dark) var ZonePen = new Pen(Brushes.Transparent, 1.0); // FrmPencil // Editing Areas of individual shown Details var ManipulatedShape = ManipulatedSymbol as VisualShape; if (ManipulatedShape != null && ManipulatedShape.CurrentMarkingZones != null) { CreateMarkingZones(ZoneBrush, ZonePen, ManipulatedShape); } if (ManipulatedSymbol.AreDetailsShown && WorkingHeadingRectangle.Width >= ACTIONER_SIZE && WorkingHeadingRectangle.Height >= ACTIONER_SIZE) { FrmDetailTitleDesignateZones.Clear(); FrmDetailTitleExpandZones.Clear(); FrmDetailContentAssignZones.Clear(); FrmDetailContentEditZones.Clear(); if (ManipulatedShape != null && ManipulatedShape.CurrentDetailZones != null && ManipulatedShape.CurrentDetailZones.Count > 0) { CreateDetailZones(ZoneBrush, ZonePen, ManipulatedShape); } if (CanShowActioners && ManipulatingDetailsRectangle.Width >= ACTIONER_SIZE * 4.2 && ManipulatingDetailsRectangle.Height >= ACTIONER_SIZE * 1.2) { // Details Bottom-Left PosX = (PointingHeadingArea.Left + (PointingHeadingArea.Width / 5.0)); PosY = ManipulatingDetailsRectangle.Y + ManipulatingDetailsRectangle.Height - ACTIONER_SIZE / 2.0; if (ManipulatedSymbol.OwnerRepresentation.RepresentedIdea.IdeaDefinitor.IsComposable) { ActSwitchCompositeView = CreateActionerFor(PosX, PosY, ESymbolManipulationAction.ActionShowCompositeAsDetail); Indicators.Add(ActSwitchCompositeView); ExclusivePointingIndicators.Add(ActSwitchCompositeView); } // Details Bottom-Right PosX = (PointingHeadingArea.Left + (PointingHeadingArea.Width / 5.0) * 4.0) - ACTIONER_SIZE; ActAddDetail = CreateActionerFor(PosX, PosY, ESymbolManipulationAction.ActionAddDetail); Indicators.Add(ActAddDetail); ExclusivePointingIndicators.Add(ActAddDetail); } } if (CanShowActioners && WorkingHeadingRectangle.Width >= ACTIONER_SIZE * 4.2 && WorkingHeadingRectangle.Height >= ACTIONER_SIZE * 1.2) { // Top-Left PosX = (PointingHeadingArea.Left + (PointingHeadingArea.Width / 5.0)); PosY = PointingHeadingArea.Top - ACTIONER_SIZE / 2.0; DefaultActionIndicator = CreateActionerFor(PosX, PosY, ESymbolManipulationAction.ActionEditProperties); Indicators.Add(DefaultActionIndicator); ExclusivePointingIndicators.Add(DefaultActionIndicator); // Bottom-Left PosY = PointingHeadingArea.Top + PointingHeadingArea.Height - ACTIONER_SIZE / 2.0; ActShowComposite = CreateActionerFor(PosX, PosY, ESymbolManipulationAction.ActionShowCompositeAsView); if (ManipulatedSymbol.OwnerRepresentation.RepresentedIdea.IdeaDefinitor.IsComposable) { Indicators.Add(ActShowComposite); ExclusivePointingIndicators.Add(ActShowComposite); } // Top-Right PosX = (PointingHeadingArea.Left + (PointingHeadingArea.Width / 5.0) * 4.0) - ACTIONER_SIZE; PosY = PointingHeadingArea.Top - ACTIONER_SIZE / 2.0; ActSwitchRelated = CreateActionerFor(PosX, PosY, ESymbolManipulationAction.ActionSwitchRelated); Indicators.Add(ActSwitchRelated); ExclusivePointingIndicators.Add(ActSwitchRelated); // Bottom-Right PosY = PointingHeadingArea.Top + PointingHeadingArea.Height - ACTIONER_SIZE / 2.0; ActSwitchDetails = CreateActionerFor(PosX, PosY, ESymbolManipulationAction.ActionSwitchDetails); Indicators.Add(ActSwitchDetails); ExclusivePointingIndicators.Add(ActSwitchDetails); } } }
protected override GeneratorResult ProcessInternal(HeatmapGeneratorSettings settings, GeneratorEntry entry) { try { entry.State = JobStates.Processing; _wrapper = new FfmpegWrapper(FfmpegExePath); var videoInfo = _wrapper.GetVideoInfo(settings.VideoFile); if (videoInfo.Duration <= TimeSpan.Zero) { entry.State = JobStates.Done; entry.DoneType = JobDoneTypes.Failure; entry.Update("Failed", 1); return(GeneratorResult.Failed()); } TimeSpan duration = videoInfo.Duration; //TODO string script = ViewModel.GetScriptFile(settings.VideoFile); var actions = ViewModel.LoadScriptActions(script, null); if (actions == null || actions.Count == 0) { entry.State = JobStates.Done; entry.DoneType = JobDoneTypes.Failure; entry.Update("Failed", 1); return(GeneratorResult.Failed()); } List <TimedPosition> timeStamps = ViewModel.FilterDuplicates(actions.ToList()).Cast <FunScriptAction>().Select(f => new TimedPosition { Position = f.Position, TimeStamp = f.TimeStamp }).ToList(); Brush heatmap = HeatMapGenerator.Generate3(timeStamps, TimeSpan.FromSeconds(10), TimeSpan.Zero, duration, 1.0, out Geometry bounds); bounds.Transform = new ScaleTransform(settings.Width, settings.Height); var rect = new Rect(0, 0, settings.Width, settings.Height); DrawingVisual visual = new DrawingVisual(); using (DrawingContext context = visual.RenderOpen()) { if (!settings.TransparentBackground) { context.DrawRectangle(Brushes.Black, null, rect); } if (settings.MovementRange) { context.PushClip(bounds); } context.DrawRectangle(heatmap, null, rect); if (settings.AddShadow) { LinearGradientBrush shadow = new LinearGradientBrush(); shadow.StartPoint = new Point(0.5, 0); shadow.EndPoint = new Point(0.5, 1); shadow.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF - 0x20, 0, 0, 0), 0)); shadow.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF - 0xcc, 0, 0, 0), 0.98)); shadow.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF - 0x50, 0, 0, 0), 0.98)); shadow.GradientStops.Add(new GradientStop(Color.FromArgb(0xFF - 0x50, 0, 0, 0), 1)); context.DrawRectangle(shadow, null, rect); } if (settings.MovementRange) { context.Pop(); } } RenderTargetBitmap bitmap = new RenderTargetBitmap(settings.Width, settings.Height, 96, 96, PixelFormats.Pbgra32); bitmap.Render(visual); PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); using (FileStream stream = new FileStream(settings.OutputFile, FileMode.Create)) encoder.Save(stream); entry.DoneType = JobDoneTypes.Success; entry.Update("Done", 1); return(GeneratorResult.Succeeded(settings.OutputFile)); } catch (Exception) { entry.Update("Failed", 1); entry.DoneType = JobDoneTypes.Failure; return(GeneratorResult.Failed()); } finally { entry.State = JobStates.Done; if (_canceled) { entry.DoneType = JobDoneTypes.Cancelled; entry.Update("Cancelled", 1); } } }
public DrawingVisualElement() { visual = new DrawingVisual(); }
/// <summary> /// Tab 1 Detect Faces and draw rectangles for detected faces in section 'Detect Faces' /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void DetectFacesBrowseButton_Click(object sender, RoutedEventArgs 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; } }
/// <summary> /// Tab 5 Identify voters with face rectangles and voters'name in section 'Identify Voters' /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void IdentifyButton_Click(object sender, RoutedEventArgs e) { int itemNum = Tab5PersonGroupIDComboBox.Items.Count; int selectedGroup = Tab5PersonGroupIDComboBox.SelectedIndex; if (itemNum == 0) { MessageBox.Show("Please define the person group ID first in page 2"); } if (selectedGroup == -1) { MessageBox.Show("Please select a group."); } if (itemNum != 0 && selectedGroup != -1) { TestFacePhoto.Source = null; 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(); using (Stream s = File.OpenRead(filePath)) { var faces = await faceServiceClient.DetectAsync(s); var faceRects = faces.Select(face => face.FaceRectangle).ToArray(); var faceIds = faces.Select(face => face.FaceId).ToArray(); string personGroupId = Tab5PersonGroupIDComboBox.Text; var results = await faceServiceClient.IdentifyAsync(personGroupId, faceIds); int i = 0; FaceRectangle faceRect = null; 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 identifyResult in results) { Console.WriteLine("Identify result of face id: {0}", identifyResult.FaceId); Console.WriteLine("Identify result of length of candidates: {0}", identifyResult.Candidates.Length); faceRect = faceRects[i]; ///No candidate indicates that the person has not provided his registered face image to register as a voter. if (identifyResult.Candidates.Length == 0) { ///Draw a face rectangle drawingContext.DrawRectangle( Brushes.Transparent, new Pen(Brushes.Red, 2), new Rect( faceRect.Left * resizeFactor, faceRect.Top * resizeFactor, faceRect.Width * resizeFactor, faceRect.Height * resizeFactor ) ); ///Draw a context with 'Unknow' in 'Ghostwhite' color Point point = new Point(faceRect.Left * resizeFactor, faceRect.Top * resizeFactor - 10); string text = "Unknow"; System.Windows.Media.FormattedText myText = new System.Windows.Media.FormattedText( text, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Marlet"), 8.0, System.Windows.Media.Brushes.GhostWhite); drawingContext.DrawText(myText, point); } ///The Candidate.Length != 0 means that this person with a bunch of registered face images has been succeed registered into this system if (identifyResult.Candidates.Length != 0) { var candidateId = identifyResult.Candidates[0].PersonId; var person = await faceServiceClient.GetPersonAsync(personGroupId, candidateId); Console.WriteLine("Identified as {0}", person.Name); ///Draw a face rectangle drawingContext.DrawRectangle( Brushes.Transparent, new Pen(Brushes.Red, 2), new Rect( faceRect.Left * resizeFactor, faceRect.Top * resizeFactor, faceRect.Width * resizeFactor, faceRect.Height * resizeFactor ) ); ///Draw a context with register person's name in 'GreenYellow' colour Point point = new Point(faceRect.Left * resizeFactor, faceRect.Top * resizeFactor - 10); string text = person.Name; System.Windows.Media.FormattedText myText = new System.Windows.Media.FormattedText( text, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Marlet"), 10.0, System.Windows.Media.Brushes.GreenYellow); drawingContext.DrawText(myText, point); } i++; } drawingContext.Close(); RenderTargetBitmap faceWithRectBitmap = new RenderTargetBitmap( (int)(bitmapSource.PixelWidth * resizeFactor), (int)(bitmapSource.PixelHeight * resizeFactor), 96, 96, PixelFormats.Pbgra32); faceWithRectBitmap.Render(visual); TestFacePhoto.Source = faceWithRectBitmap; } } }
private void RenderPage(int pageNumber, DrawingVisual visual) { int dpiX = PrinterTicket.PageResolution.X ?? 96; int dpiY = PrinterTicket.PageResolution.Y ?? 96; //Calculate the size of the printable area in inches //The printable area represents a DIPs (Device independed points) (DIPs = pixels/(DPI/96) ) var fitSize = new Size() { Width = PageSize.Width / 96.0, Height = PageSize.Height / 96.0 }; //Get page's size in inches //The page size represents a points (1pt = 1/72 inch) var pdfSize = new Size() { Width = _doc.Pages[pageNumber].Width / 72.0f, Height = _doc.Pages[pageNumber].Height / 72.0f }; //If page was rotated in original file, then we need to "rotate the paper in printer". //For that just swap the width and height of the paper. if (_doc.Pages[pageNumber].OriginalRotation == PageRotate.Rotate270 || _doc.Pages[pageNumber].OriginalRotation == PageRotate.Rotate90) { fitSize = new Size(fitSize.Height, fitSize.Width); } //Calculate the render size (in inches) fitted to the paper's size. var rSize = GetRenderSize(pdfSize, fitSize); int pixelWidth = (int)(rSize.Width * dpiX); int pixelHeight = (int)(rSize.Height * dpiY); using (PdfBitmap bmp = new PdfBitmap(pixelWidth, pixelHeight, true)) { //Render to PdfBitmap using page's Render method with FPDF_PRINTING flag. _doc.Pages[pageNumber].RenderEx( bmp, 0, 0, pixelWidth, pixelHeight, PageRotate.Normal, RenderFlags.FPDF_PRINTING | RenderFlags.FPDF_ANNOT); //Rotates the PdfBitmap image depending on the orientation of the page PdfBitmap b2 = null; if (PageRotation(_doc.Pages[pageNumber]) == PageRotate.Rotate270) { b2 = bmp.SwapXY(false, true); } else if (PageRotation(_doc.Pages[pageNumber]) == PageRotate.Rotate180) { b2 = bmp.FlipXY(true, true); } else if (PageRotation(_doc.Pages[pageNumber]) == PageRotate.Rotate90) { b2 = bmp.SwapXY(true, false); } int stride = b2 == null ? bmp.Stride : b2.Stride; int width = b2 == null ? bmp.Width : b2.Width; int height = b2 == null ? bmp.Height : b2.Height; IntPtr buffer = b2 == null ? bmp.Buffer : b2.Buffer; var imgsrc = CreateImageSource(b2 ?? bmp); if (b2 != null) { b2.Dispose(); } var dc = visual.RenderOpen(); dc.DrawImage(imgsrc, new Rect(0, 0, imgsrc.PixelWidth / (dpiX / 96.0), imgsrc.Height / (dpiY / 90.0))); dc.Close(); imgsrc = null; } }
/// <summary> /// Do one step, called by a timer /// </summary> private void Step() { lock (this) { if (!_inTransition) { return; } double width = Math.Max(_sourceImage.Width, _targetImage.Width); double height = Math.Max(_sourceImage.Height, _targetImage.Height); double accelaration = Math.Max(20 - Math.Abs(Math.Abs(_imageBorderLocation) - width / 2) / 40, 2); _imageBorderLocation += _dx * accelaration + _dx; var drawVisual = new DrawingVisual(); var imageBrushSource = new ImageBrush { ImageSource = _sourceImage, Stretch = Stretch.Fill, TileMode = TileMode.None, AlignmentX = AlignmentX.Left, AlignmentY = AlignmentY.Top, Opacity = 1, Transform = new TranslateTransform(_imageBorderLocation, 0) }; imageBrushSource.Freeze(); var imageBrushTarget = new ImageBrush { ImageSource = _targetImage, Stretch = Stretch.Fill, TileMode = TileMode.None, AlignmentX = AlignmentX.Left, AlignmentY = AlignmentY.Top, Opacity = 1, Transform = new TranslateTransform( _originalTransitionCommand == BackgroundImageCommand.NextImage ? _imageBorderLocation + _targetImage.Width : _imageBorderLocation - _targetImage.Width, 0) }; imageBrushTarget.Freeze(); using (DrawingContext dc = drawVisual.RenderOpen()) { dc.DrawRectangle(imageBrushSource, null, new Rect(0, 0, width, height)); dc.DrawRectangle(imageBrushTarget, null, new Rect(0, 0, width, height)); } var result = new RenderTargetBitmap((int)width, (int)height, _targetImage.DpiX, _targetImage.DpiY, PixelFormats.Default); result.Render(drawVisual); result.Freeze(); _backgroundPictureManagerBlock._broadcast.SendAsync(result); //end of transition if (((_currentTransitionCommand == _originalTransitionCommand) && ((_dx > 0 && _imageBorderLocation >= _sourceImage.Width) || ((_dx < 0 && _imageBorderLocation <= -_sourceImage.Width)))) || ((_currentTransitionCommand != _originalTransitionCommand) && ((_dx > 0 && _imageBorderLocation >= 0) || ((_dx < 0 && _imageBorderLocation <= 0))))) { _inTransition = false; _timer.Enabled = false; //If we finished the original transition, we need to rotate the picture if (_currentTransitionCommand == _originalTransitionCommand) { _backgroundPictureManagerBlock.RotatePictures(_originalTransitionCommand == BackgroundImageCommand.NextImage); } } } }
private ImageSource PlatedImage(BitmapImage image) { if (!string.IsNullOrEmpty(BackgroundColor)) { string currentBackgroundColor; if (BackgroundColor == "transparent") { 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); 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); } }
/// <summary> /// Exports the framework element to an image. /// </summary> /// <param name="frameworkElement">exported framework element</param> /// <param name="method">image format</param> /// <param name="filename">file name</param> /// <param name="title">image title</param> /// <param name="useFrameAndCaption"></param> /// <param name="boundingRectangle">bounding rectangle</param> public void ExportToImage(FrameworkElement frameworkElement, EExportToImageMethod method, string filename, string title, bool useFrameAndCaption, Rect?boundingRectangle = null) { const int bounds = 10; const int textoffset = 20; if (method == EExportToImageMethod.PNG || method == EExportToImageMethod.PNGClipBoard) { FormattedText titleText = useFrameAndCaption ? new FormattedText(title, new CultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Verdana"), 20, Brushes.Gray) : null; RenderTargetBitmap rtb; if (!boundingRectangle.HasValue) { boundingRectangle = new Rect(0, 0, frameworkElement.ActualWidth, frameworkElement.ActualHeight); } if (useFrameAndCaption) { rtb = new RenderTargetBitmap((int)(Math.Max(bounds + boundingRectangle.Value.Width + bounds, textoffset + titleText.Width + textoffset)), (int)(textoffset + titleText.Height + textoffset + boundingRectangle.Value.Height + bounds), 96, 96, PixelFormats.Pbgra32); } else { rtb = new RenderTargetBitmap((int)(boundingRectangle.Value.Width), (int)(boundingRectangle.Value.Height), 96, 96, PixelFormats.Pbgra32); } frameworkElement.InvalidateVisual(); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); drawingContext.DrawRectangle(ViewToolkitResources.WhiteBrush, null, new Rect(0, 0, rtb.Width, rtb.Height)); VisualBrush canvasBrush = new VisualBrush(frameworkElement) { Stretch = Stretch.None, AlignmentX = 0, AlignmentY = 0 }; if (useFrameAndCaption) { Rect rect = new Rect(bounds, textoffset + titleText.Height + textoffset, rtb.Width - 2 * bounds, rtb.Height - bounds - textoffset - titleText.Height - textoffset); drawingContext.DrawRectangle(canvasBrush, new Pen(Brushes.LightGray, 1), rect); drawingContext.DrawText(titleText, new Point(rtb.Width / 2 - titleText.Width / 2, textoffset)); } else { drawingContext.DrawRectangle(canvasBrush, null, new Rect(-boundingRectangle.Value.Left, -boundingRectangle.Value.Top, boundingRectangle.Value.Width + boundingRectangle.Value.Left, boundingRectangle.Value.Height + boundingRectangle.Value.Top)); } drawingContext.Close(); rtb.Render(drawingVisual); PngBitmapEncoder png = new PngBitmapEncoder(); png.Frames.Add(BitmapFrame.Create(rtb)); if (method == EExportToImageMethod.PNG) { using (Stream stm = File.Create(filename)) { png.Save(stm); } } if (method == EExportToImageMethod.PNGClipBoard) { Clipboard.SetImage(rtb); } } else if (method == EExportToImageMethod.XPS) { { if (!boundingRectangle.HasValue) { boundingRectangle = new Rect(0, 0, frameworkElement.ActualWidth, frameworkElement.ActualHeight); } // Save current canvas transorm Transform transform = frameworkElement.LayoutTransform; // Temporarily reset the layout transform before saving frameworkElement.LayoutTransform = null; // Get the size of the canvas Size size = new Size(boundingRectangle.Value.Width, boundingRectangle.Value.Height); // Measure and arrange elements frameworkElement.Measure(size); frameworkElement.Arrange(new Rect(size)); // Open new package System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(filename, FileMode.Create); // Create new xps document based on the package opened XpsDocument doc = new XpsDocument(package); // Create an instance of XpsDocumentWriter for the document XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc); // Write the canvas (as Visual) to the document writer.Write(frameworkElement); // Close document doc.Close(); // Close package package.Close(); // Restore previously saved layout frameworkElement.LayoutTransform = transform; } } }
/// <summary> /// Рендеринг компонента /// </summary> /// <param name="drawingContext">контекст рисования</param> protected override void OnRender(DrawingContext drawingContext) { #region Алгоритм подготовки к рисованию base.OnRender(drawingContext); //Текущая фактическая высота области рисования double currentHeight = this.RenderSize.Height - this.hScrollBar.RenderSize.Height; //Текущая фактическая ширина области рисования double currentWidth = this.RenderSize.Width - this.vScrollBar.RenderSize.Width; //Область рисования (вне этой области рисовать нельзя) Size clipSize = new Size(currentWidth, currentHeight); //ограничиваем drawingContext.PushClip(new RectangleGeometry(new Rect(new Point(0, 0), clipSize))); //очищаем фон drawingContext.DrawRectangle(this.ЦветФона, null, new Rect(new Point(0, 0), clipSize)); //Проверка на кол-во строк if (this.СписокСтрок.Count <= 0) { return; } //текущий индекс рисуемой строки int индекс = this.ИндексПервойВидимойСтроки; //текущая точка рисования на канвасе компонента Point текущаяТочкаРендеринга = new Point(0, 0); //учёт горизонтального скроллинга (если ползунок передвинут) (в случае когда не помещается полностью элемент) текущаяТочкаРендеринга.X = -this.hScrollBar.Value; //обнуляем вертикальный скролбар (нечего отображать) this.hScrollBar.Maximum = 0; //очистка Списка областей (прямоугольников), в которых отрисованы видымые элементы списка SourceData this.СписокПрямоугольныхОбластейВидимыхСтрок.Clear(); #endregion #region Цикл отрисовки видимых блоков (элементов) - пока они видны на экране (канвасе компонента) while (текущаяТочкаРендеринга.Y < currentHeight) { //Проверка индексов на допустимость if (индекс < 0) { return; } //Обработка ситуации превышения текущего индекса над общим кол-вом строк if (индекс >= this.СписокСтрок.Count) { break; } //преобразоваем элемент пользовательского типа в универсальный шаблон отображения BlockBase блокТекущейРисуемойСтроки = this.ConvertToBlockTemplate(this.СписокСтрок[индекс], индекс); //рендерим шаблон DrawingVisual визуальныйБуферТекущейРисуемойСтроки = блокТекущейРисуемойСтроки.Render(текущаяТочкаРендеринга); //рисуем его на канвасе компонента drawingContext.DrawDrawing(визуальныйБуферТекущейРисуемойСтроки.Drawing); //область рисования текущего шаблона Rect прямоугольнаяОбластьТекущейРисуемойСтроки = new Rect(текущаяТочкаРендеринга, блокТекущейРисуемойСтроки.RenderSize); //добавляем его в список (пригодится для реализации клика по элементу) this.СписокПрямоугольныхОбластейВидимыхСтрок.Add(прямоугольнаяОбластьТекущейРисуемойСтроки); //выбираем самую длинную ширину (самы длинный элемент) (для реализации горизонтального скроллинга) double deltaWidth = блокТекущейРисуемойСтроки.RenderSize.Width - currentWidth; if (deltaWidth > 0) { if (this.hScrollBar.Maximum <= deltaWidth) { this.hScrollBar.Maximum = deltaWidth; hScrollBar.IsEnabled = true; } } //переходим вниз, на свободное место для рисования текущаяТочкаРендеринга.Y += блокТекущейРисуемойСтроки.RenderSize.Height; //переход к следующей строке индекс++; } #endregion #region Выделение активной строки - отрисовка курсора if ((ПозицияКурсора_Строка >= ИндексПервойВидимойСтроки) && (ПозицияКурсора_Строка < (ИндексПервойВидимойСтроки + СписокПрямоугольныхОбластейВидимыхСтрок.Count))) { //отрисовка курсора - по факту это прямоугольник :))) drawingContext.DrawRectangle ( this.Foreground /*цвет курсора*/, null, new Rect ( СписокПрямоугольныхОбластейВидимыхСтрок[ПозицияКурсора_Строка - ИндексПервойВидимойСтроки].TopRight /*Положение курсора*/, new Size ( ШиринаКурсора /*установка ширины курсора*/, СписокПрямоугольныхОбластейВидимыхСтрок[ПозицияКурсора_Строка - ИндексПервойВидимойСтроки].Height /*Установка высоты курсора*/ ) ) ); } #endregion }
internal DrawingVisual Render() { if (null == drawingVisual) drawingVisual = new DrawingVisual(); DrawingContext context = drawingVisual.RenderOpen(); if (null != context) { Rect rect = new Rect(0, 0, parentVisual.ActualWidth, parentVisual.ActualHeight); context.PushClip(new RectangleGeometry(rect)); if (curvyTabs.Count > 0) { double offset = (curvyTabs.Count - 1) * (TabWidth + GapBetweenTabs); for (int index = curvyTabs.Count - 1; index >= 0; index--) { if (index == activeTabIndex) { offset = offset - TabWidth - GapBetweenTabs; continue; // Active tab to be rendered last. } CurvyTab tab = curvyTabs[index]; if (tab.MouseOver != false) tab.Render(context, activeBrush, offset); else tab.Render(context, inactiveBrush, offset); offset = offset - TabWidth - GapBetweenTabs; } // Render active tab. if (IsValidTabIndex(activeTabIndex)) { offset = (activeTabIndex * (TabWidth + GapBetweenTabs)); curvyTabs[activeTabIndex].Render(context, activeBrush, offset); } } context.DrawLine(borderLine, new Point(0, parentVisual.ActualHeight - 1), new Point(parentVisual.ActualWidth, parentVisual.ActualHeight - 1)); context.Pop(); context.Close(); // Done with rendering. } return drawingVisual; }
void Start() { Stretches = new List <MyStretch>(); Stretches.Add(new MyStretch((int)(bitmapWidth * 0.5f), bitmapHeight / 2, true)); if (!Directory.Exists(path_to_Obrazy)) { Directory.CreateDirectory(path_to_Obrazy); } obraz = new Image(); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); drawingContext.DrawRectangle(background.Brush, background, new Rect(0, 0, bitmapWidth, bitmapHeight)); while (continueUpdate) { List <MyStretch> next = new List <MyStretch>(); foreach (MyStretch ms in Stretches) { if (ms.isNew) { MyStretch nextA = ms.CreateA(Stretches); MyStretch nextB = ms.CreateB(Stretches); if (nextA != null) { next.Add(nextA); } if (nextB != null) { next.Add(nextB); } ms.isNew = false; } } t = (bitmapHeight >= bitmapWidth) ? bitmapWidth : bitmapHeight; foreach (MyStretch ms in next) { if (ms.ax + MyStretch.Length >= t && ms.ay + MyStretch.Length >= t || ms.bx + MyStretch.Length >= t && ms.by + MyStretch.Length >= t) { continueUpdate = false; break; } } foreach (MyStretch s in next) { Stretches.Add(s); s.Draw(drawingContext); } } drawingContext.Close(); System.Diagnostics.Debug.WriteLine("Wielkość listy " + Stretches.Count); RenderTargetBitmap bmp = new RenderTargetBitmap(bitmapWidth, bitmapHeight, 120, 96, PixelFormats.Pbgra32); bmp.Render(drawingVisual); obraz.Source = bmp; BitmapSource bmS = (BitmapSource)obraz.Source; string pathPlusName = path_to_Obrazy + "\\" + bitmapHeight + "_" + bitmapHeight + "_" + colorR + "_" + colorG + "_" + colorB + ".png"; SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.FileName = pathPlusName; saveFileDialog.Filter = "Pliki PNG | *.png"; if (saveFileDialog.ShowDialog(this) == true) { FileStream saveStream = new FileStream(saveFileDialog.FileName, FileMode.OpenOrCreate); PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmS)); encoder.Save(saveStream); saveStream.Close(); } }
private static void SnapshotPng([NotNull] UIElement source, [NotNull] string dstFileName) { try { if (Math.Abs(source.RenderSize.Height) < 0.000001) { return; } if (Math.Abs(source.RenderSize.Width) < 0.000001) { return; } double verticalTransform = 1; double horizontalTransform = 1; if (dstFileName.EndsWith("5-Standby.png", StringComparison.Ordinal)) { verticalTransform = 1.55; } if (dstFileName.EndsWith("3-Timeswhenacertaindeviceispermittedtorun.png", StringComparison.Ordinal)) { horizontalTransform = 2.1; } if (dstFileName.EndsWith("16-TimeLimit\\0-overview.png", StringComparison.Ordinal)) { horizontalTransform = 2.1; } var actualHeight = source.RenderSize.Height; var actualWidth = source.RenderSize.Width; const double resolutionFactor = 1; var renderHeight = actualHeight * resolutionFactor; var renderWidth = actualWidth * resolutionFactor; var renderTarget = new RenderTargetBitmap((int)renderWidth, (int)renderHeight, 96 * resolutionFactor, 96 * resolutionFactor, PixelFormats.Pbgra32); var sourceBrush = new VisualBrush(source); var drawingVisual = new DrawingVisual(); var drawingContext = drawingVisual.RenderOpen(); using (drawingContext) { drawingContext.PushTransform(new ScaleTransform(horizontalTransform, verticalTransform)); drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight))); } renderTarget.Render(drawingVisual); var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderTarget)); using (var stream = new FileStream(dstFileName, FileMode.Create, FileAccess.Write)) { encoder.Save(stream); } } catch (Exception e) { MessageWindowHandler.Mw.ShowDebugMessage(e); Logger.Exception(e); } }
protected override void ConfigureDrawingVisual(FastBitmap source, DrawingVisual drawingVisual) { Effect shaderEffect = GetEffect(source); drawingVisual.Effect = shaderEffect; }
/// <summary> /// конструктор по-умолчанию /// </summary> public BaseVisualComponent() { ClipFlag = true; Field = new Rect(); RenderingBuffer = new DrawingVisual(); }
// ----------------------------------------------------------------------------------------------------------------------- public override void Visualize(bool Show = true, bool OnlyAdornAsSelected = false) { // Validate that the Adorner still points something. // Else, maybe an "Undo" was performed, so the Represented-Idea may not exist anymore. if (ManipulatedSymbol == null || ManipulatedSymbol.OwnerRepresentation == null) { if (ManipulatedSymbol != null) { OwnerManager.RemoveAdorners(); } OwnerManager.OwnerView.UnselectAllObjects(); return; } var WorkingHeadingRectangle = ManipulatingHeadingRectangle; if (ManipulatedSymbol.IsHidden) { if (ManipulatedSymbol.CanShowNameOverCenter || ManipulatedSymbol.CanShowDefinitionOverTop) { WorkingHeadingRectangle = ManipulatingHeadingLabel; } else { return; // Because this is "hidden" (or shown too little to be noticed by user). } } // Reset previous drawn indicators ClearAllIndicators(); if (!Show) { return; } // Show every other selected objects VisualizeOtherAffectedObjects(); // Determine pointing areas var PointingHeadingArea = new Rect(WorkingHeadingRectangle.X - VisualSymbol.INDICATOR_SIZE / 2.0, WorkingHeadingRectangle.Y - VisualSymbol.INDICATOR_SIZE / 2.0, WorkingHeadingRectangle.Width + VisualSymbol.INDICATOR_SIZE, WorkingHeadingRectangle.Height + VisualSymbol.INDICATOR_SIZE); var PointingDetailsArea = new Rect(ManipulatingDetailsRectangle.X - VisualSymbol.INDICATOR_SIZE / 2.0, ManipulatingDetailsRectangle.Y - VisualSymbol.INDICATOR_SIZE / 2.0, ManipulatingDetailsRectangle.Width + VisualSymbol.INDICATOR_SIZE, ManipulatingDetailsRectangle.Height + VisualSymbol.INDICATOR_SIZE); /*T var PointingHeadingArea = WorkingHeadingRectangle; * var PointingDetailsArea = this.ManipulatingDetailsRectangle; */ // Start drawings creation var DrwFrmPointingHeadingPanel = new DrawingGroup { Opacity = FrmOpacity }; DrwFrmPointingHeadingPanel.Children.Add(new GeometryDrawing(FrmStroke, FrmPencil, new RectangleGeometry(PointingHeadingArea))); //-? if (this.ManipulatedSymbol.CanShowDefinitionOverTop || this.ManipulatedSymbol.CanShowNameOverCenter) // DrwFrmPointingHeadingPanel.Children.Add(new GeometryDrawing(this.FrmStroke, this.FrmPencil, new RectangleGeometry(this.ManipulatedSymbol.LabelingArea))); FrmPointingHeadingPanel = DrwFrmPointingHeadingPanel.RenderToDrawingVisual(); Indicators.Add(FrmPointingHeadingPanel); // IMPORTANT: The Details related indicators MUST BE CREATED in order to not be mismatched with null in later evaluations var DrwFrmPointingDetailsPanel = new DrawingGroup { Opacity = DrwFrmPointingHeadingPanel.Opacity }; DrwFrmPointingDetailsPanel.Children.Add(new GeometryDrawing(FrmStroke, FrmPencil, new RectangleGeometry(PointingDetailsArea))); FrmPointingDetailsPanel = DrwFrmPointingDetailsPanel.RenderToDrawingVisual(); if (ManipulatedSymbol.AreDetailsShown) { Indicators.Add(FrmPointingDetailsPanel); } if (!OnlyAdornAsSelected && WorkingHeadingRectangle.Width >= EDITAREA_MIN_WIDTH && WorkingHeadingRectangle.Height >= EDITAREA_MIN_HEIGHT) { var DrwFrmEditPanel = new DrawingGroup { Opacity = FrmOpacityEdit }; var EditingArea = new Rect(WorkingHeadingRectangle.X + WorkingHeadingRectangle.Width * 0.25, WorkingHeadingRectangle.Y + WorkingHeadingRectangle.Height * 0.25, WorkingHeadingRectangle.Width * 0.5, WorkingHeadingRectangle.Height * 0.5); DrwFrmEditPanel.Children.Add(new GeometryDrawing(FrmStrokeEdit, FrmPencil, new RectangleGeometry(EditingArea))); FrmEditZone = DrwFrmEditPanel.RenderToDrawingVisual(); Indicators.Add(FrmEditZone); ExclusivePointingIndicators.Add(FrmEditZone); } if (!ManipulatedSymbol.IsHidden) { CreateActioners(OnlyAdornAsSelected, PointingHeadingArea, WorkingHeadingRectangle); CreateSelectionIndicators(); } // Needed in order to show this adorner's indicators on top of a potentially selected visual element RefreshAdorner(); }
/// <summary> /// Generate the stereogram. Does all the common functionality, then calls the delegate /// set by the subclass to do the actual work. /// </summary> public Stereogram Generate() { // Let's do some profiling System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); timer.Start(); // Convert texture to RGB24 and scale it to fit the separation (preserving ratio but doubling width for HQ mode) bmTexture = texture.GetToScaleAndFormat(textureWidth, textureHeight, PixelFormats.Pbgra32); // Resize the depthmap to our target resolution bmDepthMap = depthmap.GetToScale(depthWidth, resolutionY); // Create a great big 2D array to hold the bytes - wasteful but convenient // ... and necessary for parallelisation pixels = new UInt32[lineWidth * rows]; // Copy the texture data into a buffer texturePixels = new UInt32[textureWidth * textureHeight]; bmTexture.CopyPixels(new Int32Rect(0, 0, textureWidth, textureHeight), texturePixels, textureWidth * bytesPerPixel, 0); // Copy the depthmap data into a buffer depthBytes = new byte[depthWidth * rows]; bmDepthMap.CopyPixels(new Int32Rect(0, 0, depthWidth, rows), depthBytes, depthWidth, 0); // Can mock up a progress indicator GeneratedLines = 0; // Prime candidate for Parallel.For... yes, about doubles the speed of generation on my Quad-Core if (System.Diagnostics.Debugger.IsAttached) // Don't run parallel when debugging { for (int y = 0; y < rows; y++) { DoLine(y); if (y > GeneratedLines) { GeneratedLines = y; } } } else { Parallel.For(0, rows, y => { if (false == abort) { DoLine(y); } if (y > GeneratedLines) { GeneratedLines = y; } }); } if (abort) { return(null); } // Virtual finaliser... not needed for any current algorithms Finalise(); // Create a writeable bitmap to dump the stereogram into wbStereogram = new WriteableBitmap(lineWidth, resolutionY, 96.0, 96.0, bmTexture.Format, bmTexture.Palette); wbStereogram.WritePixels(new Int32Rect(0, 0, lineWidth, rows), pixels, lineWidth * bytesPerPixel, 0); BitmapSource bmStereogram = wbStereogram; // High quality images need to be scaled back down... if (oversample > 1) { double over = (double)oversample; double centre = lineWidth / 2; while (over > 1) { // Scale by steps... could do it in one pass, but quality would depend on what the hardware does? double div = Math.Min(over, 2.0); // double div = over; ScaleTransform scale = new ScaleTransform(1.0 / div, 1.0, centre, 0); bmStereogram = new TransformedBitmap(bmStereogram, scale); over /= div; centre /= div; } } if (bAddConvergenceDots) { // Because I made these fields read-only, I can't now restore them... 'spose I could add the dots at hi-res but I'd still need to account for the stretching double sep = separation / oversample; double mid = midpoint / oversample; RenderTargetBitmap rtStereogram = new RenderTargetBitmap(bmStereogram.PixelWidth, bmStereogram.PixelHeight, 96.0, 96.0, PixelFormats.Pbgra32); DrawingVisual dots = new DrawingVisual(); DrawingContext dc = dots.RenderOpen(); dc.DrawImage(bmStereogram, new Rect(0.0, 0.0, rtStereogram.Width, rtStereogram.Height)); dc.DrawEllipse(new SolidColorBrush(Colors.Black), new Pen(new SolidColorBrush(Color.FromArgb(128, 0, 0, 0)), 1.0), new Point(mid - sep / 2, rtStereogram.Height / 16), sep / 16, sep / 16); dc.DrawEllipse(new SolidColorBrush(Colors.Black), new Pen(new SolidColorBrush(Color.FromArgb(128, 0, 0, 0)), 1.0), new Point(mid + sep / 2, rtStereogram.Height / 16), sep / 16, sep / 16); dc.Close(); rtStereogram.Render(dots); bmStereogram = rtStereogram; } // Freeze the bitmap so it can be passed to other threads bmStereogram.Freeze(); timer.Stop(); Stereogram stereogram = new Stereogram(bmStereogram); stereogram.options = this.options; stereogram.Name = String.Format("{0}+{1}+{2}", depthmap.Name, texture.Name, options.algorithm.ToString()); stereogram.Milliseconds = timer.ElapsedMilliseconds; return(stereogram); }
private void CreateSelectionIndicators() { var SelectionIndicators = ManipulatedSymbol.GenerateSelectionIndicators(VisualSymbol.INDICATOR_SIZE, (ManipulatedSymbol.OwnerRepresentation.IsSelected ? VisualElement.SelectionIndicatorBackground : IndStroke), IndPencil, (ManipulatedSymbol.OwnerRepresentation.IsSelected ? VisualElement.SelectionIndicatorGeometryCreator : null)); foreach (var SelInd in SelectionIndicators) { var IndVis = SelInd.Item1.RenderToDrawingVisual(); Indicators.Add(IndVis); if (SelInd.Item2) // Is for Symbol Header... { if (SelInd.Item3 == EManipulationDirection.Top) { IndHeadingTop = IndVis; } if (SelInd.Item3 == EManipulationDirection.Bottom) { IndHeadingBottom = IndVis; } if (SelInd.Item3 == EManipulationDirection.Left) { IndHeadingLeft = IndVis; } if (SelInd.Item3 == EManipulationDirection.Right) { IndHeadingRight = IndVis; } if (SelInd.Item3 == EManipulationDirection.TopLeft) { IndHeadingTopLeft = IndVis; } if (SelInd.Item3 == EManipulationDirection.TopRight) { IndHeadingTopRight = IndVis; } if (SelInd.Item3 == EManipulationDirection.BottomLeft) { IndHeadingBottomLeft = IndVis; } if (SelInd.Item3 == EManipulationDirection.BottomRight) { IndHeadingBottomRight = IndVis; } } else // Is for Symbol Detail... { if (SelInd.Item3 == EManipulationDirection.Bottom) { IndDetailsBottom = IndVis; } if (SelInd.Item3 == EManipulationDirection.Left) { IndDetailsLeft = IndVis; } if (SelInd.Item3 == EManipulationDirection.Right) { IndDetailsRight = IndVis; } if (SelInd.Item3 == EManipulationDirection.BottomLeft) { IndDetailsBottomLeft = IndVis; } if (SelInd.Item3 == EManipulationDirection.BottomRight) { IndDetailsBottomRight = IndVis; } } } }
public void UpdateKeyLights() { // Create a bitmap copy of what's shown in the UI artCanvas RenderTargetBitmap rtb = new RenderTargetBitmap(renderWidth, renderHeight, 96, 96, PixelFormats.Pbgra32); DrawingVisual dv = new DrawingVisual(); using (DrawingContext ctx = dv.RenderOpen()) { VisualBrush vb = new VisualBrush(drawCanvas); ctx.DrawRectangle(vb, null, new Rect(0, 0, renderWidth, renderHeight)); } rtb.Render(dv); // Create a pixel map of RGB values from the bitmap int[] pixels = new int[renderWidth * renderHeight * renderBytesPerPixel]; rtb.CopyPixels(pixels, renderBytesPerPixel * renderWidth, 0); // code above derived with thanks from https://blogs.msdn.microsoft.com/jaimer/2009/07/03/rendertargetbitmap-tips/ // now loop through entire List of keys and set the color of each to match the pixel map at that location for (int i = 0; i < KeyboardInfo.keysCount; i++) { int keylocationX = (int)(KeyboardInfo.keyLocations[i, KeyboardInfo.key_X] * renderScaleHoriz); int keyLocationY = (int)(KeyboardInfo.keyLocations[i, KeyboardInfo.key_Y] * renderScaleVert); int arrayOffset = keyLocationY * renderWidth + keylocationX; int theColor = pixels[arrayOffset]; int red = (int)(((theColor >> 16) & 0xFF) * mult8bitToPercent); int green = (int)(((theColor >> 8) & 0xFF) * mult8bitToPercent); int blue = (int)((theColor & 0xFF) * mult8bitToPercent); switch (KeyboardInfo.keyLocations[i, KeyboardInfo.key_WinCode]) { case KeyboardInfo.specialLogiKey: // logo, badge, and G-keys LogitechGSDK.LogiLedSetLightingForKeyWithKeyName((keyboardNames)KeyboardInfo.keyLocations[i, KeyboardInfo.key_HIDcode], red, green, blue); break; case KeyboardInfo.mediaKey: break; // media keys have no controllable lights on G910 default: LogitechGSDK.LogiLedSetLightingForKeyWithHidCode(KeyboardInfo.keyLocations[i, KeyboardInfo.key_HIDcode], red, green, blue); // above three cases handle all per-key RGB device lighting. Next section is for zone devices for (int j = 0; j < 5; j++) { if (keyToZoneMap[j] == KeyboardInfo.keyLocations[i, KeyboardInfo.key_WinCode]) { //if the color is being set on one of my 5 trigger keys for zone lighting, set the zone lighting LogitechGSDK.LogiLedSetTargetDevice(LogitechGSDK.LOGI_DEVICETYPE_RGB); LogitechGSDK.LogiLedSetLightingForTargetZone(DeviceType.Keyboard, j + 1, red, green, blue); //zone 0 is entire G213; zone 1-5 set light colors //assignment of trigger keys to set non-keyboard device colors is arbitrary; just did easy thing if (RingPrefs.showOnDevice[RingPrefs.speakerDevice] || paintPeripheralsOnce) { LogitechGSDK.LogiLedSetLightingForTargetZone(DeviceType.Speaker, j, red, green, blue); //zone 4 doesn't exist but slower to if/then around it } if (j < 2) // these devices have only 2 zones (0 and 1) { if (RingPrefs.showOnDevice[RingPrefs.headsetDevice] || paintPeripheralsOnce) { LogitechGSDK.LogiLedSetLightingForTargetZone(DeviceType.Headset, j, red, green, blue); } if (RingPrefs.showOnDevice[RingPrefs.mouseDevice] || paintPeripheralsOnce) { LogitechGSDK.LogiLedSetLightingForTargetZone(DeviceType.Mouse, j, red, green, blue); } } LogitechGSDK.LogiLedSetTargetDevice(LogitechGSDK.LOGI_DEVICETYPE_PERKEY_RGB); } } break; } } paintPeripheralsOnce = false; }
public static bool ImageSave(FrameworkElement inkCanvas, string fileName = null) { if (fileName == null) { var ofd = new SaveFileDialog { DefaultExt = ".jpg", Filter = "jpg file|*.jpg" }; if (ofd.ShowDialog() == true) { fileName = ofd.FileName; } if (fileName == null) { return(false); } } try { int ratio = 1; var width = (int)Math.Round(inkCanvas.ActualWidth * ratio); var height = (int)Math.Round(inkCanvas.ActualHeight * ratio); if (inkCanvas != null) { if (!Double.IsNaN(inkCanvas.Width)) { width = (int)inkCanvas.Width; } if (!Double.IsNaN(inkCanvas.Height)) { height = (int)inkCanvas.Height; } } Size size = new Size(width, height); inkCanvas.Measure(size); inkCanvas.Arrange(new Rect(size)); var bmpCopied = new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Default); var dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { var vb = new VisualBrush(inkCanvas) { Stretch = Stretch.Fill }; dc.DrawRectangle(vb, null, new Rect(new Point(), new Size(width, height))); } bmpCopied.Render(dv); using (var file = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { var encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmpCopied)); encoder.Save(file); return(true); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); return(false); } }
/// <summary> /// Handles the user clicking on the screenshot button /// </summary> /// <param name="sender">object sending the event</param> /// <param name="e">event arguments</param> private void ScreenshotButton_Click(object sender, RoutedEventArgs e) { // Create a render target to which we'll render our composite image RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)CompositeImage.ActualWidth, (int)CompositeImage.ActualHeight, 96.0, 96.0, PixelFormats.Pbgra32); DrawingVisual dv = new DrawingVisual(); using (DrawingContext dc = dv.RenderOpen()) { VisualBrush brush = new VisualBrush(CompositeImage); dc.DrawRectangle(brush, null, new Rect(new Point(), new Size(CompositeImage.ActualWidth, CompositeImage.ActualHeight))); } renderBitmap.Render(dv); BitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); unsafe { uint *bitmapPixelsPointer = (uint *)this.bitmap.BackBuffer; uint packedColor = bitmapPixelsPointer[0]; Color unpackedColor = new Color(); unpackedColor.B = (byte)(packedColor); unpackedColor.G = (byte)(packedColor >> 8); unpackedColor.R = (byte)(packedColor >> 16); unpackedColor.A = (byte)(packedColor >> 24); Console.WriteLine("Bitmap [0][0] Element: B:{0}, G:{1}, R:{2}, A:{3}", unpackedColor.B, unpackedColor.G, unpackedColor.R, unpackedColor.A); } string time = System.DateTime.Now.ToString("hh'-'mm'-'ss", CultureInfo.CurrentUICulture.DateTimeFormat); string myPhotos = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + "\\projectorCalibration\\kinect"; bool exists = System.IO.Directory.Exists(myPhotos); if (!exists) { System.IO.Directory.CreateDirectory(myPhotos); } string path = Path.Combine(myPhotos, "KinectScreenshot-CoordinateMapping-" + time + ".png"); // Write the new file to disk try { using (FileStream fs = new FileStream(path, FileMode.Create)) { encoder.Save(fs); } this.StatusText = string.Format(Properties.Resources.SavedScreenshotStatusTextFormat, path); } catch (IOException) { this.StatusText = string.Format(Properties.Resources.FailedScreenshotStatusTextFormat, path); } }
private async void BrowseButton_Click(object sender, RoutedEventArgs args) { try { IdentifyButton.IsEnabled = false; ProgressTextBlock.Text = "Identifying Crew Members..."; ProgressGrid.Visibility = Visibility.Visible; // Train the Person Group await _faceServiceClient.TrainPersonGroupAsync(PersonGroupId); var bitmapSource = new BitmapImage(); bitmapSource.BeginInit(); bitmapSource.CacheOption = BitmapCacheOption.None; bitmapSource.UriSource = new Uri(CrewPhotoPath, UriKind.Relative); bitmapSource.EndInit(); var drawingVisual = new DrawingVisual(); var drawingContext = drawingVisual.RenderOpen(); drawingContext.DrawImage(bitmapSource, new Rect(0, 0, bitmapSource.Width, bitmapSource.Height)); var dpi = bitmapSource.DpiX; var resizeFactor = 96 / dpi; using (var crewPhotoStream = File.OpenRead(CrewPhotoPath)) { // Get detected Faces var faces = await _faceServiceClient.DetectAsync(crewPhotoStream); var faceIds = faces.Select(face => face.FaceId).ToArray(); // Identify faces in the Person Group var results = await _faceServiceClient.IdentifyAsync(PersonGroupId, faceIds); foreach (var identifyResult in results) { var isIdentified = identifyResult.Candidates.Length != 0; // Get the best fit var targetFace = faces.FirstOrDefault(f => f.FaceId == identifyResult.FaceId); if (targetFace == null) { continue; } // Get the face rectangle var faceRect = targetFace.FaceRectangle; // Draw the face rectangle drawingContext.DrawRectangle( Brushes.Transparent, new Pen(isIdentified ? Brushes.Green : Brushes.Red, 4), new Rect( faceRect.Left * resizeFactor, faceRect.Top * resizeFactor, faceRect.Width * resizeFactor, faceRect.Height * resizeFactor ) ); // Draw the rectangle containing the Person Name drawingContext.DrawRectangle( isIdentified ? Brushes.Green : Brushes.Red, new Pen(isIdentified ? Brushes.Green : Brushes.Red, 4), new Rect( faceRect.Left * resizeFactor, faceRect.Top * resizeFactor - 20, faceRect.Width * resizeFactor, resizeFactor + 20 ) ); string name; if (isIdentified) { var candidateId = identifyResult.Candidates[0].PersonId; var person = await _faceServiceClient.GetPersonAsync(PersonGroupId, candidateId); name = person.Name; } else { name = "Alien"; } var formattedText = new FormattedText(name, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, _typeface, 16, Brushes.White); // Draw the Name drawingContext.DrawText(formattedText, new Point(faceRect.Left * resizeFactor + 4, faceRect.Top * resizeFactor - 20)); } } drawingContext.Close(); var faceWithRectBitmap = new RenderTargetBitmap( (int)(bitmapSource.PixelWidth * resizeFactor), (int)(bitmapSource.PixelHeight * resizeFactor), 96, 96, PixelFormats.Pbgra32); faceWithRectBitmap.Render(drawingVisual); CrewPhoto.Source = faceWithRectBitmap; } catch (Exception e) { Debug.WriteLine(e.Message); } finally { IdentifyButton.IsEnabled = true; ProgressGrid.Visibility = Visibility.Collapsed; } }
private void setYellowGreen() { DrawingVisual vis1 = new DrawingVisual(); DrawingVisual vis2 = new DrawingVisual(); DrawingVisual vis3 = new DrawingVisual(); DrawingVisual vis4 = new DrawingVisual(); DrawingVisual vis5 = new DrawingVisual(); DrawingVisual vis6 = new DrawingVisual(); DrawingContext dcSmallBlue = vis1.RenderOpen(); DrawingContext dcMediumBlue = vis2.RenderOpen(); DrawingContext dcLargeBlue = vis3.RenderOpen(); DrawingContext dcSmallRed = vis4.RenderOpen(); DrawingContext dcMediumRed = vis5.RenderOpen(); DrawingContext dcLargeRed = vis6.RenderOpen(); dcSmallBlue.DrawEllipse(Brushes.Transparent, new Pen(Brushes.Green, 2), new Point(50, 50), 15, 15); dcMediumBlue.DrawEllipse(Brushes.Transparent, new Pen(Brushes.Green, 2), new Point(50, 50), 30, 30); dcLargeBlue.DrawEllipse(Brushes.Transparent, new Pen(Brushes.Green, 2), new Point(50, 50), 45, 45); dcSmallRed.DrawEllipse(Brushes.Transparent, new Pen(Brushes.Yellow, 2), new Point(50, 50), 15, 15); dcMediumRed.DrawEllipse(Brushes.Transparent, new Pen(Brushes.Yellow, 2), new Point(50, 50), 30, 30); dcLargeRed.DrawEllipse(Brushes.Transparent, new Pen(Brushes.Yellow, 2), new Point(50, 50), 45, 45); dcSmallBlue.Close(); dcMediumBlue.Close(); dcLargeBlue.Close(); dcSmallRed.Close(); dcMediumRed.Close(); dcLargeRed.Close(); RenderTargetBitmap bmp = new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Pbgra32); RenderTargetBitmap bmp2 = new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Pbgra32); RenderTargetBitmap bmp3 = new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Pbgra32); RenderTargetBitmap bmp4 = new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Pbgra32); RenderTargetBitmap bmp5 = new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Pbgra32); RenderTargetBitmap bmp6 = new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Pbgra32); //////////////////////////////////////// bmp.Render(vis1); btnGreenSmall.Background = new ImageBrush(bmp); Image x = new Image { Source = bmp }; btnGreenSmall.Content = x; ///////////////////////////////////////// bmp2.Render(vis2); btnGreenMedium.Background = new ImageBrush(bmp2); Image x1 = new Image { Source = bmp2 }; btnGreenMedium.Content = x1; bmp3.Render(vis3); btnGreenLarge.Background = new ImageBrush(bmp3); Image x2 = new Image { Source = bmp3 }; btnGreenLarge.Content = x2; bmp4.Render(vis4); btnYellowSmall.Background = new ImageBrush(bmp4); Image x3 = new Image { Source = bmp4 }; btnYellowSmall.Content = x3; bmp5.Render(vis5); btnYellowMedium.Background = new ImageBrush(bmp5); Image x4 = new Image { Source = bmp5 }; btnYellowMedium.Content = x4; bmp6.Render(vis6); btnYellowLarge.Background = new ImageBrush(bmp6); Image x5 = new Image { Source = bmp6 }; btnYellowLarge.Content = x5; btnGreenSmall.Visibility = Visibility.Visible; btnGreenMedium.Visibility = Visibility.Visible; btnGreenLarge.Visibility = Visibility.Visible; btnYellowSmall.Visibility = Visibility.Visible; btnYellowMedium.Visibility = Visibility.Visible; btnYellowLarge.Visibility = Visibility.Visible; }
public static GeometryModel3D bitmapText(string _text, Brush textColor, bool isDoubleSided, double height, Point3D center, Vector3D textDirection, Vector3D updirection) { //Image myImage = new Image(); FormattedText text = new FormattedText(_text, new CultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface(new FontFamily("Arial"), FontStyles.Normal, FontWeights.Normal, new FontStretch()), height, textColor); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); drawingContext.DrawText(text, new Point(0, 0)); drawingContext.Close(); // We just assume the characters are square double width = _text.Length * height * 0.6; int _height = Convert.ToInt32(Math.Floor(height)); int _width = Convert.ToInt32(Math.Floor(width)); if (_height == 0) { _height = 1; } if (_width == 0) { _width = 1; } RenderTargetBitmap bmp = new RenderTargetBitmap(_width, _height, 240, 192, PixelFormats.Pbgra32); bmp.Render(drawingVisual); //myImage.Source = bmp; // Now use that TextBlock as the brush for a material var mat = new DiffuseMaterial { Brush = new ImageBrush(bmp) { Viewport = new Rect(0, 0, 1, 1), Stretch = Stretch.Fill } }; // tb.Measure(new Size(text.Length * height * 2, height * 2)); // width=tb.DesiredSize.Width; // Since the parameter coming in was the center of the label, // we need to find the four corners // p0 is the lower left corner // p1 is the upper left // p2 is the lower right // p3 is the upper right var p0 = center - width / 2 * textDirection - height / 2 * updirection; var p1 = p0 + updirection * 1 * height; var p2 = p0 + textDirection * width; var p3 = p0 + updirection * 1 * height + textDirection * width; // Now build the geometry for the sign. It's just a // rectangle made of two triangles, on each side. var mg = new MeshGeometry3D { Positions = new Point3DCollection { p0, p1, p2, p3 } }; if (isDoubleSided) { mg.Positions.Add(p0); // 4 mg.Positions.Add(p1); // 5 mg.Positions.Add(p2); // 6 mg.Positions.Add(p3); // 7 } mg.TriangleIndices.Add(0); mg.TriangleIndices.Add(3); mg.TriangleIndices.Add(1); mg.TriangleIndices.Add(0); mg.TriangleIndices.Add(2); mg.TriangleIndices.Add(3); if (isDoubleSided) { mg.TriangleIndices.Add(4); mg.TriangleIndices.Add(5); mg.TriangleIndices.Add(7); mg.TriangleIndices.Add(4); mg.TriangleIndices.Add(7); mg.TriangleIndices.Add(6); } // These texture coordinates basically stretch the // TextBox brush to cover the full side of the label. mg.TextureCoordinates.Add(new Point(0, 1)); mg.TextureCoordinates.Add(new Point(0, 0)); mg.TextureCoordinates.Add(new Point(1, 1)); mg.TextureCoordinates.Add(new Point(1, 0)); if (isDoubleSided) { mg.TextureCoordinates.Add(new Point(1, 1)); mg.TextureCoordinates.Add(new Point(1, 0)); mg.TextureCoordinates.Add(new Point(0, 1)); mg.TextureCoordinates.Add(new Point(0, 0)); } // And that's all. Return the result. return(new GeometryModel3D(mg, mat)); }
public WPFRenderer() { m_visual = new DrawingVisual(); }
private BitmapSource CreateBitmap(List <BitmapSource> bitmapList, XDocument metrics) { RenderTargetBitmap renderTargetBitmap = (RenderTargetBitmap)null; SolidColorBrush solidColorBrush = new SolidColorBrush(new Color() { R = 255 }); try { int val1 = 0; int num1 = Settings.SpaceWidth; if (!Settings.IsSpaceEnabled) { num1 = 0; } int val2 = num1; int num2 = num1; if (bitmapList.Count == 0) { return((BitmapSource)null); } int num3 = bitmapList[0].PixelHeight + 2 * Settings.ExtraSpaceWidth; for (int index = 0; index < bitmapList.Count; ++index) { val2 += bitmapList[index].PixelWidth + 2 * Settings.ExtraSpaceWidth + num1; if ((index + 1) % Settings.CharactersInARow == 0 && index + 1 < bitmapList.Count) { val1 = Math.Max(val1, val2); val2 = num1; num2 += num3 + num1; } } int pixelWidth = Math.Max(val1, val2); int pixelHeight = num2 + num3 + num1; renderTargetBitmap = new RenderTargetBitmap(pixelWidth, pixelHeight, 96.0, 96.0, PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); int num4 = 0; int num5 = num1; Rect rect = new Rect(0.0, 0.0, (double)pixelWidth, (double)num1); drawingContext.DrawRectangle((Brush)solidColorBrush, (Pen)null, rect); for (int index = 0; index < bitmapList.Count; ++index) { int num6 = bitmapList[index].PixelWidth + 2 * Settings.ExtraSpaceWidth; rect = new Rect((double)num4, (double)num5, (double)num1, (double)num3); drawingContext.DrawRectangle((Brush)solidColorBrush, (Pen)null, rect); int num7 = num4 + num1; rect = new Rect((double)(num7 + Settings.ExtraSpaceWidth), (double)(num5 + Settings.ExtraSpaceWidth), (double)(num6 - 2 * Settings.ExtraSpaceWidth), (double)(num3 - 2 * Settings.ExtraSpaceWidth)); drawingContext.DrawImage((ImageSource)bitmapList[index], rect); rect = new Rect((double)num7, (double)num5, (double)num6, (double)num3); this.AddMetricsRect(metrics, index, rect); num4 = num7 + num6; if ((index + 1) % Settings.CharactersInARow == 0 && index + 1 < bitmapList.Count) { if (Settings.IsSpaceEnabled) { rect = new Rect((double)num4, (double)num5, (double)(pixelWidth - num4), (double)num3); drawingContext.DrawRectangle((Brush)solidColorBrush, (Pen)null, rect); } int num8 = num5 + num3; rect = new Rect(0.0, (double)num8, (double)pixelWidth, (double)num1); drawingContext.DrawRectangle((Brush)solidColorBrush, (Pen)null, rect); num5 = num8 + num1; num4 = 0; } } if (Settings.IsSpaceEnabled) { rect = new Rect((double)num4, (double)num5, (double)(pixelWidth - num4), (double)num3); drawingContext.DrawRectangle((Brush)solidColorBrush, (Pen)null, rect); } rect = new Rect(0.0, (double)(num5 + num3), (double)pixelWidth, (double)num1); drawingContext.DrawRectangle((Brush)solidColorBrush, (Pen)null, rect); drawingContext.Close(); renderTargetBitmap.Render((Visual)drawingVisual); } catch (Exception ex) { Console.WriteLine(ex); } return((BitmapSource)renderTargetBitmap); }
/// <summary> /// derived class overwrite this to give different outlook. /// </summary> /// <param name="drawingVisual"></param> protected virtual void Render(DrawingVisual drawingVisual) { }