private Manager() { #region Create Loading Threads for (int i = 0; i < MaxThreads; i++) { Thread loaderThread = new Thread(LoaderWork) { IsBackground = true, Priority = ThreadPriority.BelowNormal, Name = $"ImageLoaderThread{i + 1}" }; loaderThread.Start(); } #endregion #region Load Images from Resources ResourceDictionary resourceDictionary = new ResourceDictionary(); resourceDictionary.Source = new Uri("ImageLoader;component/Resources.xaml", UriKind.Relative); _loadingImage = resourceDictionary["ImageLoading"] as DrawingImage; _loadingImage?.Freeze(); _errorThumbnail = resourceDictionary["ImageError"] as DrawingImage; _errorThumbnail?.Freeze(); #endregion # region Create Loading Animation
public async System.Threading.Tasks.Task Explode() { if (ParticleCount > MaxParticleCount) { return; } ParticleCount++; // TODO: rewrite this part for better design & performance // store service & package as static member. var service = ServiceProvider.GlobalProvider.GetService(typeof(SPowerMode)); var pm_service = service as IPowerMode; var package = pm_service.Package; var page = package.General; ExplosionParticle.Color = page.Color; ExplosionParticle.AlphaRemoveAmount = page.AlphaRemoveAmount; ExplosionParticle.bGetColorFromEnvironment = bGetColorFromEnvironment; ExplosionParticle.RandomColor = page.RandomColor; ExplosionParticle.FrameDelay = page.FrameDelay; ExplosionParticle.Gravity = page.Gravity; ExplosionParticle.MaxParticleCount = page.MaxParticleCount; ExplosionParticle.MaxSideVelocity = page.MaxSideVelocity; ExplosionParticle.MaxUpVelocity = page.MaxUpVelocity; //ExplosionParticle.ParticlesEnabled = page.ParticlesEnabled; //ExplosionParticle.ShakeEnabled = page.ShakeEnabled; ExplosionParticle.StartAlpha = page.StartAlpha; // End of TODO. var alpha = StartAlpha; var upVelocity = Random.NextDouble() * MaxUpVelocity; var leftVelocity = Random.NextDouble() * MaxSideVelocity * Random.NextSignSwap(); SolidColorBrush brush = null; if (bGetColorFromEnvironment) { var svc = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.Shell.Interop.SVsUIShell)) as Microsoft.VisualStudio.Shell.Interop.IVsUIShell5; brush = new SolidColorBrush(Microsoft.VisualStudio.Shell.VsColors.GetThemedWPFColor(svc, Microsoft.VisualStudio.PlatformUI.EnvironmentColors.PanelTextColorKey)); } else if (RandomColor) { brush = new SolidColorBrush(Random.NextColor()); } else { brush = new SolidColorBrush(Color); } brush.Freeze(); var drawing = new GeometryDrawing(brush, null, geometry); drawing.Freeze(); var drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); var image = new Image { Source = drawingImage, }; while (alpha >= AlphaRemoveAmount) { _left -= leftVelocity; _top -= upVelocity; upVelocity -= Gravity; alpha -= AlphaRemoveAmount; image.Opacity = alpha; Canvas.SetLeft(image, _left); Canvas.SetTop(image, _top); try { // Add the image to the adornment layer and make it relative to the viewport adornmentLayer.AddAdornment(AdornmentPositioningBehavior.ViewportRelative, null, null, image, null); await System.Threading.Tasks.Task.Delay(FrameDelay); adornmentLayer.RemoveAdornment(image); } catch { break; } } try { adornmentLayer.RemoveAdornment(image); } catch { //Ignore all errors, not critical } ParticleCount--; }
private DrawingImage RenderLayers() { var renderLayers = GetRenderLayers(); // Draw the current frame to the preview var keyboardRect = _deviceManager.ActiveKeyboard.KeyboardRectangle(); 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 foreach (var layer in renderLayers) { layer.Update(null, true, false); if (layer.LayerType.ShowInEdtor) { layer.Draw(null, drawingContext, true, false); } } // Get the selection color var accentColor = ThemeManager.DetectAppStyle(Application.Current)?.Item2?.Resources["AccentColor"]; if (accentColor == null) { var preview = new DrawingImage(); preview.Freeze(); KeyboardPreview = preview; return(new DrawingImage()); } var pen = new Pen(new SolidColorBrush((Color)accentColor), 0.4); // Draw the selection outline and resize indicator if (SelectedLayer != null && SelectedLayer.MustDraw()) { var layerRect = SelectedLayer.Properties.PropertiesRect(); // 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)); } SelectedProfile?.RaiseDeviceDrawnEvent(new ProfileDeviceEventsArg(DrawType.Preview, null, true, drawingContext)); // Remove the clip drawingContext.Pop(); } var drawnPreview = new DrawingImage(visual.Drawing); drawnPreview.Freeze(); // Setup layers for the next frame if (_moduleModel.IsInitialized && ActiveWindowHelper.MainWindowActive) { _moduleModel.PreviewLayers = renderLayers; } return(drawnPreview); }
public static DrawingImage GetImage(BrushType val) { double height = 1; double width = 2; // // Create the Geometry to draw. // var geometryGroup = new GeometryGroup(); geometryGroup.Children.Add(new RectangleGeometry(new Rect(0, 0, width, height))); var geometryDrawing = new GeometryDrawing() { Geometry = geometryGroup }; switch (val) { case BrushType.SolidBrush: geometryDrawing.Brush = new SolidColorBrush(Colors.Black); break; case BrushType.LinearGradientBrush: geometryDrawing.Brush = new LinearGradientBrush(Colors.Black, Colors.White, 0); break; case BrushType.TriangularShapeLinearGradientBrush: { var gStops = new GradientStopCollection { new GradientStop(Colors.Black, 0), new GradientStop(Colors.White, 0.5), new GradientStop(Colors.Black, 1) }; geometryDrawing.Brush = new LinearGradientBrush(gStops, 0); } break; case BrushType.SigmaBellShapeLinearGradientBrush: { var gStops = new GradientStopCollection { new GradientStop(Colors.Black, 0), new GradientStop(Colors.White, 0.5), new GradientStop(Colors.Black, 1) }; geometryDrawing.Brush = new LinearGradientBrush(gStops, 0); } break; case BrushType.PathGradientBrush: case BrushType.TriangularShapePathGradientBrush: case BrushType.SigmaBellShapePathGradientBrush: geometryDrawing.Brush = new RadialGradientBrush(Colors.Black, Colors.White); break; case BrushType.HatchBrush: case BrushType.SyntheticTextureBrush: case BrushType.TextureBrush: geometryDrawing.Brush = new SolidColorBrush(Colors.Black); break; default: break; } var geometryImage = new DrawingImage(geometryDrawing); // Freeze the DrawingImage for performance benefits. geometryImage.Freeze(); return(geometryImage); }
private void CreateAdornment() { var lines = view.VisualSnapshot.Lines; if (codeLocation == null) { return; } var startLine = lines.FirstOrDefault(a => a.LineNumber == codeLocation.From.Line - 1); var endLine = lines.FirstOrDefault(a => a.LineNumber == codeLocation.To.Line - 1); if (startLine == null || endLine == null) { return; } var startPosition = startLine.Start + codeLocation.From.Column - 1; var endPosition = endLine.Start + codeLocation.To.Column - 1; var span = new SnapshotSpan(view.TextSnapshot, Span.FromBounds(startPosition, endPosition)); try { layer.TextView.ViewScroller.EnsureSpanVisible(span, EnsureSpanVisibleOptions.AlwaysCenter); } catch (InvalidOperationException) { // Intentionally ignored. } var g = view.TextViewLines.GetMarkerGeometry(span); if (g != null) { var drawing = new GeometryDrawing(brush, pen, g); drawing.Freeze(); var drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); var image = new Image { Source = drawingImage }; // Align the image with the top of the bounds of the text geometry. Canvas.SetLeft(image, g.Bounds.Left); Canvas.SetTop(image, g.Bounds.Top); Canvas.SetLeft(achievementUiElement, g.Bounds.Right + 50); Canvas.SetTop(achievementUiElement, g.Bounds.Top); achievementUiElement.MouseDown += (sender, args) => Reset(); adornmentVisible = true; try { layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, image, (tag, element) => adornmentVisible = false); descriptionLayer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, achievementUiElement, null); } catch (ArgumentException) { // Intentionally ignored. } } }
private static void OnIsLoadingChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { FrameworkElementLoadingBehavior elBeh = obj as FrameworkElementLoadingBehavior; if (elBeh == null) { return; } FrameworkElement el = elBeh.AssociatedObject; if (el == null) { return; } AdornerLayer layer = AdornerLayer.GetAdornerLayer(el); if ((bool)args.NewValue) { if (elBeh.Decorator == null) { ScaleTransform scaleTransform = new ScaleTransform(0.5, 0.5); SkewTransform skewTransform = new SkewTransform(0, 0); RotateTransform rotateTransform = new RotateTransform(0); TranslateTransform translateTransform = new TranslateTransform(0, 0); TransformGroup group = new TransformGroup(); group.Children.Add(scaleTransform); group.Children.Add(skewTransform); group.Children.Add(rotateTransform); group.Children.Add(translateTransform); DoubleAnimation doubleAnimation = new DoubleAnimation(0, 359, new TimeSpan(0, 0, 0, 1)); doubleAnimation.RepeatBehavior = RepeatBehavior.Forever; rotateTransform.BeginAnimation(RotateTransform.AngleProperty, doubleAnimation); ResourceDictionary resourceDictionary = new ResourceDictionary(); resourceDictionary.Source = new Uri("Tum.PDE.ToolFramework.Modeling.Visualization;component/Controls/Loaders/ImageLoader.xaml", UriKind.Relative); DrawingImage img = resourceDictionary["ImageLoading"] as DrawingImage; img.Freeze(); Image imgControl = new Image(); imgControl.Source = img; imgControl.Width = 84; imgControl.Height = 84; imgControl.RenderTransformOrigin = new Point(0.5, 0.5); imgControl.RenderTransform = group; elBeh.Decorator = new DecoratorAdorner(el, imgControl); elBeh.Decorator.Width = 100; elBeh.Decorator.Height = 100; } layer.Add(elBeh.Decorator); } else { if (elBeh.Decorator != null) { layer.Remove(elBeh.Decorator); } } }
private void CreateVisual(CaretAdornmentData nodeData, int caretLineOffset, int caretOffset, IUserIdentity userIdentity) { if (View.IsClosed) { return; } if (RepoDocument != null && nodeData.RelativeToServerSource) { var remoteFileText = SourceControlRepo.GetRemoteFileLines(View.TextBuffer.GetTextDocumentFilePath()); if (remoteFileText != null) { string localFileText = View.TextSnapshot.GetText(); caretLineOffset = LineNumberTranslator.GetLineNumber(localFileText.Split(new[] { "\r\n" }, StringSplitOptions.None), remoteFileText, caretLineOffset, FileNumberBasis.Local); } } var caretLineNumber = View.TextSnapshot.GetLineNumberFromPosition(nodeData.SpanStart) + caretLineOffset; var caretPosition = View.TextSnapshot.GetLineFromLineNumber(Math.Min(caretLineNumber, View.TextSnapshot.LineCount - 1)).Start.Position + caretOffset; if (caretPosition < nodeData.NonWhiteSpaceStart) { caretPosition = nodeData.NonWhiteSpaceStart; } else if (caretPosition > nodeData.SpanEnd) { caretPosition = nodeData.SpanEnd; } var atEnd = caretPosition >= View.TextSnapshot.Length; var remoteCaretSpan = new SnapshotSpan(View.TextSnapshot, atEnd ? View.TextSnapshot.Length - 1 : caretPosition, 1); var onSameLineAsEnd = remoteCaretSpan.Start.GetContainingLine().LineNumber == View.TextSnapshot.GetLineNumberFromPosition(View.TextSnapshot.Length); Geometry characterGeometry = View.TextViewLines.IsValid ? View.TextViewLines.GetMarkerGeometry(remoteCaretSpan) : null; if (characterGeometry != null) { var caretGeometry = new LineGeometry(atEnd && onSameLineAsEnd ? characterGeometry.Bounds.TopRight : characterGeometry.Bounds.TopLeft, atEnd && onSameLineAsEnd ? characterGeometry.Bounds.BottomRight : characterGeometry.Bounds.BottomLeft); var drawing = new GeometryDrawing(null, UserColours.GetUserPen(userIdentity), caretGeometry); drawing.Freeze(); var drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); var image = new Image { Source = drawingImage, }; // Align the image with the top of the bounds of the text geometry var bounds = caretGeometry.Bounds; Canvas.SetLeft(image, bounds.Left); Canvas.SetTop(image, bounds.Top); Layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, remoteCaretSpan, null, image, null); FrameworkElement userControl = null; if (UserAvatars.ContainsKey(userIdentity.Id) && UserAvatars[userIdentity.Id].Count != 0) { userControl = UserAvatars[userIdentity.Id].Dequeue(); } if (TeamCodingPackage.Current.Settings.UserSettings.UserCodeDisplay == Options.UserSettings.UserDisplaySetting.Colour) { if (userControl == null) { userControl = new Border() { Tag = userIdentity.Id, Background = UserColours.GetUserBrush(userIdentity), CornerRadius = new CornerRadius(bounds.Height / 2 / 2) }; } userControl.Width = bounds.Height / 2; userControl.Height = bounds.Height / 2; Canvas.SetTop(userControl, bounds.Top - (userControl.Height * 0.75)); } else { if (userControl == null) { userControl = TeamCodingPackage.Current.UserImages.CreateUserIdentityControl(userIdentity); } userControl.Width = bounds.Height / 1.25f; userControl.Height = bounds.Height / 1.25f; Canvas.SetTop(userControl, bounds.Top - userControl.Height); } userControl.ToolTip = userIdentity.DisplayName ?? userIdentity.Id; Canvas.SetLeft(userControl, bounds.Left - userControl.Width / 2); Layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, remoteCaretSpan, null, userControl, AdornmentRemoved); } }
public static DrawingImage CreateImage(PointPattern[] pointPatterns, Size size, Color color) { if (pointPatterns == null) { return(null); } DrawingGroup drawingGroup = new DrawingGroup(); for (int i = 0; i < pointPatterns.Length; i++) { PathGeometry pathGeometry = new PathGeometry(); color.A = (byte)(0xFF - i * 0x55); SolidColorBrush brush = new SolidColorBrush(color); Pen drawingPen = new Pen(brush, size.Height / 20 + i * 1.5) { StartLineCap = PenLineCap.Round, EndLineCap = PenLineCap.Round }; if (pointPatterns[i].Points == null) { return(null); } for (int j = 0; j < pointPatterns[i].Points.Count; j++) { if (pointPatterns[i].Points[j].Count == 1) { Geometry ellipse = new EllipseGeometry(new Point(size.Width * j + size.Width / 2, size.Height / 2), drawingPen.Thickness / 2, drawingPen.Thickness / 2); pathGeometry.AddGeometry(ellipse); continue; } StreamGeometry sg = new StreamGeometry { FillRule = FillRule.EvenOdd }; using (StreamGeometryContext sgc = sg.Open()) { // Create new size object accounting for pen width Size szeAdjusted = new Size(size.Width - drawingPen.Thickness - 1, (size.Height - drawingPen.Thickness - 1)); Size scaledSize; Point[] scaledPoints = ScaleGesture(pointPatterns[i].Points[j], szeAdjusted.Width - 10, szeAdjusted.Height - 10, out scaledSize); // Define size that will mark the offset to center the gesture double iLeftOffset = (size.Width / 2) - (scaledSize.Width / 2); double iTopOffset = (size.Height / 2) - (scaledSize.Height / 2); Vector sizOffset = new Vector(iLeftOffset + j * size.Width, iTopOffset); sgc.BeginFigure(Point.Add(scaledPoints[0], sizOffset), false, false); foreach (Point p in scaledPoints) { sgc.LineTo(Point.Add(p, sizOffset), true, true); } DrawArrow(sgc, scaledPoints, sizOffset, drawingPen.Thickness); } sg.Freeze(); pathGeometry.AddGeometry(sg); } pathGeometry.Freeze(); GeometryDrawing drawing = new GeometryDrawing(null, drawingPen, pathGeometry); drawing.Freeze(); drawingGroup.Children.Add(drawing); } // myPath.Data = sg; drawingGroup.Freeze(); DrawingImage drawingImage = new DrawingImage(drawingGroup); drawingImage.Freeze(); return(drawingImage); }
public void Render() { try { double CanvasWidth = (ActualWidth - 24) * Zoom; double CanvasHeight = Height - 14; CanvasPlot.Children.Clear(); if (CanvasWidth <= 0 || CanvasHeight <= 0) { return; } #region Determine axis range ValueMin = double.MaxValue; ValueMax = -double.MaxValue; if (!double.IsNaN(AxisMin)) { ValueMin = AxisMin; } else if (Points != null && Points.Count > 0) { foreach (var point in Points) { if (!double.IsNaN(point.Value)) { ValueMin = Math.Min(ValueMin, point.Value); } } } else { ValueMin = 0; } if (!double.IsNaN(AxisMax)) { ValueMax = AxisMax; } else if (Points != null && Points.Count > 0 && Points.Any(v => !double.IsNaN(v.Value))) { foreach (var point in Points) { if (!double.IsNaN(point.Value)) { ValueMax = Math.Max(ValueMax, point.Value); } } } else { ValueMax = 1; } double Range = ValueMax - ValueMin; if (ValueMin == ValueMax) // Range = 0, probably only one point { ValueMax += 1; ValueMin -= 1; } else // Make sure there are a few pixels left to draw the points at the extremes { if (double.IsNaN(AxisMax)) { ValueMax += Range / CanvasHeight * PointRadius; } if (double.IsNaN(AxisMin)) { ValueMin -= Range / CanvasHeight * PointRadius; } } Range = ValueMax - ValueMin; Dispatcher.Invoke(() => { string FloatFormat = "F0"; if (Math.Max(ValueMax, ValueMin) < 100) { FloatFormat = "F1"; } if (Math.Max(ValueMax, ValueMin) < 10) { FloatFormat = "F2"; } TextLineBottom.Text = ValueMin.ToString(FloatFormat, CultureInfo.InvariantCulture); TextLineCenter.Text = ((ValueMin + ValueMax) * 0.5).ToString(FloatFormat, CultureInfo.InvariantCulture); TextLineTop.Text = ValueMax.ToString(FloatFormat, CultureInfo.InvariantCulture); }); #endregion #region Adjust range highlight double RangeHighlightClampedMin = Math.Max(ValueMin, RangeHighlightMin); double RangeHighlightClampedMax = Math.Min(ValueMax, RangeHighlightMax); PanelRangeHighlight.Margin = new Thickness(0, 7 + (ValueMax - RangeHighlightClampedMax) / Range * CanvasHeight, 0, 0); PanelRangeHighlight.Height = Math.Max(0, RangeHighlightClampedMax - RangeHighlightClampedMin) / Range * CanvasHeight; #endregion if (Range < 0 || Points == null || Points.Count == 0) { ImagePlot.Source = null; return; } float[] HistogramBins = new float[50]; DrawingGroup DGroup = new DrawingGroup(); using (DrawingContext DContext = DGroup.Open()) { DContext.PushClip(new RectangleGeometry(new Rect(new Size(CanvasWidth, CanvasHeight)))); Pen OutlinePen = new Pen(Brushes.Transparent, 0); OutlinePen.Freeze(); SolidColorBrush BackgroundBrush = new SolidColorBrush(Colors.Transparent); BackgroundBrush.Freeze(); DContext.DrawRectangle(BackgroundBrush, OutlinePen, new Rect(new Size(CanvasWidth, CanvasHeight))); SolidColorBrush[] ColorBrushes = PointColors.Count > 0 ? PointColors.Select(c => { SolidColorBrush Brush = new SolidColorBrush(Color.FromArgb(255, c.R, c.G, c.B)); Brush.Freeze(); return(Brush); }).ToArray() : new[] { new SolidColorBrush(Color.FromArgb(150, Colors.DeepSkyBlue.R, Colors.DeepSkyBlue.G, Colors.DeepSkyBlue.B)) }; StepX = (CanvasWidth - PointRadius * 2) / Points.Count; OffsetX = StepX / 2 + PointRadius; StepY = CanvasHeight / Range; PointCenters = new System.Windows.Point[Points.Count]; for (int i = 0; i < Points.Count; i++) { if (double.IsNaN(Points[i].Value)) { continue; } double X = i * StepX + OffsetX; double Y = (ValueMax - Points[i].Value) * StepY; DContext.DrawEllipse(ColorBrushes[Points[i].ColorID], OutlinePen, new System.Windows.Point(X, Y), PointRadius, PointRadius); PointCenters[i] = new System.Windows.Point(X, Y); HistogramBins[Math.Max(0, Math.Min(HistogramBins.Length - 1, (int)((Points[i].Value - ValueMin) / Range * (HistogramBins.Length - 1) + 0.5)))]++; } } DrawingImage Plot = new DrawingImage(DGroup); Plot.Freeze(); Dispatcher.Invoke(() => ImagePlot.Source = Plot); Dispatcher.Invoke(() => { float[] HistogramConv = new float[HistogramBins.Length]; float[] ConvKernel = { 0.11f, 0.37f, 0.78f, 1f, 0.78f, 0.37f, 0.11f }; for (int i = 0; i < HistogramBins.Length; i++) { float Sum = 0; float Samples = 0; for (int j = 0; j < ConvKernel.Length; j++) { int ij = i - 3 + j; if (ij < 0 || ij >= HistogramBins.Length) { continue; } Sum += ConvKernel[j] * HistogramBins[ij]; Samples += ConvKernel[j]; } HistogramConv[i] = Sum / Samples; } float HistogramMax = MathHelper.Max(HistogramConv); if (HistogramMax > 0) { HistogramConv = HistogramConv.Select(v => v / HistogramMax * 16).ToArray(); } Polygon HistogramPolygon = new Polygon() { Stroke = Brushes.Transparent, Fill = Brushes.Gray, Opacity = 0.15 }; PointCollection HistogramPoints = new PointCollection(HistogramConv.Length); HistogramPoints.Add(new System.Windows.Point(16, 0)); HistogramPoints.Add(new System.Windows.Point(16, CanvasHeight)); for (int i = 0; i < HistogramConv.Length; i++) { double X = 15 - HistogramConv[i]; double Y = CanvasHeight - (i / (float)(HistogramConv.Length - 1) * CanvasHeight); HistogramPoints.Add(new System.Windows.Point(X, Y)); } HistogramPolygon.Points = HistogramPoints; CanvasHistogram.Children.Clear(); CanvasHistogram.Children.Add(HistogramPolygon); Canvas.SetRight(HistogramPolygon, 0); }); } catch { } }
public static ImageSource GetImage(double scale, bool isForY) { double height = 1; double width = 1; double lineWidth = 0.05; var group = new DrawingGroup(); // draws a transparent outline to fix the borders var outlineDrawing = new GeometryDrawing { Geometry = new RectangleGeometry(new Rect(-lineWidth, -lineWidth, width + lineWidth, height + lineWidth)), Pen = new Pen(Brushes.Transparent, 0) }; group.Children.Add(outlineDrawing); var absscale = Math.Abs(scale); if (absscale == 1) { var drawing1 = new GeometryDrawing { Geometry = new EllipseGeometry(new Point(width / 2, height / 2), width / 4, height / 4) }; if (scale > 0) { drawing1.Brush = new RadialGradientBrush(Color.FromRgb(204, 204, 255), Color.FromRgb(100, 100, 255)); } else { drawing1.Brush = new RadialGradientBrush(Color.FromRgb(100, 100, 255), Color.FromRgb(204, 204, 255)); } group.Children.Add(drawing1); drawing1 = new GeometryDrawing { Geometry = new LineGeometry(new Point(0, height / 2), new Point(width, height / 2)), Pen = new Pen(Brushes.Black, lineWidth) }; group.Children.Add(drawing1); drawing1 = new GeometryDrawing { Geometry = new LineGeometry(new Point(width / 2, 0), new Point(width / 2, height)), Pen = new Pen(Brushes.Black, lineWidth) }; group.Children.Add(drawing1); } else { var drawing1 = new GeometryDrawing(); if (absscale > 2) { drawing1.Geometry = new EllipseGeometry(new Point(width / 2, height / 2), (width / 2), (height / 2) / absscale); } else if (absscale > 1) { drawing1.Geometry = new EllipseGeometry(new Point(width / 2, height / 2), (width / 4) * absscale, (height / 4)); } else if (absscale > 0.5) { drawing1.Geometry = new EllipseGeometry(new Point(width / 2, height / 2), (width / 4), (height / 4) / absscale); } else if (absscale > 0) { drawing1.Geometry = new EllipseGeometry(new Point(width / 2, height / 2), (width / 2) * absscale, (height / 2)); } // drawing1.Brush = new RadialGradientBrush(Color.FromRgb(204, 204, 255), Color.FromRgb(100, 100, 255)); if (scale > 0) { drawing1.Brush = new LinearGradientBrush(Color.FromRgb(204, 204, 255), Color.FromRgb(100, 100, 255), 0); } else { drawing1.Brush = new LinearGradientBrush(Color.FromRgb(100, 100, 255), Color.FromRgb(204, 204, 255), 0); } group.Children.Add(drawing1); drawing1 = new GeometryDrawing { Geometry = new LineGeometry(new Point(0, height / 2), new Point(width, height / 2)), Pen = new Pen(Brushes.Black, lineWidth) }; group.Children.Add(drawing1); Point d11, d12, d13; Point d21, d22, d23; if (absscale > 1) { // triangles pointing outside; d11 = new Point(0, height / 2); d12 = new Point(width / 4, height / 2 + height / 8); d13 = new Point(width / 4, height / 2 - height / 8); d21 = new Point(width, height / 2); d22 = new Point(width - width / 4, height / 2 + height / 8); d23 = new Point(width - width / 4, height / 2 - height / 8); } else { // triangles pointing inside d11 = new Point(width / 4, height / 2); d12 = new Point(0, height / 2 + height / 8); d13 = new Point(0, height / 2 - height / 8); d21 = new Point(width - width / 4, height / 2); d22 = new Point(width, height / 2 + height / 8); d23 = new Point(width, height / 2 - height / 8); } // now adjust the triangles a little if (absscale > 2) { // nothing to do here, the triangles are already max outside } else if (absscale > 1) { double offs = width / 2 - absscale * (width / 4); d11.X += offs; d12.X += offs; d13.X += offs; d21.X -= offs; d22.X -= offs; d23.X -= offs; } else if (absscale > 0.5) { // nothing to do here, the triangles are already max outside } else if (absscale > 0) { double offs = width / 4 - absscale * width / 2; d11.X += offs; d12.X += offs; d13.X += offs; d21.X -= offs; d22.X -= offs; d23.X -= offs; } var fig1 = new PathFigure(d11, new PathSegment[] { new LineSegment(d12, false), new LineSegment(d13, false) }, true); var fig2 = new PathFigure(d21, new PathSegment[] { new LineSegment(d22, false), new LineSegment(d23, false) }, true); drawing1 = new GeometryDrawing { Geometry = new PathGeometry(new PathFigure[] { fig1, fig2 }), Brush = Brushes.Black }; group.Children.Add(drawing1); } if (isForY) { group.Transform = new RotateTransform(90, width / 2, height / 2); } var geometryImage = new DrawingImage(group); // Freeze the DrawingImage for performance benefits. geometryImage.Freeze(); return(geometryImage); }
private static ImageSource GetImage(string fontFamilyName) { const double height = 1; const double width = 2; const double fontSize = 1; var drawingGroup = new DrawingGroup(); var outerGeometry = new RectangleGeometry(new Rect(0, 0, width, height)); var geometryDrawing = new GeometryDrawing() { Geometry = outerGeometry }; geometryDrawing.Pen = new Pen(Brushes.Transparent, 0); drawingGroup.Children.Add(geometryDrawing); var fontX = WpfFontManager.GetFontX(fontFamilyName, 12, Altaxo.Drawing.FontXStyle.Regular); Typeface typeface = WpfFontManager.ToWpf(fontX); if (!typeface.TryGetGlyphTypeface(out var glyphTypeFace)) { glyphTypeFace = null; } if (null != glyphTypeFace) { var glyphRun = new GlyphRun(); ((System.ComponentModel.ISupportInitialize)glyphRun).BeginInit(); glyphRun.GlyphTypeface = glyphTypeFace; glyphRun.FontRenderingEmSize = fontSize; var textChars = GetDisplayText(glyphTypeFace); glyphRun.Characters = textChars; ushort[] glyphIndices = new ushort[textChars.Length]; double[] advanceWidths = new double[textChars.Length]; for (int i = 0; i < textChars.Length; ++i) { int codePoint = textChars[i]; ushort glyphIndex = glyphTypeFace.CharacterToGlyphMap[codePoint]; double glyphWidht = glyphTypeFace.AdvanceWidths[glyphIndex]; glyphIndices[i] = glyphIndex; advanceWidths[i] = glyphWidht * fontSize; } if (glyphIndices.Length > 0) { glyphRun.GlyphIndices = glyphIndices; glyphRun.AdvanceWidths = advanceWidths; glyphRun.BaselineOrigin = new Point(0, glyphTypeFace.Baseline * fontSize); ((System.ComponentModel.ISupportInitialize)glyphRun).EndInit(); var glyphRunDrawing = new GlyphRunDrawing(Brushes.Black, glyphRun); drawingGroup.Children.Add(glyphRunDrawing); } } drawingGroup.ClipGeometry = outerGeometry; var geometryImage = new DrawingImage(drawingGroup); // Freeze the DrawingImage for performance benefits. geometryImage.Freeze(); return(geometryImage); }
private void DrawCaret(Selection selection) { SnapshotSpan span; Geometry geometry; // EOF edge case fix if (selection.Caret.GetPosition(Snapshot) == Snapshot.Length) { span = new SnapshotSpan(selection.Caret.GetPoint(Snapshot).Subtract(1), 1); var textView = view.TextViewLines[view.TextViewLines.Count - 1]; var rect = new Rect( textView.Right, textView.Bottom - view.FormattedLineSource.LineHeight, view.FormattedLineSource.ColumnWidth, view.FormattedLineSource.LineHeight); geometry = new RectangleGeometry(rect); } else { span = new SnapshotSpan(selection.Caret.GetPoint(Snapshot), 1); geometry = view.TextViewLines.GetMarkerGeometry(span); } UIElement element = null; double virtualSpace = 0; if (geometry != null) { if (view.Caret.OverwriteMode && !selection.IsSelection()) { var drawing = new GeometryDrawing(insertionBrush, new Pen(), geometry); drawing.Freeze(); var drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); element = new Image { Source = drawingImage }; } else { element = new Rectangle { Fill = caretBrush, Width = view.FormattedLineSource.ColumnWidth / 6, Height = view.FormattedLineSource.LineHeight, Margin = new Thickness(0, 0, 0, 0), }; virtualSpace = selection.VirtualSpaces * view.TextViewLines[0].VirtualSpaceWidth; } } if (element != null) { Canvas.SetLeft(element, geometry.Bounds.Left + virtualSpace); Canvas.SetTop(element, geometry.Bounds.Top); layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, Vsix.Name, element, null); } }
private static DrawingImage GetMapImageWithDrawnImageAtPoint(bool big_gui, object[] array_db_values, EDayTime day_time, bool is_highlighted, BitmapSource image_to_draw, Point?where_to_draw) { string[] strMapRows = array_db_values[(int)EDBMapsTableColumns.eStrDef].ToString().Split('\n'); SizeTile sizeTile = big_gui ? HexTypes.HexTypes.SizeBigTile : HexTypes.HexTypes.SizeSmallTile; // Calculation by trial and error of the formula to draw the tiles on map double nStartYMultiplier = sizeTile.Height * 0.25; double nStartXOddOffset = sizeTile.Width * 0.8; double nStartXMultiplier = 2 * nStartXOddOffset; DrawingVisual visual = new DrawingVisual(); using (DrawingContext drawingContext = visual.RenderOpen()) { for (int nRows = 0; nRows < strMapRows.Length; nRows++) { // Calculation by trial and error of the formula to draw the tiles on map double nStartY = nRows * nStartYMultiplier; string[] strMapColumns = strMapRows[nRows].Split(','); bool bIsRowOdd = nRows % 2 != 0; for (int nColumn = 0; nColumn < strMapColumns.Length; nColumn++) { int nHextype = Convert.ToInt32(strMapColumns[nColumn]); BitmapSource tile = HexTypes.HexTypes.GetCorrectTileForDrawing(nHextype, big_gui, day_time, is_highlighted); // Calculation by trial and error of the formula to draw the tiles on map double nStartX = (nColumn * nStartXMultiplier); if (bIsRowOdd) { nStartX += nStartXOddOffset; } drawingContext.DrawImage(tile, new Rect(nStartX, nStartY, tile.PixelWidth, tile.PixelHeight)); } } // As a final step let's see if there's an image to draw if (image_to_draw != null) { drawingContext.DrawImage(image_to_draw, new Rect(where_to_draw.Value.X, where_to_draw.Value.Y, image_to_draw.PixelWidth, image_to_draw.PixelHeight)); } // Below code might be useful to save things to a file, and since it took me a long time to find it, I will maintain this here for now in case I will need it later //drawingContext.DrawImage(tile, new Rect(0, 0, tile.PixelWidth, tile.PixelHeight)); ////Brush brush = new Brush() //SolidColorBrush semiTransBrush = new SolidColorBrush(Color.FromArgb(128, 0, 0, 0)); //drawingContext.DrawRoundedRectangle(semiTransBrush, null, new Rect(10, 34, 80, 22), 5, 5); //FormattedText text = new FormattedText("Random", CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface("Segoe UI"), 20.0, Brushes.Red); //drawingContext.DrawText(text, new Point(14, 30)); } //RenderTargetBitmap mergedImage = new RenderTargetBitmap(nTotalWidth, nTotalHeight, 96, 96, PixelFormats.Pbgra32); //mergedImage.Render(visual); //BitmapSource final = App.ConvertImageDpi(mergedImage, App.I.DpiX, App.I.DpiY); //PngBitmapEncoder encoder = new PngBitmapEncoder(); //encoder.Frames.Add(BitmapFrame.Create(mergedImage)); //using (FileStream file = File.OpenWrite("c:\\teste\\cenas.png")) //{ // encoder.Save(file); //} DrawingImage finalMap = new DrawingImage(visual.Drawing); finalMap.Freeze(); return(finalMap); }
TreeViewItem ProcessPlacemark(Placemark placemark) { string name = placemark.Name; StackPanel pan = new StackPanel(); pan.Orientation = System.Windows.Controls.Orientation.Horizontal; SharpKml.Dom.Style style = KmlFileHelper.FindStyleByStyleURL(_kmlFile, placemark.StyleUrl.OriginalString); if (placemark.Geometry is SharpKml.Dom.Point) { Uri uri = null; if (style != null && style.Icon != null && style.Icon.Icon != null && style.Icon.Icon.Href != null) { uri = style.Icon.Icon.Href; } Image image = new Image(); image.Height = 16; image.Source = _imagesFromUri.FindImageByUri(uri); pan.Children.Add(image); } else if (placemark.Geometry is LineString) { GeometryGroup Lines = new GeometryGroup(); Color32 styleColor = new Color32(); if (style != null && style.Line != null && style.Line.Color != null) { styleColor = (Color32)style.Line.Color; } // Line LineGeometry line = new LineGeometry(); line.StartPoint = new System.Windows.Point(0, 5); line.EndPoint = new System.Windows.Point(10, 5); Lines.Children.Add(line); GeometryDrawing MyGeometryDrawing = new GeometryDrawing(); MyGeometryDrawing.Geometry = Lines; MyGeometryDrawing.Brush = new SolidColorBrush(Color.FromArgb(styleColor.Alpha, styleColor.Red, styleColor.Green, styleColor.Blue)); MyGeometryDrawing.Pen = new Pen(MyGeometryDrawing.Brush, 1); DrawingImage drawingImage = new DrawingImage(MyGeometryDrawing); drawingImage.Freeze(); Image image = new Image(); image.Height = 16; image.Width = 16; image.Source = drawingImage; pan.Children.Add(image); } TextBlock textBlock = new TextBlock(); textBlock.Text = name; textBlock.Margin = new System.Windows.Thickness(4, 0, 0, 0); pan.Children.Add(textBlock); KMLFeatureTreeViewItem item = new KMLFeatureTreeViewItem() { Header = pan, Feature = placemark }; return(item); }
public static Image drawingSawtoothWave() { PathSegmentCollection pathSegmentCollection = new PathSegmentCollection(); PathFigureCollection segmentPathFigureCollection = new PathFigureCollection(); PathFigure segmentPathFigure = new PathFigure(); segmentPathFigure = new PathFigure(); segmentPathFigure.IsFilled = false; segmentPathFigure.IsClosed = false; Point StartPoint = new Point(0, 20); Point point1 = new Point(20, 0); Point point2 = new Point(20, 20); segmentPathFigure.StartPoint = StartPoint; LineSegment lineSegment1 = new LineSegment(point1, true); LineSegment lineSegment2 = new LineSegment(point2, true); pathSegmentCollection.Add(lineSegment1); pathSegmentCollection.Add(lineSegment2); segmentPathFigure.Segments = pathSegmentCollection; segmentPathFigureCollection.Add(segmentPathFigure); PathGeometry segmentPathGeometry = new PathGeometry(); segmentPathGeometry.Figures = segmentPathFigureCollection; // // Create the Geometry to draw. // GeometryGroup geometryGroup = new GeometryGroup(); geometryGroup.Children.Add(segmentPathGeometry); // // Create a GeometryDrawing. // GeometryDrawing aGeometryDrawing = new GeometryDrawing(); aGeometryDrawing.Geometry = geometryGroup; // Paint the drawing with a gradient. aGeometryDrawing.Brush = new LinearGradientBrush( Colors.Blue, Color.FromRgb(204, 204, 255), new Point(0, 0), new Point(1, 1)); // Outline the drawing with a solid color. aGeometryDrawing.Pen = new Pen(Brushes.Black, 2); // // Use a DrawingImage and an Image control // to display the drawing. // DrawingImage geometryImage = new DrawingImage(aGeometryDrawing); // Freeze the DrawingImage for performance benefits. geometryImage.Freeze(); Image anImage = new Image(); anImage.Source = geometryImage; anImage.HorizontalAlignment = HorizontalAlignment.Left; return(anImage); }
public ClipExample() { // // Create several GeometryDrawing objects. // // Create a rectangle. GeometryDrawing drawing1 = new GeometryDrawing( Brushes.Pink, null, new RectangleGeometry(new Rect(0, 0, 50, 85)) ); // // Create a polygon. // PathFigure pLineFigure = new PathFigure(); pLineFigure.StartPoint = new Point(25, 25); PolyLineSegment pLineSegment = new PolyLineSegment(); pLineSegment.Points.Add(new Point(0, 50)); pLineSegment.Points.Add(new Point(25, 75)); pLineSegment.Points.Add(new Point(50, 50)); pLineSegment.Points.Add(new Point(25, 25)); pLineSegment.Points.Add(new Point(25, 0)); pLineFigure.Segments.Add(pLineSegment); PathGeometry pGeometry = new PathGeometry(); pGeometry.Figures.Add(pLineFigure); GeometryDrawing drawing2 = new GeometryDrawing( Brushes.Lime, new Pen(Brushes.Black, 10), pGeometry ); // // Create a circle. // GeometryDrawing drawing3 = new GeometryDrawing( Brushes.Lime, new Pen(Brushes.Black, 2), new EllipseGeometry(new Point(10, 10), 5, 5) ); // Create the DrawingGroup and add the // geometry drawings. DrawingGroup aDrawingGroup = new DrawingGroup(); aDrawingGroup.Children.Add(drawing1); aDrawingGroup.Children.Add(drawing2); aDrawingGroup.Children.Add(drawing3); // // Create an EllipseGeometry and use it to // clip the DrawingGroup. // EllipseGeometry clipGeometry = new EllipseGeometry(new Point(25, 50), 25, 50); aDrawingGroup.ClipGeometry = clipGeometry; // Use an Image control and a DrawingImage to // display the drawing. DrawingImage aDrawingImage = new DrawingImage(aDrawingGroup); // Freeze the DrawingImage for performance benefits. aDrawingImage.Freeze(); Image anImage = new Image(); anImage.Source = aDrawingImage; anImage.Stretch = Stretch.None; anImage.HorizontalAlignment = HorizontalAlignment.Left; // Create a border around the images and add it to the // page. Border imageBorder = new Border(); imageBorder.BorderBrush = Brushes.Gray; imageBorder.BorderThickness = new Thickness(1); imageBorder.VerticalAlignment = VerticalAlignment.Top; imageBorder.HorizontalAlignment = HorizontalAlignment.Left; imageBorder.Margin = new Thickness(20); imageBorder.Child = anImage; this.Background = Brushes.White; this.Margin = new Thickness(20); this.Content = imageBorder; }
public DrawingGroupGuidelineSetExample() { // // Create a DrawingGroup // that has no guideline set // GeometryDrawing drawing1 = new GeometryDrawing( Brushes.Black, null, new RectangleGeometry(new Rect(0, 20, 30, 80)) ); GeometryGroup whiteRectangles = new GeometryGroup(); whiteRectangles.Children.Add(new RectangleGeometry(new Rect(5.5, 25, 20, 20))); whiteRectangles.Children.Add(new RectangleGeometry(new Rect(5.5, 50, 20, 20))); whiteRectangles.Children.Add(new RectangleGeometry(new Rect(5.5, 75, 20, 20))); GeometryDrawing drawing2 = new GeometryDrawing( Brushes.White, null, whiteRectangles ); // Create a DrawingGroup DrawingGroup drawingGroupWithoutGuidelines = new DrawingGroup(); drawingGroupWithoutGuidelines.Children.Add(drawing1); drawingGroupWithoutGuidelines.Children.Add(drawing2); // Use an Image control and a DrawingImage to // display the drawing. DrawingImage drawingImage01 = new DrawingImage(drawingGroupWithoutGuidelines); // Freeze the DrawingImage for performance benefits. drawingImage01.Freeze(); Image image01 = new Image(); image01.Source = drawingImage01; image01.Stretch = Stretch.None; image01.HorizontalAlignment = HorizontalAlignment.Left; image01.Margin = new Thickness(10); // // Create another DrawingGroup and apply // a blur effect to it. // // Create a clone of the first DrawingGroup. DrawingGroup drawingGroupWithGuidelines = drawingGroupWithoutGuidelines.Clone(); // Create a guideline set. GuidelineSet guidelines = new GuidelineSet(); guidelines.GuidelinesX.Add(5.5); guidelines.GuidelinesX.Add(25.5); guidelines.GuidelinesY.Add(25); guidelines.GuidelinesY.Add(50); guidelines.GuidelinesY.Add(75); // Apply it to the drawing group. drawingGroupWithGuidelines.GuidelineSet = guidelines; // Use another Image control and DrawingImage // to display the drawing. DrawingImage drawingImage02 = new DrawingImage(drawingGroupWithGuidelines); // Freeze the DrawingImage for performance benefits. drawingImage02.Freeze(); Image image02 = new Image(); image02.Source = drawingImage02; image02.Stretch = Stretch.None; image02.HorizontalAlignment = HorizontalAlignment.Left; image02.Margin = new Thickness(50, 10, 10, 10); StackPanel mainPanel = new StackPanel(); mainPanel.Orientation = Orientation.Horizontal; mainPanel.HorizontalAlignment = HorizontalAlignment.Left; mainPanel.Margin = new Thickness(20); mainPanel.Children.Add(image01); mainPanel.Children.Add(image02); // // Use a DrawingBrush to create a grid background. // GeometryDrawing backgroundRectangleDrawing = new GeometryDrawing( Brushes.White, null, new RectangleGeometry(new Rect(0, 0, 1, 1)) ); PolyLineSegment backgroundLine1 = new PolyLineSegment(); backgroundLine1.Points.Add(new Point(1, 0)); backgroundLine1.Points.Add(new Point(1, 0.1)); backgroundLine1.Points.Add(new Point(0, 0.1)); PathFigure line1Figure = new PathFigure(); line1Figure.Segments.Add(backgroundLine1); PathGeometry backgroundLine1Geometry = new PathGeometry(); backgroundLine1Geometry.Figures.Add(line1Figure); GeometryDrawing backgroundLineDrawing1 = new GeometryDrawing( new SolidColorBrush(Color.FromArgb(255, 204, 204, 255)), null, backgroundLine1Geometry ); PolyLineSegment backgroundLine2 = new PolyLineSegment(); backgroundLine2.Points.Add(new Point(0, 1)); backgroundLine2.Points.Add(new Point(0.1, 1)); backgroundLine2.Points.Add(new Point(0.1, 0)); PathFigure line2Figure = new PathFigure(); line2Figure.Segments.Add(backgroundLine2); PathGeometry backgroundLine2Geometry = new PathGeometry(); backgroundLine2Geometry.Figures.Add(line2Figure); GeometryDrawing backgroundLineDrawing2 = new GeometryDrawing( new SolidColorBrush(Color.FromArgb(255, 204, 204, 255)), null, backgroundLine2Geometry ); DrawingGroup backgroundGroup = new DrawingGroup(); backgroundGroup.Children.Add(backgroundRectangleDrawing); backgroundGroup.Children.Add(backgroundLineDrawing1); backgroundGroup.Children.Add(backgroundLineDrawing2); DrawingBrush gridPatternBrush = new DrawingBrush(backgroundGroup); gridPatternBrush.Viewport = new Rect(0, 0, 10, 10); gridPatternBrush.ViewportUnits = BrushMappingMode.Absolute; gridPatternBrush.TileMode = TileMode.Tile; gridPatternBrush.Freeze(); Border mainBorder = new Border(); mainBorder.Background = gridPatternBrush; mainBorder.BorderThickness = new Thickness(1); mainBorder.BorderBrush = Brushes.Gray; mainBorder.HorizontalAlignment = HorizontalAlignment.Left; mainBorder.VerticalAlignment = VerticalAlignment.Top; mainBorder.Margin = new Thickness(20); mainBorder.Child = mainPanel; // // Add the items to the page. // this.Content = mainBorder; this.Background = Brushes.White; }
public GlyphRunDrawingExample() { // <SnippetGlyphRunDrawingExampleInline> GlyphRun theGlyphRun = new GlyphRun( new GlyphTypeface(new Uri(@"C:\WINDOWS\Fonts\TIMES.TTF")), 0, false, 13.333333333333334, new ushort[] { 43, 72, 79, 79, 82, 3, 58, 82, 85, 79, 71 }, new Point(0, 12.29), new double[] { 9.62666666666667, 7.41333333333333, 2.96, 2.96, 7.41333333333333, 3.70666666666667, 12.5866666666667, 7.41333333333333, 4.44, 2.96, 7.41333333333333 }, null, null, null, null, null, null ); GlyphRunDrawing gDrawing = new GlyphRunDrawing(Brushes.Black, theGlyphRun); // </SnippetGlyphRunDrawingExampleInline> // // Use a DrawingImage and an Image control // to display the drawing. // DrawingImage theDrawingImage = new DrawingImage(gDrawing); // Freeze the DrawingImage for performance benefits. theDrawingImage.Freeze(); Image anImage = new Image(); anImage.Source = theDrawingImage; anImage.Stretch = Stretch.None; anImage.HorizontalAlignment = HorizontalAlignment.Left; // // Place the image inside a border and // add it to the page. // Border exampleBorder = new Border(); exampleBorder.Child = anImage; exampleBorder.BorderBrush = Brushes.Gray; exampleBorder.BorderThickness = new Thickness(1); exampleBorder.HorizontalAlignment = HorizontalAlignment.Left; exampleBorder.VerticalAlignment = VerticalAlignment.Top; exampleBorder.Margin = new Thickness(10); this.Margin = new Thickness(20); this.Background = Brushes.White; this.Content = exampleBorder; }
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; }
public VideoDrawingExample() { // <SnippetVideoDrawingExampleInline> // // Create a VideoDrawing. // // <SnippetVideoDrawingExampleInline1> MediaPlayer player = new MediaPlayer(); // </SnippetVideoDrawingExampleInline1> // <SnippetVideoDrawingExampleInline2> player.Open(new Uri(@"sampleMedia\xbox.wmv", UriKind.Relative)); // </SnippetVideoDrawingExampleInline2> // <SnippetVideoDrawingExampleInline3> VideoDrawing aVideoDrawing = new VideoDrawing(); // </SnippetVideoDrawingExampleInline3> // <SnippetVideoDrawingExampleInline4> aVideoDrawing.Rect = new Rect(0, 0, 100, 100); // </SnippetVideoDrawingExampleInline4> // <SnippetVideoDrawingExampleInline5> aVideoDrawing.Player = player; // </SnippetVideoDrawingExampleInline5> // <SnippetVideoDrawingExampleInline6> // Play the video once. player.Play(); // </SnippetVideoDrawingExampleInline6> // </SnippetVideoDrawingExampleInline> // <SnippetRepeatingVideoDrawingExampleInline> // // Create a VideoDrawing that repeats. // // <SnippetRepeatingVideoDrawingExampleInline1> // Create a MediaTimeline. MediaTimeline mTimeline = new MediaTimeline(new Uri(@"sampleMedia\xbox.wmv", UriKind.Relative)); // Set the timeline to repeat. mTimeline.RepeatBehavior = RepeatBehavior.Forever; // </SnippetRepeatingVideoDrawingExampleInline1> // <SnippetRepeatingVideoDrawingExampleInline2> // Create a clock from the MediaTimeline. MediaClock mClock = mTimeline.CreateClock(); // </SnippetRepeatingVideoDrawingExampleInline2> // <SnippetRepeatingVideoDrawingExampleInline3> MediaPlayer repeatingVideoDrawingPlayer = new MediaPlayer(); repeatingVideoDrawingPlayer.Clock = mClock; // </SnippetRepeatingVideoDrawingExampleInline3> // <SnippetRepeatingVideoDrawingExampleInline4> VideoDrawing repeatingVideoDrawing = new VideoDrawing(); repeatingVideoDrawing.Rect = new Rect(150, 0, 100, 100); repeatingVideoDrawing.Player = repeatingVideoDrawingPlayer; // </SnippetRepeatingVideoDrawingExampleInline4> // </SnippetRepeatingVideoDrawingExampleInline> // Create a DrawingGroup to combine the drawings. DrawingGroup videoDrawings = new DrawingGroup(); videoDrawings.Children.Add(aVideoDrawing); videoDrawings.Children.Add(repeatingVideoDrawing); // // Use a DrawingImage and an Image control // to display the drawing. // DrawingImage exampleDrawingImage = new DrawingImage(videoDrawings); // Freeze the DrawingImage for performance benefits. exampleDrawingImage.Freeze(); Image anImage = new Image(); anImage.Source = exampleDrawingImage; anImage.Stretch = Stretch.None; anImage.HorizontalAlignment = HorizontalAlignment.Left; // // Place the image inside a border and // add it to the page. // Border exampleBorder = new Border(); exampleBorder.Child = anImage; exampleBorder.BorderBrush = Brushes.Gray; exampleBorder.BorderThickness = new Thickness(1); exampleBorder.HorizontalAlignment = HorizontalAlignment.Left; exampleBorder.VerticalAlignment = VerticalAlignment.Top; exampleBorder.Margin = new Thickness(10); this.Margin = new Thickness(20); this.Background = Brushes.White; this.Content = exampleBorder; }
private void loadWaveForm() { //DrawingGroup dGroup = VisualTreeHelper.GetDrawing(WaveFormCanvas); bool wasPlaying = (m_Player.State == AudioPlayerState.Playing); if (m_Player.State != AudioPlayerState.NotReady) { if (wasPlaying) { m_Player.Pause(); } } if (mCurrentAudioStreamProvider() == null) { return; } if (m_pcmFormat == null) { m_FilePlayStream.Position = 0; m_FilePlayStream.Seek(0, SeekOrigin.Begin); m_pcmFormat = PCMDataInfo.ParseRiffWaveHeader(m_FilePlayStream); m_StreamRiffHeaderEndPos = m_FilePlayStream.Position; } else { m_FilePlayStream.Position = m_StreamRiffHeaderEndPos; m_FilePlayStream.Seek(m_StreamRiffHeaderEndPos, SeekOrigin.Begin); } if (m_pcmFormat.BitDepth != 16) { return; } if (m_pcmFormat.NumberOfChannels == 1) { PeakOverloadLabelCh2.Visibility = Visibility.Collapsed; } else { PeakOverloadLabelCh2.Visibility = Visibility.Visible; } ushort frameSize = (ushort)(m_pcmFormat.NumberOfChannels * m_pcmFormat.BitDepth / 8); double samplesPerPixel = Math.Ceiling(m_pcmFormat.DataLength / (double)frameSize / WaveFormCanvas.ActualWidth * m_pcmFormat.NumberOfChannels); m_bytesPerPixel = samplesPerPixel * frameSize / m_pcmFormat.NumberOfChannels; byte[] bytes = new byte[(int)m_bytesPerPixel]; short[] samples = new short[(int)samplesPerPixel]; StreamGeometry geometryCh1 = new StreamGeometry(); StreamGeometryContext sgcCh1 = geometryCh1.Open(); StreamGeometry geometryCh2 = null; StreamGeometryContext sgcCh2 = null; if (m_pcmFormat.NumberOfChannels > 1) { geometryCh2 = new StreamGeometry(); sgcCh2 = geometryCh2.Open(); } double height = WaveFormImage.Height; if (m_pcmFormat.NumberOfChannels > 1) { height /= 2; } for (double x = 0; x < WaveFormImage.Width; ++x) { int read = m_FilePlayStream.Read(bytes, 0, (int)m_bytesPerPixel); if (read <= 0) { continue; } Buffer.BlockCopy(bytes, 0, samples, 0, read); short min = short.MaxValue; short max = short.MinValue; for (int channel = 0; channel < m_pcmFormat.NumberOfChannels; channel++) { int limit = (int)Math.Ceiling(read / (float)frameSize); for (int i = channel; i < limit; i += m_pcmFormat.NumberOfChannels) { if (samples[i] < min) { min = samples[i]; } if (samples[i] > max) { max = samples[i]; } } double y1 = height - ((min - short.MinValue) * height) / ushort.MaxValue; if (channel == 0) { sgcCh1.BeginFigure(new Point(x, y1), false, false); } else { y1 += height; sgcCh2.BeginFigure(new Point(x, y1), false, false); } double y2 = height - ((max - short.MinValue) * height) / ushort.MaxValue; if (channel == 0) { sgcCh1.LineTo(new Point(x, y2), true, false); } else { y2 += height; sgcCh2.LineTo(new Point(x, y2), true, false); } } } m_FilePlayStream.Close(); m_FilePlayStream = null; sgcCh1.Close(); if (m_pcmFormat.NumberOfChannels > 1) { sgcCh2.Close(); } DrawingImage drawImg = new DrawingImage(); // geometryCh1.Freeze(); GeometryDrawing geoDraw1 = new GeometryDrawing(Brushes.LimeGreen, new Pen(Brushes.LimeGreen, 1.0), geometryCh1); geoDraw1.Freeze(); // GeometryDrawing geoDraw2 = null; if (m_pcmFormat.NumberOfChannels > 1) { geometryCh2.Freeze(); geoDraw2 = new GeometryDrawing(Brushes.LimeGreen, new Pen(Brushes.LimeGreen, 1.0), geometryCh2); geoDraw2.Freeze(); } // if (m_pcmFormat.NumberOfChannels > 1) { DrawingGroup drawGrp = new DrawingGroup(); drawGrp.Children.Add(geoDraw1); drawGrp.Children.Add(geoDraw2); drawGrp.Freeze(); drawImg.Drawing = drawGrp; } else { drawImg.Drawing = geoDraw1; } drawImg.Freeze(); WaveFormImage.Source = drawImg; m_WaveFormLoadingAdorner.Visibility = Visibility.Hidden; if (wasPlaying) { m_Player.Resume(); } }
private void AddSequenceAdornment(ITextViewLine line, SnapshotSpan span, LineCoverage coverage) { var rect = new Rect(0d, line.Top, _sequenceCoverageLineWidth, line.Height); var geometry = new RectangleGeometry(rect); geometry.Freeze(); var brush = _brushesAndPens[coverage.SequenceCoverageState].Brush; if (coverage.SequenceCoverageState == CoverageState.Covered && coverage.LineVisitors.Any(p => SelectedTests.Contains(p))) { brush = _selectedBrushAndPen.Brush; } var drawing = new GeometryDrawing(brush, null, geometry); drawing.Freeze(); var drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); var toolTip = new StackPanel(); var header = new TextBlock() { Text = string.Format(Resources.VisitorCount, coverage.VisitCount), TextWrapping = TextWrapping.Wrap }; toolTip.Children.Add(header); var image = new Image() { Source = drawingImage, ToolTip = toolTip }; Canvas.SetLeft(image, geometry.Bounds.Left); Canvas.SetTop(image, geometry.Bounds.Top); SharedDictionaryManager.InitializeDictionaries(image.Resources.MergedDictionaries); if (coverage.LineVisitors.Count > 0) { var description = new TextBlock() { Text = string.Join("\r\n", coverage.LineVisitors.Select(p => p.ShortName)), TextWrapping = TextWrapping.Wrap, Opacity = 0.7d }; toolTip.Children.Add(description); image.Tag = coverage.LineVisitors.ToArray(); image.MouseRightButtonDown += (o, e) => e.Handled = true; image.MouseRightButtonUp += OnTestCoverageRightButtonUp; image.MouseLeftButtonDown += (o, e) => e.Handled = true; image.MouseLeftButtonUp += (o, e) => _selectTestCommand.Execute(coverage.LineVisitors.First()); image.Cursor = Cursors.Hand; } _adornmentLayer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, image, null); }
private void createMultipleDrawingGroupExample(Panel examplePanel) { // <SnippetGraphicsMMMultipleDrawingGroupsExample> // Create a DrawingGroup. DrawingGroup mainGroup = new DrawingGroup(); // // Create a GeometryDrawing // GeometryDrawing ellipseDrawing = new GeometryDrawing( new SolidColorBrush(Color.FromArgb(102, 181, 243, 20)), new Pen(Brushes.Black, 4), new EllipseGeometry(new Point(50, 50), 50, 50) ); // // Use a DrawingGroup to apply a blur // bitmap effect to the drawing. // DrawingGroup blurGroup = new DrawingGroup(); blurGroup.Children.Add(ellipseDrawing); BlurBitmapEffect blurEffect = new BlurBitmapEffect(); blurEffect.Radius = 5; blurGroup.BitmapEffect = blurEffect; // Add the DrawingGroup to the main DrawingGroup. mainGroup.Children.Add(blurGroup); // // Create an ImageDrawing. // ImageDrawing kiwiPictureDrawing = new ImageDrawing( new BitmapImage(new Uri(@"sampleImages\kiwi.png", UriKind.Relative)), new Rect(50, 50, 100, 100)); // // Use a DrawingGroup to apply an opacity mask // and a bevel. // DrawingGroup maskedAndBeveledGroup = new DrawingGroup(); maskedAndBeveledGroup.Children.Add(kiwiPictureDrawing); // Create an opacity mask. RadialGradientBrush rgBrush = new RadialGradientBrush(); rgBrush.GradientStops.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 0.55)); rgBrush.GradientStops.Add(new GradientStop(Color.FromArgb(255, 0, 0, 0), 0.65)); rgBrush.GradientStops.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 0.75)); rgBrush.GradientStops.Add(new GradientStop(Color.FromArgb(255, 0, 0, 0), 0.80)); rgBrush.GradientStops.Add(new GradientStop(Color.FromArgb(0, 0, 0, 0), 0.90)); rgBrush.GradientStops.Add(new GradientStop(Color.FromArgb(255, 0, 0, 0), 1.0)); maskedAndBeveledGroup.OpacityMask = rgBrush; // Apply a bevel. maskedAndBeveledGroup.BitmapEffect = new BevelBitmapEffect(); // Add the DrawingGroup to the main group. mainGroup.Children.Add(maskedAndBeveledGroup); // // Create another GeometryDrawing. // GeometryDrawing ellipseDrawing2 = new GeometryDrawing( new SolidColorBrush(Color.FromArgb(102, 181, 243, 20)), new Pen(Brushes.Black, 4), new EllipseGeometry(new Point(150, 150), 50, 50) ); // Add the DrawingGroup to the main group. mainGroup.Children.Add(ellipseDrawing2); // </SnippetGraphicsMMMultipleDrawingGroupsExample> // // Use a DrawingImage and an Image to display the DrawingGroup. // DrawingImage drawingImageSource = new DrawingImage(mainGroup); // Freeze the DrawingImage for performance benefits. drawingImageSource.Freeze(); Image anImage = new Image(); anImage.Source = drawingImageSource; anImage.Stretch = Stretch.None; anImage.HorizontalAlignment = HorizontalAlignment.Left; Border imageBorder = new Border(); imageBorder.BorderBrush = Brushes.Gray; imageBorder.BorderThickness = new Thickness(1); imageBorder.HorizontalAlignment = HorizontalAlignment.Left; imageBorder.Margin = new Thickness(10); imageBorder.Child = anImage; examplePanel.Children.Add(imageBorder); }
private void AddBranchAdornment(ITextViewLine line, SnapshotSpan span, LineCoverage coverage) { var diameter = _textView.LineHeight / _branchCoverageSpotHeightDivider; var spacing = _branchCoverageSpotGap + diameter; var top = (line.Height - diameter) / 2d; var brush = _brushesAndPens[coverage.BranchCoverageState].Brush; var pen = _brushesAndPens[coverage.BranchCoverageState].Pen; var groupIndex = 0; var index = 0; var left = _sequenceCoverageLineWidth * 1.5d; foreach (var branchPoint in coverage.BranchesVisited) { foreach (var branch in branchPoint) { var rect = new Rect(left, line.Top + top, diameter, diameter); var geometry = new EllipseGeometry(rect); geometry.Freeze(); var brushOverride = brush; var penOverride = pen; if (branch && coverage.BranchVisitors[groupIndex][index].Any(p => SelectedTests.Contains(p))) { brushOverride = _selectedBrushAndPen.Brush; penOverride = _selectedBrushAndPen.Pen; } var drawing = new GeometryDrawing(branch ? brushOverride : null, penOverride, geometry); drawing.Freeze(); var drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); var image = new Image() { Source = drawingImage }; var testMethod = coverage.BranchVisitors[groupIndex][index].FirstOrDefault(); if (testMethod != null) { image.MouseLeftButtonDown += (o, e) => e.Handled = true; image.MouseLeftButtonUp += (o, e) => _selectTestCommand.Execute(testMethod); image.Cursor = Cursors.Hand; image.Tag = coverage.BranchVisitors[groupIndex][index].ToArray(); image.MouseRightButtonDown += (o, e) => e.Handled = true; image.MouseRightButtonUp += OnTestCoverageRightButtonUp; SharedDictionaryManager.InitializeDictionaries(image.Resources.MergedDictionaries); } Canvas.SetLeft(image, geometry.Bounds.Left); Canvas.SetTop(image, geometry.Bounds.Top); _adornmentLayer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, image, null); left += spacing; index++; } groupIndex++; index = 0; left += spacing; } }
public static ImageSource GetImage(DashStyleEx val) { const double height = 1; const double width = 2; const double lineWidth = height / 5; DashStyle dashStyle = DashStyles.Solid; if (val.IsKnownStyle) { if (val == DashStyleEx.Solid) { dashStyle = DashStyles.Solid; } else if (val == DashStyleEx.Dash) { dashStyle = DashStyles.Dash; } else if (val == DashStyleEx.Dot) { dashStyle = DashStyles.Dot; } else if (val == DashStyleEx.DashDot) { dashStyle = DashStyles.DashDot; } else if (val == DashStyleEx.DashDotDot) { dashStyle = DashStyles.DashDotDot; } else if (val == DashStyleEx.LongDash) { dashStyle = new DashStyle(new double[] { 5, 2 }, 0); } } else if (val.IsCustomStyle) { var list = new List <double>(); foreach (var e in val.CustomStyle) { list.Add(e); } dashStyle = new DashStyle(list, 0); } // draws a transparent outline to fix the borders var drawingGroup = new DrawingGroup(); var geometryDrawing = new GeometryDrawing { Geometry = new RectangleGeometry(new Rect(0, 0, width, height)), Pen = new Pen(Brushes.Transparent, 0) }; drawingGroup.Children.Add(geometryDrawing); geometryDrawing = new GeometryDrawing() { Geometry = new LineGeometry(new Point(0, height / 2), new Point(width, height / 2)) }; geometryDrawing.Pen = new Pen(Brushes.Black, lineWidth) { DashStyle = dashStyle }; drawingGroup.Children.Add(geometryDrawing); var geometryImage = new DrawingImage(drawingGroup); // Freeze the DrawingImage for performance benefits. geometryImage.Freeze(); return(geometryImage); }
private void AddLineResultAdornment(ITextViewLine line, SnapshotSpan span, LineResult[] lineResults) { if (lineResults.Length > 0) { var geometry = Geometry.Parse("F1M9.4141,8L12.4141,11 11.0001,12.414 8.0001,9.414 5.0001,12.414 3.5861,11 6.5861,8 3.5861,5 5.0001,3.586 8.0001,6.586 11.0001,3.586 12.4141,5z"); geometry.Freeze(); var drawing = new GeometryDrawing(lineResults.Any(p => p.IsPrimary) ? _exceptionOriginBrushAndPen.Brush : _exceptionTraceBrushAndPen.Brush, null, geometry); drawing.Freeze(); var drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); var toolTip = new StackPanel() { MaxWidth = 600 }; foreach (var group in lineResults.GroupBy(p => p.ErrorMessage)) { var header = new TextBlock() { Text = string.Join(Environment.NewLine, group.Select(p => p.TestMethod.ShortName).Distinct()), TextWrapping = TextWrapping.Wrap }; var description = new TextBlock() { Text = group.Key, TextWrapping = TextWrapping.Wrap, Opacity = 0.7d, Margin = new Thickness(0, 0, 0, 10) }; toolTip.Children.Add(header); toolTip.Children.Add(description); } toolTip.Children.OfType <TextBlock>().Last().Margin = new Thickness(); var viewBox = new Viewbox() { Width = _textView.LineHeight, Height = _textView.LineHeight, Stretch = Stretch.Uniform }; var button = new ActionButton() { Icon = drawingImage, CommandParameter = lineResults.FirstOrDefault().TestMethod, Command = _selectTestCommand, ToolTip = toolTip, Cursor = Cursors.Hand, Tag = lineResults.Select(p => p.TestMethod).ToArray() }; button.MouseRightButtonDown += (o, e) => e.Handled = true; button.MouseRightButtonUp += OnTestCoverageRightButtonUp; viewBox.Child = button; Canvas.SetLeft(viewBox, _sequenceCoverageLineWidth); Canvas.SetTop(viewBox, line.Top); _adornmentLayer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, viewBox, null); } }
public void Render() { try { double CanvasWidth = ActualWidth; double CanvasHeight = ActualHeight; double FullRange = AxisMax * 2; CanvasPlot.Children.Clear(); if (double.IsNaN(AxisMax)) { return; } if (CanvasWidth <= 0 || CanvasHeight <= 0) { return; } if (Points == null || Points.Count == 0) { ImagePlot.Source = null; return; } DrawingGroup DGroup = new DrawingGroup(); using (DrawingContext DContext = DGroup.Open()) { DContext.PushClip(new RectangleGeometry(new Rect(new Size(CanvasWidth, CanvasHeight)))); Pen OutlinePen = new Pen(Brushes.Transparent, 0); OutlinePen.Freeze(); SolidColorBrush BackgroundBrush = new SolidColorBrush(Colors.Transparent); BackgroundBrush.Freeze(); DContext.DrawRectangle(BackgroundBrush, OutlinePen, new Rect(new Size(CanvasWidth, CanvasHeight))); SolidColorBrush[] ColorBrushes = PointColors.Count > 0 ? PointColors.Select(c => { SolidColorBrush Brush = new SolidColorBrush(Color.FromArgb(120, c.R, c.G, c.B)); Brush.Freeze(); return(Brush); }).ToArray() : new[] { new SolidColorBrush(Color.FromArgb(150, Colors.DeepSkyBlue.R, Colors.DeepSkyBlue.G, Colors.DeepSkyBlue.B)) }; PointCenters = new System.Windows.Point[Points.Count]; for (int i = 0; i < Points.Count; i++) { if (double.IsNaN(Points[i].X) || double.IsNaN(Points[i].Y)) { continue; } //if (Math.Abs(Points[i].X) > AxisMax || Math.Abs(Points[i].Y) > AxisMax) // continue; double X = Points[i].X / FullRange * CanvasWidth + CanvasWidth / 2; double Y = Points[i].Y / FullRange * CanvasHeight + CanvasHeight / 2; DContext.DrawEllipse(ColorBrushes[Points[i].ColorID], OutlinePen, new System.Windows.Point(X, Y), PointRadius, PointRadius); PointCenters[i] = new System.Windows.Point(X, Y); } } DrawingImage Plot = new DrawingImage(DGroup); Plot.Freeze(); Dispatcher.Invoke(() => ImagePlot.Source = Plot); } catch { } }
/// <summary> /// Adds the scarlet box behind the 'a' characters within the given line /// </summary> /// <param name="line">Line to add the adornments</param> /* * private void CreateVisuals(ITextViewLine line) * { * IWpfTextViewLineCollection textViewLines = this.view.TextViewLines; * * // Loop through each character, and place a box around any 'a' * for (int charIndex = line.Start; charIndex < line.End; charIndex++) * { * if (this.view.TextSnapshot[charIndex] == 'a') * { * SnapshotSpan span = new SnapshotSpan(this.view.TextSnapshot, Span.FromBounds(charIndex, charIndex + 1)); * Geometry geometry = textViewLines.GetMarkerGeometry(span); * if (geometry != null) * { * var drawing = new GeometryDrawing(this.brush, this.pen, geometry); * drawing.Freeze(); * * var drawingImage = new DrawingImage(drawing); * drawingImage.Freeze(); * * var image = new Image * { * Source = drawingImage, * }; * * // Align the image with the top of the bounds of the text geometry * Canvas.SetLeft(image, geometry.Bounds.Left); * Canvas.SetTop(image, geometry.Bounds.Top); * * this.layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, image, null); * } * } * } * } */ private void HighlightCoverage(CoverageState[] coverdata, ProfileVector profiledata, ITextViewLine line) { if (view == null || profiledata == null || line == null || view.TextSnapshot == null) { return; } IWpfTextViewLineCollection textViewLines = view.TextViewLines; if (textViewLines == null || line.Extent == null) { return; } int lineno = 1 + view.TextSnapshot.GetLineNumberFromPosition(line.Extent.Start); CoverageState covered = lineno < coverdata.Length ? coverdata[lineno] : CoverageState.Irrelevant; if (covered != CoverageState.Irrelevant) { SnapshotSpan span = new SnapshotSpan(view.TextSnapshot, Span.FromBounds(line.Start, line.End)); Geometry g = textViewLines.GetMarkerGeometry(span); if (g != null) { g = new RectangleGeometry(new Rect(g.Bounds.X, g.Bounds.Y, view.ViewportWidth, g.Bounds.Height)); GeometryDrawing drawing = (covered == CoverageState.Covered) ? new GeometryDrawing(coveredBrush, coveredPen, g) : new GeometryDrawing(uncoveredBrush, uncoveredPen, g); drawing.Freeze(); DrawingImage drawingImage = new DrawingImage(drawing); drawingImage.Freeze(); Image image = new Image(); image.Source = drawingImage; //Align the image with the top of the bounds of the text geometry Canvas.SetLeft(image, g.Bounds.Left); Canvas.SetTop(image, g.Bounds.Top); layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, image, null); } } var profile = profiledata.Get(lineno); if (profile != null && profile.Item1 != 0 || profile.Item2 != 0) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(profile.Item1); sb.Append("%/"); sb.Append(profile.Item2); sb.Append("%"); SnapshotSpan span = new SnapshotSpan(view.TextSnapshot, Span.FromBounds(line.Start, line.End)); Geometry g = textViewLines.GetMarkerGeometry(span); if (g != null) // Yes, this apparently happens... { double x = g.Bounds.X + g.Bounds.Width + 20; if (x < view.ViewportWidth / 2) { x = view.ViewportWidth / 2; } g = new RectangleGeometry(new Rect(x, g.Bounds.Y, 30, g.Bounds.Height)); Label lbl = new Label(); lbl.FontSize = 7; lbl.Foreground = Brushes.Black; lbl.Background = Brushes.Transparent; lbl.FontFamily = new FontFamily("Verdana"); lbl.Content = sb.ToString(); Canvas.SetLeft(lbl, g.Bounds.Left); Canvas.SetTop(lbl, g.Bounds.Top); layer.AddAdornment(AdornmentPositioningBehavior.TextRelative, span, null, lbl, null); } } }
public OpacityExample() { // // Create a GeometryDrawing. // // Define the drawing's contents. PathFigure pLineFigure = new PathFigure(); pLineFigure.StartPoint = new Point(25, 25); PolyLineSegment pLineSegment = new PolyLineSegment(); pLineSegment.Points.Add(new Point(0, 50)); pLineSegment.Points.Add(new Point(25, 75)); pLineSegment.Points.Add(new Point(50, 50)); pLineSegment.Points.Add(new Point(25, 25)); pLineSegment.Points.Add(new Point(25, 0)); pLineFigure.Segments.Add(pLineSegment); PathGeometry pGeometry = new PathGeometry(); pGeometry.Figures.Add(pLineFigure); GeometryDrawing drawing1 = new GeometryDrawing( Brushes.Lime, new Pen(Brushes.Black, 10), pGeometry ); // // Create another GeometryDrawing. // GeometryDrawing drawing2 = new GeometryDrawing( Brushes.Lime, new Pen(Brushes.Black, 2), new EllipseGeometry(new Point(10, 10), 5, 5) ); // Create the DrawingGroup and add the // geometry drawings. DrawingGroup aDrawingGroup = new DrawingGroup(); aDrawingGroup.Children.Add(drawing1); aDrawingGroup.Children.Add(drawing2); // // Set the opacity of the DrawingGroup to 0.25. // aDrawingGroup.Opacity = 0.25; // Use an Image control and a DrawingImage to // display the drawing. DrawingImage aDrawingImage = new DrawingImage(aDrawingGroup); // Freeze the DrawingImage for performance benefits. aDrawingImage.Freeze(); Image anImage = new Image(); anImage.Source = aDrawingImage; anImage.Stretch = Stretch.None; anImage.HorizontalAlignment = HorizontalAlignment.Left; // Create a border around the images and add it to the // page. Border imageBorder = new Border(); imageBorder.BorderBrush = Brushes.Gray; imageBorder.BorderThickness = new Thickness(1); imageBorder.VerticalAlignment = VerticalAlignment.Top; imageBorder.HorizontalAlignment = HorizontalAlignment.Left; imageBorder.Margin = new Thickness(20); imageBorder.Child = anImage; this.Background = Brushes.White; this.Margin = new Thickness(20); this.Content = imageBorder; }
public BitmapEffectExample() { // // Create a DrawingGroup // that has no BitmapEffect // PathFigure pLineFigure = new PathFigure(); pLineFigure.StartPoint = new Point(25, 25); PolyLineSegment pLineSegment = new PolyLineSegment(); pLineSegment.Points.Add(new Point(0, 50)); pLineSegment.Points.Add(new Point(25, 75)); pLineSegment.Points.Add(new Point(50, 50)); pLineSegment.Points.Add(new Point(25, 25)); pLineSegment.Points.Add(new Point(25, 0)); pLineFigure.Segments.Add(pLineSegment); PathGeometry pGeometry = new PathGeometry(); pGeometry.Figures.Add(pLineFigure); GeometryDrawing drawing1 = new GeometryDrawing( Brushes.Lime, new Pen(Brushes.Black, 10), pGeometry ); GeometryDrawing drawing2 = new GeometryDrawing( Brushes.Lime, new Pen(Brushes.Black, 2), new EllipseGeometry(new Point(10, 10), 5, 5) ); // Create a DrawingGroup DrawingGroup drawingGroupWithoutBitmapEffect = new DrawingGroup(); drawingGroupWithoutBitmapEffect.Children.Add(drawing1); drawingGroupWithoutBitmapEffect.Children.Add(drawing2); // Use an Image control and a DrawingImage to // display the drawing. DrawingImage drawingImage01 = new DrawingImage(drawingGroupWithoutBitmapEffect); // Freeze the DrawingImage for performance benefits. drawingImage01.Freeze(); Image image01 = new Image(); image01.Source = drawingImage01; image01.Stretch = Stretch.None; image01.HorizontalAlignment = HorizontalAlignment.Left; // // Create another DrawingGroup and apply // a blur effect to it. // // Create a clone of the first DrawingGroup. DrawingGroup drawingGroupWithBitmapEffect = drawingGroupWithoutBitmapEffect.Clone(); // Create a blur effect. BlurBitmapEffect blurEffect = new BlurBitmapEffect(); blurEffect.Radius = 3.0; // Apply it to the drawing group. drawingGroupWithBitmapEffect.BitmapEffect = blurEffect; // Use another Image control and DrawingImage // to display the drawing. DrawingImage drawingImage02 = new DrawingImage(drawingGroupWithBitmapEffect); // Freeze the DrawingImage for performance benefits. drawingImage02.Freeze(); Image image02 = new Image(); image02.Source = drawingImage02; image02.Stretch = Stretch.None; image02.HorizontalAlignment = HorizontalAlignment.Left; // Create borders around the images and add them to the // page. Border border01 = new Border(); border01.BorderBrush = Brushes.Gray; border01.BorderThickness = new Thickness(1); border01.VerticalAlignment = VerticalAlignment.Top; border01.Margin = new Thickness(10); border01.Child = image01; Border border02 = new Border(); border02.BorderBrush = Brushes.Gray; border02.BorderThickness = new Thickness(1); border02.VerticalAlignment = VerticalAlignment.Top; border02.Margin = new Thickness(50, 10, 10, 10); border02.Child = image02; StackPanel mainPanel = new StackPanel(); mainPanel.Orientation = Orientation.Horizontal; mainPanel.HorizontalAlignment = HorizontalAlignment.Left; mainPanel.VerticalAlignment = VerticalAlignment.Top; mainPanel.Children.Add(border01); mainPanel.Children.Add(border02); // // Use a DrawingBrush to create a checkered background for the page. // GeometryDrawing backgroundSquareDrawing = new GeometryDrawing( Brushes.White, null, new RectangleGeometry(new Rect(0, 0, 1, 1))); GeometryGroup twoRectangles = new GeometryGroup(); twoRectangles.Children.Add(new RectangleGeometry(new Rect(0, 0, 0.5, 0.5))); twoRectangles.Children.Add(new RectangleGeometry(new Rect(0.5, 0.5, 0.5, 0.5))); SolidColorBrush squaresBrush = new SolidColorBrush(Color.FromArgb(102, 204, 204, 204)); squaresBrush.Opacity = 0.4; GeometryDrawing checkerDrawing = new GeometryDrawing( squaresBrush, null, twoRectangles); DrawingGroup checkerDrawings = new DrawingGroup(); checkerDrawings.Children.Add(backgroundSquareDrawing); checkerDrawings.Children.Add(checkerDrawing); DrawingBrush checkerBrush = new DrawingBrush(checkerDrawings); checkerBrush.Viewport = new Rect(0, 0, 10, 10); checkerBrush.ViewportUnits = BrushMappingMode.Absolute; checkerBrush.TileMode = TileMode.Tile; checkerBrush.Freeze(); this.Background = checkerBrush; this.Content = mainPanel; }