public GradientBrushTexture(GradientStopCollection stops) { _assetId++; _stops = stops.OrderedGradientStopList.Select(GradientStopData.FromGradientStop).ToList(); _name = String.Format("GradientBrushTexture#{0}", _assetId); Allocate(); }
internal LinearGradientBrush(Direct2DRenderTarget renderTargetOwner, GradientStop[] gradientStops, ExtendMode extendMode, PointF startPoint, PointF endPoint) { m_renderTargetOwner = renderTargetOwner; var gradientStopList = new List<SlimDX.Direct2D.GradientStop>(gradientStops.Length); for (int i = 0; i < gradientStops.Length; i++) { gradientStopList.Add(gradientStops[i].InternalGradientStop); } var props = new LinearGradientBrushProperties(); props.StartPoint = startPoint.InternalPointF; props.EndPoint = endPoint.InternalPointF; m_startPoint = startPoint; m_endPoint = endPoint; var internalRt = m_renderTargetOwner.InternalRenderTarget; m_internalGradientStopCollection = new GradientStopCollection(internalRt, gradientStopList.ToArray(), Gamma.Linear, (SlimDX.Direct2D.ExtendMode)extendMode); m_internalLinearGradientBrush = new SlimDX.Direct2D.LinearGradientBrush(internalRt, m_internalGradientStopCollection, props); }
internal RadialGradientBrush(Direct2DRenderTarget renderTargetOwner, GradientStop[] gradientStops, ExtendMode extendMode, PointF centerPoint, PointF gradientOriginOffset, SizeF radius) { m_renderTargetOwner = renderTargetOwner; m_extendMode = extendMode; m_radius = radius; m_gradientOriginOffset = gradientOriginOffset; m_centerPoint = centerPoint; var gradientStopList = new List<SlimDX.Direct2D.GradientStop>(gradientStops.Length); for (int i = 0; i < gradientStops.Length; i++) { gradientStopList.Add(gradientStops[i].InternalGradientStop); } var props = new RadialGradientBrushProperties(); props.CenterPoint = centerPoint.InternalPointF; props.GradientOriginOffset = gradientOriginOffset.InternalPointF; props.HorizontalRadius = radius.Width; props.VerticalRadius = radius.Height; m_internalGradientStopCollection = new GradientStopCollection(m_renderTargetOwner.InternalRenderTarget, gradientStopList.ToArray(), Gamma.Linear, (SlimDX.Direct2D.ExtendMode)extendMode); m_internalRadialGradientBrush = new SlimDX.Direct2D.RadialGradientBrush(m_renderTargetOwner.InternalRenderTarget, m_internalGradientStopCollection, props); }
public BGBarListBoxItem(RecFolderInfo item) { InitializeComponent(); labelFolder.Content = item.recFolder; progressBar.Value = item.freeBytes; progressBar.Maximum = item.totalBytes; GradientStopCollection stops = new GradientStopCollection(); stops.Add(new GradientStop(Colors.Red, 0.1)); stops.Add(new GradientStop(Colors.Yellow, 0.3)); stops.Add(new GradientStop(Colors.Lime, 0.4)); LinearGradientBrush brush = new LinearGradientBrush(stops, new Point(0, 0), new Point(1, 0)); brush.ColorInterpolationMode = ColorInterpolationMode.SRgbLinearInterpolation; progressBar.Background = brush; if (item.freeBytes > 0 && item.totalBytes > 0) { List<string> units = new List<string> { "Bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB" }; int unit_base = 1024; int n = (int)Math.Floor(Math.Min(Math.Log(item.freeBytes) / Math.Log(unit_base), units.Count - 1)); int m = (int)Math.Floor(Math.Min(Math.Log(item.totalBytes) / Math.Log(unit_base), units.Count - 1)); ToolTip = "空き容量: " + Math.Round(item.freeBytes / Math.Pow(unit_base, n), 1).ToString() + " " + units[n] + "/" + Math.Round(item.totalBytes / Math.Pow(unit_base, m), 1).ToString() + " " + units[m]; } }
public static GradientBrush Convert(System.Windows.Media.Color color) { var scrgb = color.ToScRGBColor(); var xyz = KnownColorSpaces.scRGB.ToXYZColor(scrgb); var lab = KnownColorSpaces.Lab.FromXYZColor(xyz) as LabColor; var l_base = lab.L; var gradientStops = new GradientStopCollection(); var _lab = new LabColor(0xff, l_base * 1.07, lab.a, lab.b); var _c = _lab.ToWindowsMediaColor(); gradientStops.Add(new GradientStop(_c, 0.5)); _lab = new LabColor(0xff, l_base * .93, lab.a, lab.b); _c = _lab.ToWindowsMediaColor(); gradientStops.Add(new GradientStop(_c, 1)); var result = new LinearGradientBrush(gradientStops, 90); result.Freeze(); return result; }
public static System.Windows.Media.Brush GetBrush(this Brush brush) { if (brush is GradientBrush) { var gradienBrush = brush as GradientBrush; var stops = new GradientStopCollection(gradienBrush.Stops.Select( g => new System.Windows.Media.GradientStop(g.Color.GetColor(), g.Offset) )); if (brush is LinearGradientBrush) { return new System.Windows.Media.LinearGradientBrush(stops); } else if (brush is RadialGradientBrush) { return new System.Windows.Media.RadialGradientBrush(stops); } else { throw new NotImplementedException(); } } else if (brush is SolidBrush) { var solidBrush = brush as SolidBrush; return new SolidColorBrush(solidBrush.Color.GetColor()); } else { throw new NotImplementedException(); } }
void D2Lines_Paint(object sender, PaintEventArgs e) { var lines = LineInfo.GenerateRandom(new Rectangle(Point.Empty, this.ClientSize)); var sw = new Stopwatch(); sw.Start(); this.d2target.BeginDraw(); this.d2target.Clear(Color.Black); foreach (var line in lines) { using (var gsc = new GradientStopCollection(this.d2target, new[]{ new GradientStop{ Position = 0f, Color = line.Ca }, new GradientStop{ Position = 1f, Color = line.Cb }, })) using(var gb = new LinearGradientBrush(this.d2target, gsc, new LinearGradientBrushProperties{ StartPoint = line.Pa, EndPoint = line.Pb, })) { this.d2target.DrawLine(gb, line.Pa.X, line.Pa.Y, line.Pb.X, line.Pb.Y); } } this.d2target.EndDraw(); sw.Stop(); Program.Info( "{0}: {1} [ms], {2} [line], {3:.00} [line/ms], {4} * {5}", this.Text, sw.ElapsedMilliseconds, lines.Length, lines.Length / (float)sw.ElapsedMilliseconds, this.ClientSize.Width, this.ClientSize.Height ); }
private void DrawSquares() { if (Row >= 3) { startx += 5; } if (Row >= 6) { startx += 5; } int x = startx + (Row * 40); if (Column >= 3) { starty += 5; } if (Column >= 6) { starty += 5; } int y = starty + (Column * 37); SetValue(Canvas.LeftProperty, Convert.ToDouble(x)); SetValue(Canvas.TopProperty, Convert.ToDouble(y)); GradientStopCollection gradients = new GradientStopCollection(); if (Value != 0) { gradients.Add(new GradientStop(Colors.LightBlue, 1)); gradients.Add(new GradientStop(Color.FromArgb(38, 255, 255, 255), 0.448)); gradients.Add(new GradientStop(Color.FromArgb(90, 73, 73, 73), 0.076)); SudokuTextBox.Text = Value.ToString(); SudokuTextBox.IsEnabled = false; } else { gradients.Add(new GradientStop(Colors.LightGreen, 0.9)); gradients.Add(new GradientStop(Colors.White, 0.448)); gradients.Add(new GradientStop(Colors.LightGreen, 0.076)); } SudokuTextBox.BorderThickness = new Thickness(0); SudokuTextBox.TextAlignment = TextAlignment.Center; LinearGradientBrush brush = new LinearGradientBrush(gradients); brush.StartPoint = new Point(0.5, 0); brush.EndPoint = new Point(0.5, 1); SudokuRectangle.Fill = brush; SudokuRectangle.Stroke = Brushes.Gray; SudokuRectangle.StrokeThickness = 1; SudokuRectangle.RadiusX = 8; SudokuRectangle.RadiusY = 8; SudokuTextBox.TextChanged += new TextChangedEventHandler(SudokuTextBox_TextChanged); }
public override void SaveGradient() { double rate = DataManager.Instance.MainData.PixelWidth / _bokehData.Width; GradientStopCollection collection = new GradientStopCollection(); collection.Add(new GradientStop() { Color = Colors.Transparent, Offset = _bokehData.Rate }); collection.Add(new GradientStop() { Color = Color.FromArgb(128, 0, 0, 0), Offset = _bokehData.Rate }); collection.Add(new GradientStop() { Color = Color.FromArgb(255, 0, 0, 0), Offset = 1 }); RadialGradientBrush brush = new RadialGradientBrush() { GradientOrigin = _bokehData.StarPoint, Center = _bokehData.StarPoint, RadiusX = _bokehData.RadiusX, RadiusY = _bokehData.RadiusY, GradientStops = collection, }; Rectangle rectangle = new Rectangle() { Width = DataManager.Instance.MainData.PixelWidth, Height = DataManager.Instance.MainData.PixelHeight, Fill = _bokehData.MaskBrush, OpacityMask = brush }; Canvas saveCanvas = new Canvas() { Width = rectangle.Width, Height = rectangle.Height, Background = new ImageBrush() { ImageSource = DataManager.Instance.MainData }, }; saveCanvas.Children.Add(rectangle); WriteableBitmap bmp = new WriteableBitmap(saveCanvas, null); DataManager.Instance.SaveToFile(bmp); }
/// <summary> /// Converts the color of the supplied brush changing its luminosity by the given factor. /// </summary> /// <param name="value">The value that is produced by the binding target.</param> /// <param name="targetType">The type to convert to.</param> /// <param name="parameter">The factor used to adjust the luminosity (0..1).</param> /// <param name="culture">The culture to use in the converter (unused).</param> /// <returns>A converted value.</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) #endif { if (value == null) return null; if (parameter == null) return null; var factor = double.Parse(parameter.ToString(), CultureInfo.InvariantCulture); if (value is SolidColorBrush) { var color = ((SolidColorBrush)value).Color; var hlsColor = HlsColor.FromRgb(color); hlsColor.L *= factor; return new SolidColorBrush(hlsColor.ToRgb()); } else if (value is LinearGradientBrush) { var gradientStops = new GradientStopCollection(); foreach (var stop in ((LinearGradientBrush)value).GradientStops) { var hlsColor = HlsColor.FromRgb(stop.Color); hlsColor.L *= factor; gradientStops.Add(new GradientStop() { Color = hlsColor.ToRgb(), Offset = stop.Offset }); } var brush = new LinearGradientBrush(gradientStops, 0.0); return brush; } return value; }
protected Brush CreateGradientBrush(Color baseColor) { const byte brightness = 60; var gradientStops = new GradientStopCollection(); gradientStops.Add(new GradientStop() { Color = LightenColor(baseColor, brightness), Offset = 0.0 }); gradientStops.Add(new GradientStop() { Color = baseColor, Offset = 1.0 }); return new LinearGradientBrush(gradientStops, 90); }
private void OnMouseLeave(object sender, RoutedEventArgs e) { GradientStopCollection stopCollection = new GradientStopCollection(); stopCollection.Add(new GradientStop(Colors.Blue, 0.05)); stopCollection.Add(new GradientStop(Colors.LightBlue, 0.95)); RadialGradientBrush brush = new RadialGradientBrush(stopCollection); circle.Fill = brush; }
public void CreateParallelBrush(string ls, double acc, double tot, string esp, string eep) { var stops = new GradientStopCollection(); var line = ls.AsLine(); var actual = GradientPath.CreateParallelBrush(stops, acc, tot, line); Assert.Equal(esp, actual.StartPoint.ToString("F0")); Assert.Equal(eep, actual.EndPoint.ToString("F0")); }
public void CreatePerpendicularBrush(string ls, double width, string esp, string eep) { var stops = new GradientStopCollection(); var line = ls.AsLine(); var actual = GradientPath.CreatePerpendicularBrush(stops, 10, line); Assert.Equal(Point.Parse(esp), actual.StartPoint); Assert.Equal(Point.Parse(eep), actual.EndPoint); }
protected static LinearGradientBrush CreateFrozenBrush(GradientStopCollection stops, Point start, Point end) { var brush = new LinearGradientBrush(stops, start, end); brush.Freeze(); return brush; }
public LinearGradientBrush (GradientStopCollection gradientStopCollection, double angle) : this () { if (gradientStopCollection != null) GradientStops = gradientStopCollection; double radian = angle * Math.PI / 180; EndPoint = new Point (Math.Cos (radian), Math.Sin (radian)); }
public GradientBrushTexture(GradientStopCollection stops) { _assetId++; _stops = new List<GradientStopData>(stops.Count); foreach (GradientStop stop in stops) _stops.Add(GradientStopData.FromGradientStop(stop)); _name = String.Format("GradientBrushTexture#{0}", _assetId); Allocate(); }
public TweetTrackerAction(Status status, IEnumerable<CaptureSubject> addedTo) { this._addedTo = new ObservableCollection<CaptureSubject>(addedTo); this._colors = new GradientStopCollection(); this._status = status; this.MakeGradients(); this._colors.Freeze(); }
/// <summary> /// Updates the fill. /// </summary> /// <param name="stops">The stops.</param> public void UpdateFill(GradientStopCollection stops) { Background = new LinearGradientBrush { StartPoint = new Point(0, 0), EndPoint = new Point(0, 1), GradientStops = stops }; }
public GradientBrushTexture GetGradientBrush(GradientStopCollection stops) { foreach (GradientBrushTexture texture in _cache) if (texture.IsSame(stops)) return texture; GradientBrushTexture gradientBrush = new GradientBrushTexture(stops); _cache.Add(gradientBrush); return gradientBrush; }
private void OnOneClick(object sender, RoutedEventArgs e) { RadialGradientBrush brush = this.Resources["redBrush"] as RadialGradientBrush; var gradientStops = new GradientStopCollection(); gradientStops.Add(new GradientStop(Colors.LightBlue, 0)); gradientStops.Add(new GradientStop(Colors.DarkBlue, 1)); LinearGradientBrush newBrush = new LinearGradientBrush(gradientStops); this.Resources["redBrush"] = newBrush; }
public BrushEditor() { GradientStopCollection stops = new GradientStopCollection(); stops.Add(new GradientStop(Colors.Black, 0)); stops.Add(new GradientStop(Colors.White, 1)); linearGradientBrush = new LinearGradientBrush(stops); linearGradientBrush.EndPoint = new Point(1, 0); radialGradientBrush = new RadialGradientBrush(stops); }
private void SetGradient(Color topColor, Color bottomColor) { GradientStopCollection gradients = new GradientStopCollection(); gradients.Add(new GradientStop(topColor, 0.9)); gradients.Add(new GradientStop(Colors.WhiteSmoke, 0.448)); gradients.Add(new GradientStop(bottomColor, 0.076)); LinearGradientBrush brush = new LinearGradientBrush(gradients); brush.StartPoint = new Point(0.5, 0); brush.EndPoint = new Point(0.5, 1); SudokuRectangle.Fill = brush; }
public void CollectionCtorSingle () { GradientStopCollection gsc = new GradientStopCollection (); gsc.Add (new GradientStop ()); RadialGradientBrush rgb = new RadialGradientBrush (gsc); Assert.IsTrue (Object.ReferenceEquals (gsc, rgb.GradientStops), "Same GradientStops"); GradientStop gs1 = rgb.GradientStops [0]; Assert.AreEqual ("#00000000", gs1.Color.ToString (), "1.Color"); Assert.AreEqual (0.0, gs1.Offset, "1.Offset"); }
private Brush getGradientBrush(Color color1, Color color2, int stopColor1, int stopColor2) { Point startPoint = new Point(0.5, 0); Point endPoint = new Point(0.5, 1); GradientStop stop1 = new GradientStop(color1, stopColor1); GradientStop stop2 = new GradientStop(color2, stopColor2); GradientStopCollection stops = new GradientStopCollection() { stop1, stop2 }; return new LinearGradientBrush(stops, startPoint, endPoint); }
static SortDirectionAdorner() { GradientStopCollection stops = new GradientStopCollection(2); stops.Insert(0, new GradientStop(SystemColors.ActiveCaptionColor, 0)); stops.Insert(1, new GradientStop(SystemColors.ControlColor, 1)); ArrowBrush = new LinearGradientBrush(stops, new Point(.5, 1.0), new Point(.5, 0.0)); DecendingArrow = Geometry.Parse("M 5,5 L 9,13 L 13,5"); AscendingArrow = Geometry.Parse("M 5,13 L 9,5 L 13,13"); }
public void AssocColor(string seriesId, Color b) { Color bTransparent = b; bTransparent.A = 0; GradientStopCollection gs = new GradientStopCollection(); gs.Add(new GradientStop(bTransparent, 0)); gs.Add(new GradientStop(b, 0.1)); LinearGradientBrush g = new LinearGradientBrush(gs, new Point(0,0), new Point(ActualWidth, 0)); g.MappingMode = BrushMappingMode.Absolute; g.Freeze(); brushes[seriesId] = g; }
public static LinearGradientBrush ChangeBackgroundColor(Color c) { var gs1 = new GradientStop(Colors.White, 0); var gs2 = new GradientStop(c, 1); var gsc = new GradientStopCollection {gs1, gs2}; var lgb = new LinearGradientBrush { StartPoint = new Point(0, 0), EndPoint = new Point(0, 1), GradientStops = gsc }; return lgb; }
/// <summary> /// Updates the fill. /// </summary> /// <param name="stops">The stops.</param> public void UpdateFill(GradientStopCollection stops) { var brush = Background as LinearGradientBrush; if (brush == null || brush.GradientStops != stops) { Background = new LinearGradientBrush { StartPoint = new Point(0, 0), EndPoint = new Point(0, 1), GradientStops = stops }; } }
public LinearGradientBrush GetBrush() { var gradientStops = new GradientStopCollection(); foreach (var gs in Stops.Select(ps => new GradientStop {Color = ps.Color, Offset = ps.StopValue})) { gradientStops.Add(gs); } //rect.Fill = new LinearGradientBrush(stops); var linbrush = new LinearGradientBrush {GradientStops = gradientStops}; linbrush.StartPoint = new Point(0,0); linbrush.EndPoint = new Point(1,0); return linbrush; }
protected override bool OnClickEnd(Point pointerPosition, int clickCount) { if (clickCount == 1 && this.ActiveAdorner != null && this.Tool is GradientBrushTool) { PropertyReference propertyReference1 = this.GetBrushPropertyReference((SceneNode)this.EditingElement); GradientStopCollection gradientStopCollection = (GradientStopCollection)this.ActiveAdorner.GetBrushPropertyAsWpf(GradientBrushNode.GradientStopsProperty); Matrix matrix = this.ActiveAdorner.GetCompleteBrushTransformMatrix(true) * this.ActiveView.GetComputedTransformToRoot(this.EditingElement); Point startPoint; Point endPoint; if (gradientStopCollection == null || !this.ActiveAdorner.GetBrushEndpoints(out startPoint, out endPoint)) { return(true); } Vector perpendicular; double offset = RoundingHelper.RoundLength(GradientStopBehavior.VectorProjection(startPoint * matrix, endPoint * matrix, this.dragStartPosition, 0.0, out perpendicular)); int index1 = 0; int index2 = 0; for (int index3 = 0; index3 < gradientStopCollection.Count; ++index3) { if (gradientStopCollection[index1].Offset > offset || gradientStopCollection[index3].Offset > gradientStopCollection[index1].Offset && gradientStopCollection[index3].Offset <= offset) { index1 = index3; } if (gradientStopCollection[index2].Offset < offset || gradientStopCollection[index3].Offset < gradientStopCollection[index2].Offset && gradientStopCollection[index3].Offset >= offset) { index2 = index3; } } GradientStop gradientStop; if (gradientStopCollection.Count == 0) { gradientStop = new GradientStop(Colors.White, offset); } else { double num = (offset - gradientStopCollection[index1].Offset) / (gradientStopCollection[index2].Offset - gradientStopCollection[index1].Offset); if (num > 1.0) { num = 1.0; } if (num < 0.0) { num = 0.0; } gradientStop = new GradientStop(Color.FromArgb((byte)((double)gradientStopCollection[index1].Color.A * (1.0 - num) + (double)gradientStopCollection[index2].Color.A * num), (byte)((double)gradientStopCollection[index1].Color.R * (1.0 - num) + (double)gradientStopCollection[index2].Color.R * num), (byte)((double)gradientStopCollection[index1].Color.G * (1.0 - num) + (double)gradientStopCollection[index2].Color.G * num), (byte)((double)gradientStopCollection[index1].Color.B * (1.0 - num) + (double)gradientStopCollection[index2].Color.B * num)), offset); } this.CopyPrimaryBrushToSelection(); PropertyReference propertyReference2 = propertyReference1.Append(GradientBrushNode.GradientStopsProperty); PropertyReference propertyReference3 = propertyReference2.Append(GradientStopCollectionNode.CountProperty); foreach (SceneElement sceneElement in this.ActiveView.ElementSelectionSet.Selection) { PropertyReference propertyReference4 = this.ActiveView.DesignerContext.PropertyManager.FilterProperty((SceneNode)sceneElement, propertyReference3); PropertyReference propertyReference5 = this.ActiveView.DesignerContext.PropertyManager.FilterProperty((SceneNode)sceneElement, propertyReference2); if (propertyReference4 != null && propertyReference5 != null) { int index3 = (int)sceneElement.GetComputedValue(propertyReference4); sceneElement.InsertValueAsWpf(propertyReference5, index3, (object)gradientStop); } } this.SetSelectedStopIndex(gradientStopCollection.Count); this.CommitEditTransaction(); } return(base.OnClickEnd(pointerPosition, clickCount)); }
public void Test_Utils_Brush_IsEqualTo() { var scb1 = new SolidColorBrush(Colors.Red); var scb2 = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0)); var scb3 = new SolidColorBrush(Color.FromArgb(255, 128, 128, 255)); Assert.AreEqual(true, scb1.IsEqualTo(scb2)); Assert.AreEqual(false, scb1.IsEqualTo(scb3)); Assert.AreEqual(false, scb2.IsEqualTo(scb3)); var gColl1 = new GradientStopCollection { new GradientStop() { Color = Colors.Red, Offset = 0 }, new GradientStop() { Color = Colors.Green, Offset = 0.5 }, new GradientStop() { Color = Colors.Blue, Offset = 1 } }; var lgb1 = new LinearGradientBrush() { StartPoint = new Point(0, 0), EndPoint = new Point(0, 1), GradientStops = gColl1 }; var gColl2 = new GradientStopCollection { new GradientStop() { Color = Colors.Red, Offset = 0 }, new GradientStop() { Color = Colors.Green, Offset = 0.5 }, new GradientStop() { Color = Colors.Blue, Offset = 1 } }; var lgb2 = new LinearGradientBrush() { StartPoint = new Point(0, 0), EndPoint = new Point(0, 1), GradientStops = gColl2 }; var gColl3 = new GradientStopCollection { new GradientStop() { Color = Colors.Red, Offset = 0 }, new GradientStop() { Color = Colors.Green, Offset = 0.5 }, new GradientStop() { Color = Colors.Yellow, Offset = 1 } }; var lgb3 = new LinearGradientBrush() { StartPoint = new Point(0, 0), EndPoint = new Point(0, 1), GradientStops = gColl3 }; Assert.AreEqual(true, lgb1.IsEqualTo(lgb2)); Assert.AreEqual(false, lgb1.IsEqualTo(lgb3)); Assert.AreEqual(false, lgb2.IsEqualTo(lgb3)); }
/// <summary> /// Builds the shading function of the specified gradient stop collection. /// </summary> protected PdfDictionary BuildShadingFunction(GradientStopCollection gradients, bool softMask, PdfColorMode colorMode, bool reverse, out PdfDictionary funcReverse) { PdfDictionary func = new PdfDictionary(); int count = gradients.Count; Debug.Assert(count >= 2); if (CanOptimizeForTwoColors(gradients)) { funcReverse = null; // Build a Type 3 function with an array of 2 Type 2 functions func.Elements["/FunctionType"] = new PdfInteger(3); // Type 3 - Stitching Function func.Elements["/Domain"] = new PdfLiteral("[0 1]"); PdfArray fnarray = new PdfArray(); func.Elements["/Functions"] = fnarray; StringBuilder bounds = new StringBuilder("["); StringBuilder encode = new StringBuilder("["); for (int idx = 1; idx < count; idx++) { PdfDictionary fn2 = new PdfDictionary(); fn2.Elements["/FunctionType"] = new PdfInteger(2); Color clr0 = gradients[idx - 1].Color; Color clr1 = gradients[idx].Color; if (softMask) { fn2.Elements["/C0"] = new PdfLiteral("[" + PdfEncoders.ToString(clr0.ScA) + "]"); fn2.Elements["/C1"] = new PdfLiteral("[" + PdfEncoders.ToString(clr1.ScA) + "]"); fn2.Elements["/Range"] = new PdfLiteral("[0 1]"); } else { fn2.Elements["/C0"] = new PdfLiteral("[" + PdfEncoders.ToString(clr0, colorMode) + "]"); fn2.Elements["/C1"] = new PdfLiteral("[" + PdfEncoders.ToString(clr1, colorMode) + "]"); fn2.Elements["/Range"] = new PdfLiteral("[0 1 0 1 0 1]"); } fn2.Elements["/Domain"] = new PdfLiteral("[0 1]"); fn2.Elements["/N"] = new PdfInteger(1); fnarray.Elements.Add(fn2); if (idx > 1) { bounds.Append(' '); encode.Append(' '); } if (idx < count - 1) { bounds.Append(PdfEncoders.ToString(gradients[idx].Offset)); } encode.Append(reverse ? "1 0" : "0 1"); } bounds.Append(']'); encode.Append(']'); func.Elements["/Bounds"] = new PdfLiteral(bounds.ToString()); func.Elements["/Encode"] = new PdfLiteral(encode.ToString()); } else { #if true funcReverse = BuildShadingFunction3(gradients, softMask, colorMode); Context.PdfDocument.Internals.AddObject(funcReverse); func.Elements["/FunctionType"] = new PdfInteger(3); // Type 3 - Stitching Function func.Elements["/Domain"] = new PdfLiteral("[0 1]"); func.Elements["/Encode"] = new PdfLiteral("[1 0]"); func.Elements["/Bounds"] = new PdfLiteral("[]"); func.Elements["/Range"] = new PdfLiteral("[0 1 0 1 0 1]"); PdfArray fnarray0 = new PdfArray(); fnarray0.Elements.Add(funcReverse); func.Elements["/Functions"] = fnarray0; #else // // Build a Type 3 function with an array of n-1 Type 2 functions PdfDictionary fn1 = new PdfDictionary(); func.Elements["/FunctionType"] = new PdfInteger(3); // Type 3 - Stitching Function func.Elements["/Domain"] = new PdfLiteral("[0 1]"); func.Elements["/Encode"] = new PdfLiteral("[1 0]"); func.Elements["/Bounds"] = new PdfLiteral("[]"); func.Elements["/Range"] = new PdfLiteral("[0 1 0 1 0 1]"); PdfArray fnarray0 = new PdfArray(); fnarray0.Elements.Add(fn1); func.Elements["/Functions"] = fnarray0; fn1.Elements["/FunctionType"] = new PdfInteger(3); // Type 3 - Stitching Function fn1.Elements["/Domain"] = new PdfLiteral("[0 1]"); fn1.Elements["/Range"] = new PdfLiteral("[0 1 0 1 0 1]"); PdfArray fnarray = new PdfArray(); fn1.Elements["/Functions"] = fnarray; StringBuilder bounds = new StringBuilder("["); StringBuilder encode = new StringBuilder("["); for (int idx = 1; idx < count; idx++) { PdfDictionary fn2 = new PdfDictionary(); fn2.Elements["/FunctionType"] = new PdfInteger(2); Color clr0 = gradients[idx - 1].Color; Color clr1 = gradients[idx].Color; if (softMask) { fn2.Elements["/C0"] = new PdfLiteral("[" + PdfEncoders.ToString(clr0.ScA) + "]"); fn2.Elements["/C1"] = new PdfLiteral("[" + PdfEncoders.ToString(clr1.ScA) + "]"); fn2.Elements["/Range"] = new PdfLiteral("[0 1]"); } else { fn2.Elements["/C0"] = new PdfLiteral("[" + PdfEncoders.ToString(clr0, colorMode) + "]"); fn2.Elements["/C1"] = new PdfLiteral("[" + PdfEncoders.ToString(clr1, colorMode) + "]"); fn2.Elements["/Range"] = new PdfLiteral("[0 1 0 1 0 1]"); } fn2.Elements["/Domain"] = new PdfLiteral("[0 1]"); fn2.Elements["/N"] = new PdfInteger(1); //this.renderer.Owner.Internals.AddObject(fn2); //fnarray.Elements.Add(fn2.Reference); fnarray.Elements.Add(fn2); if (idx > 1) { bounds.Append(' '); encode.Append(' '); } if (idx < count - 1) { bounds.Append(PdfEncoders.ToString(gradients[idx].Offset)); } encode.Append("0 1"); } bounds.Append(']'); encode.Append(']'); fn1.Elements["/Bounds"] = new PdfLiteral(bounds.ToString()); fn1.Elements["/Encode"] = new PdfLiteral(encode.ToString()); #endif } return(func); }
public LinearGradientBrush(GradientStopCollection gradientStops) { GradientStops = gradientStops; }
private WriteableBitmap DrawChar(int x_offset, Rect rect, TextContext context) { // Create the outline strategy which is going to shift blit diagonally var strategyOutline = TextDesignerWpf.CanvasHelper.TextOutline(MaskColor.Blue, MaskColor.Blue, 4); WriteableBitmap canvas = TextDesignerWpf.CanvasHelper.GenImage((int)(image1.Width), (int)(image1.Height), Colors.White, 0); // the single mask outline WriteableBitmap maskOutline = TextDesignerWpf.CanvasHelper.GenMask(strategyOutline, (int)(image1.Width), (int)(image1.Height), new Point(0, 0), context); // the mask to store all the single mask blitted diagonally WriteableBitmap maskOutlineAll = TextDesignerWpf.CanvasHelper.GenImage((int)(image1.Width) + 10, (int)(image1.Height) + 10); RenderTargetBitmap bmp = new RenderTargetBitmap((int)(maskOutlineAll.Width), (int)(maskOutlineAll.Height), 96, 96, PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); // blit diagonally for (int i = 0; i < 8; ++i) { drawingContext.DrawImage(maskOutline, new Rect((double)(-i), (double)(-i), maskOutline.Width, maskOutline.Height - 0.0)); } drawingContext.Close(); bmp.Render(drawingVisual); maskOutlineAll = new WriteableBitmap(bmp); // Measure the dimension of the big mask in order to generate the correct sized gradient image //============================================================================================= uint top = 0; uint bottom = 0; uint left = 0; uint right = 0; TextDesignerWpf.CanvasHelper.MeasureMaskLength(maskOutlineAll, MaskColor.Blue, ref top, ref left, ref bottom, ref right); right += 2; bottom += 2; // Generate the gradient image for the diagonal outline //======================================================= WriteableBitmap gradImage = TextDesignerWpf.CanvasHelper.GenImage((int)(right - left), (int)(bottom - top)); List <Color> listColors = new List <Color>(); listColors.Add(Colors.Purple); listColors.Add(Colors.MediumPurple); DrawGradient.Draw(ref gradImage, listColors, false); // Because Canvas::ApplyImageToMask requires all image to have same dimensions, // we have to blit our small gradient image onto a temp image as big as the canvas //=================================================================================== WriteableBitmap gradBlitted = TextDesignerWpf.CanvasHelper.GenImage((int)(image1.Width), (int)(image1.Height)); byte[] pixels2 = new byte[gradImage.PixelHeight * gradImage.PixelWidth * gradImage.Format.BitsPerPixel / 8]; gradImage.CopyPixels(pixels2, gradImage.BackBufferStride, 0); gradBlitted.WritePixels(new Int32Rect((int)left, (int)top, (int)(gradImage.Width), (int)(gradImage.Height)), pixels2, gradImage.BackBufferStride, 0); TextDesignerWpf.CanvasHelper.ApplyImageToMask(gradBlitted, maskOutlineAll, canvas, MaskColor.Blue, false); // Create strategy and mask image for the text body //=================================================== var strategyText = TextDesignerWpf.CanvasHelper.TextNoOutline(MaskColor.Blue); WriteableBitmap maskText = TextDesignerWpf.CanvasHelper.GenMask(strategyText, (int)(image1.Width), (int)(image1.Height), new Point(0, 0), context); // Measure the dimension required for text body using the mask //============================================================= top = 0; bottom = 0; left = 0; right = 0; TextDesignerWpf.CanvasHelper.MeasureMaskLength(maskText, MaskColor.Blue, ref top, ref left, ref bottom, ref right); top -= 2; left -= 2; right += 2; bottom += 2; GradientStopCollection coll = new GradientStopCollection(); GradientStop stop = new GradientStop(Colors.DeepPink, 0.0); coll.Add(stop); stop = new GradientStop(Colors.LightPink, 1.0); coll.Add(stop); // Create the gradient brush for the text body LinearGradientBrush gradTextbrush = new LinearGradientBrush(coll, 90.0); // Create the actual strategy for the text body used for rendering, with the gradient brush var strategyText2 = TextDesignerWpf.CanvasHelper.TextNoOutline(gradTextbrush); // Draw the newly created strategy onto the canvas TextDesignerWpf.CanvasHelper.DrawTextImage(strategyText2, ref canvas, new Point(0, 0), context); return(canvas); }
public static RadialGradientBrush ConstructBrush(SvgRadialGradientElement gradient, Rect bounds, Matrix transform) { if (gradient.Stops.Count == 0) { return(null); } double centerX = gradient.Cx.AnimVal.Value; double centerY = gradient.Cy.AnimVal.Value; double focusX = gradient.Fx.AnimVal.Value; double focusY = gradient.Fy.AnimVal.Value; double radius = gradient.R.AnimVal.Value; GradientStopCollection gradientStops = ToGradientStops(gradient.Stops); RadialGradientBrush brush = new RadialGradientBrush(gradientStops); brush.RadiusX = radius; brush.RadiusY = radius; brush.Center = new Point(centerX, centerY); brush.GradientOrigin = new Point(focusX, focusY); if (gradient.SpreadMethod != null) { SvgSpreadMethod spreadMethod = (SvgSpreadMethod)gradient.SpreadMethod.AnimVal; GradientSpreadMethod sm; if (TryGetSpreadMethod(spreadMethod, out sm)) { brush.SpreadMethod = sm; } } SvgUnitType mappingMode = SvgUnitType.ObjectBoundingBox; if (gradient.GradientUnits != null) { mappingMode = (SvgUnitType)gradient.GradientUnits.AnimVal; if (mappingMode == SvgUnitType.ObjectBoundingBox) { brush.MappingMode = BrushMappingMode.RelativeToBoundingBox; } else if (mappingMode == SvgUnitType.UserSpaceOnUse) { brush.MappingMode = BrushMappingMode.Absolute; brush.Center.Offset(bounds.X, bounds.Y); brush.GradientOrigin.Offset(bounds.X, bounds.Y); } } Matrix brushTransform = ToWpfMatrix(((SvgTransformList)gradient.GradientTransform.AnimVal).TotalMatrix); if (mappingMode == SvgUnitType.UserSpaceOnUse) { brushTransform *= transform; } if (!brushTransform.IsIdentity) { brush.Transform = new MatrixTransform(brushTransform); } string colorInterpolation = gradient.GetPropertyValue("color-interpolation"); if (!string.IsNullOrWhiteSpace(colorInterpolation)) { if (colorInterpolation == "linearRGB") { brush.ColorInterpolationMode = ColorInterpolationMode.SRgbLinearInterpolation; } else { brush.ColorInterpolationMode = ColorInterpolationMode.ScRgbLinearInterpolation; } } return(brush); }
/// <summary> /// Returns a Windows brush from the NGraphics brush /// </summary> /// <param name="fromBrush"></param> /// <returns></returns> private System.Windows.Media.Brush GetBrush(NGraphics.Brush fromBrush) { var sb = fromBrush as SolidBrush; if (sb != null) { // Solid brush return(new SolidColorBrush(new System.Windows.Media.Color { A = sb.Color.A, R = sb.Color.R, G = sb.Color.G, B = sb.Color.B })); } var lb = fromBrush as NGraphics.LinearGradientBrush; if (lb != null) { // Linear gradient var gradStops = new GradientStopCollection(); var n = lb.Stops.Count; if (n >= 2) { var locs = new float[n]; var comps = new int[n]; for (var i = 0; i < n; i++) { var s = lb.Stops[i]; gradStops.Add(new System.Windows.Media.GradientStop { Color = new System.Windows.Media.Color { A = s.Color.A, R = s.Color.R, B = s.Color.B, G = s.Color.G, }, Offset = s.Offset, }); } } var grad = new System.Windows.Media.LinearGradientBrush(gradStops, 90); return(grad); } var rb = fromBrush as NGraphics.RadialGradientBrush; if (rb != null) { // Radial gradient var grad = new System.Windows.Media.RadialGradientBrush(); var n = rb.Stops.Count; if (n >= 2) { var locs = new float[n]; var comps = new int[n]; for (var i = 0; i < n; i++) { var s = rb.Stops[i]; grad.GradientStops.Add(new System.Windows.Media.GradientStop { Color = new System.Windows.Media.Color { A = s.Color.A, R = s.Color.R, B = s.Color.B, G = s.Color.G, }, Offset = s.Offset, }); } } return(grad); } return(null); }
private void ApplyValueSettings() { if (Cell == null) { m_Caption_Text.Visibility = Visibility.Collapsed; if (m_ProgressBar != null) { m_ProgressBar.Visibility = Visibility.Collapsed; } if (m_Image != null) { m_Image.Visibility = Visibility.Collapsed; } return; } // Если в ячейке отображается только значение, то оно должно быть выравнено по правому краю // Если в ячейке отображается только картинка, то она должна быть выравнена по центру // Если в ячейке отображается картинка и значение, то картинка должна быть выравнена по левому краю, а значение по правому bool show_Value = true; bool show_Image = false; bool show_ProgressBar = false; if (m_CustomCellAppearance != null) { show_Value = m_CustomCellAppearance.Options.ShowValue; show_Image = m_CustomCellAppearance.Options.UseImage && !String.IsNullOrEmpty(m_CustomCellAppearance.CustomImageUri); show_ProgressBar = m_CustomCellAppearance.Options.UseProgressBar; } if (show_ProgressBar == true) { show_Image = false; } // Прогрессбар из условия if (show_ProgressBar) { if (m_ProgressBar == null) { m_ProgressBar = new ProgressBar(); m_ProgressBar.VerticalAlignment = VerticalAlignment.Stretch; m_ProgressBar.HorizontalAlignment = HorizontalAlignment.Stretch; m_LayoutPanel.Children.Add(m_ProgressBar); Grid.SetColumnSpan(m_ProgressBar, 3); // Текстовое поле поверх прогресса m_LayoutPanel.Children.Remove(m_Caption_Text); m_LayoutPanel.Children.Add(m_Caption_Text); Grid.SetColumn(m_Caption_Text, 1); } m_ProgressBar.Minimum = m_CustomCellAppearance.ProgressBarOptions.MinValue; m_ProgressBar.Maximum = m_CustomCellAppearance.ProgressBarOptions.MaxValue; double value = 0; if (Cell.CellDescr != null && Cell.CellDescr.Value != null && Cell.CellDescr.Value.Value != null) { try { value = Convert.ToDouble(Cell.CellDescr.Value.Value); } catch (System.InvalidCastException) { } } m_ProgressBar.Value = value; GradientStopCollection stops = new GradientStopCollection(); stops.Add(new GradientStop() { Color = m_CustomCellAppearance.ProgressBarOptions.StartColor }); stops.Add(new GradientStop() { Color = m_CustomCellAppearance.ProgressBarOptions.EndColor, Offset = 1 }); LinearGradientBrush brush = new LinearGradientBrush(stops, 0); m_ProgressBar.Foreground = brush; m_ProgressBar.Visibility = Visibility.Visible; // В прогрессбаре текст отображаем в центре m_Caption_Text.TextAlignment = TextAlignment.Center; } else { if (m_ProgressBar != null) { m_ProgressBar.Visibility = Visibility.Collapsed; } } // Если никаких условий не задано, либо в условии прописано отображать значение if (show_Value) { m_Caption_Text.Visibility = Visibility.Visible; m_Caption_Text.FontWeight = FontWeights.Normal; if (NotRecalculatedChange != null) { // Пытаемся отобразить модифицированное значение в том же формате, в котором оно будет отображаться пользователю когда запишется в куб // Модифицированное значение пытаемся преобразовать в число. Если преобразование успешное, то пытаемся применить строку форматирования // В случае, если преобразование в число не получится, то выводим модифицированное значение просто в строку String text = NotRecalculatedChange.NewValue; if (Cell.CellDescr != null && !String.IsNullOrEmpty(Cell.CellDescr.FormatString)) { // Проверяем чтобы в качестве разделителя был допутимый символ (чтобы значение можно было конвертировать). String modif = text; modif = modif.Replace(".", System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator); modif = modif.Replace(",", System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator); try { double value = Convert.ToDouble(modif); String str = value.ToString(Cell.CellDescr.FormatString, CultureInfo.InvariantCulture); if (str != Cell.CellDescr.FormatString) // Для случаев Currency и т.д. { text = str; } } catch { } } m_Caption_Text.Text = text; } else { if (Cell.CellDescr != null && Cell.CellDescr.Value != null) { m_Caption_Text.Text = Cell.CellDescr.Value.DisplayValue; } else { m_Caption_Text.Text = String.Empty; } } if (m_CustomCellAppearance != null && m_CustomCellAppearance.Options.UseForeColor) { // Цвет из настроек условий для ячейки m_Caption_Text.Foreground = new SolidColorBrush(m_CustomCellAppearance.ForeColor); } else { Brush brush = new SolidColorBrush(Colors.Black); if (RecalculatedChange != null) { m_Caption_Text.FontWeight = FontWeights.Bold; brush = new SolidColorBrush(Colors.Blue); } else { if (NotRecalculatedChange == null && Cell.CellDescr != null) { int foreColor = Cell.CellDescr.ForeColor; if (foreColor != int.MinValue) { // Цвет из OLAP (свойства ячейки) Color color = ColorHelper.FromRgb(foreColor); brush = new SolidColorBrush(color); } } } m_Caption_Text.Foreground = brush; } } else { m_Caption_Text.Visibility = Visibility.Collapsed; } BitmapImage image = null; if (m_CustomCellAppearance != null && !String.IsNullOrEmpty(m_CustomCellAppearance.CustomImageUri)) { try { image = new BitmapImage(new Uri(m_CustomCellAppearance.CustomImageUri, UriKind.Relative)); } catch { } } // Если ошибка при обновлении ячейки if (NotRecalculatedChange != null && NotRecalculatedChange.HasError) { show_Image = true; image = UriResources.Images.ErrorSmall16; } // Картинка из условия if (show_Image && image != null) { if (m_Image == null) { m_Image = new Image(); m_Image.Margin = new Thickness(2, 0, 2, 0); m_Image.Width = m_Image.Height = 16; m_Image.Visibility = Visibility.Collapsed; m_Image.Stretch = Stretch.Uniform; m_LayoutPanel.Children.Add(m_Image); Grid.SetColumn(m_Image, 0); } m_Image.Visibility = Visibility.Visible; m_Image.Source = image; if (image != null) { m_Image.Width = image.PixelWidth * Scale; m_Image.Height = image.PixelHeight * Scale; } if (show_Value) { // Отображается картинка и значение Grid.SetColumnSpan(m_Image, 1); } else { // Отображается только картинка Grid.SetColumnSpan(m_Image, 3); } } else { if (m_Image != null) { m_Image.Visibility = Visibility.Collapsed; } } }
/// <summary> /// 绘制抢救时间段 /// </summary> private void DrawRescueTimes(double TicStartY) { if (RescueTimeList == null || RescueTimeList.Count == 0) { return; } GradientStopCollection GradientStops = new GradientStopCollection(); GradientStops.Add(new GradientStop(Color.FromRgb(0xFF, 0x79, 0x0A), 0.0)); GradientStops.Add(new GradientStop(Color.FromRgb(0xFF, 0x87, 0x24), 0.3)); GradientStops.Add(new GradientStop(Color.FromRgb(0xFF, 0x99, 0x44), 0.7)); GradientStops.Add(new GradientStop(Color.FromRgb(0xFF, 0xA5, 0x5A), 1.0)); LinearGradientBrush bgBrush = new LinearGradientBrush(GradientStops, new Point(0, 0), new Point(0, 1)); Border processBorder; Image image; BitmapImage bi3 = new BitmapImage(); bi3.BeginInit(); bi3.UriSource = new Uri("../Images/rescue.png", UriKind.Relative); bi3.EndInit(); DateTime rescueEndTime = DateTime.Now; double x1, x2; bool isOverMin, isOverMax; for (int i = 0; i < RescueTimeList.Count; i++) { RescueTime rescueTime = RescueTimeList[i]; if (rescueTime.CameraTime.HasValue) { rescueEndTime = rescueTime.CameraTime.Value.AddMinutes(2); } else { if (!rescueTime.BeginTime.HasValue) { continue; } if (rescueTime.BeginTime.Value >= _XAxis.MaxTime) { continue; } if (rescueTime.EndTime.HasValue) { rescueEndTime = rescueTime.EndTime.Value; } else { rescueEndTime = DateTime.Now; } if (!rescueTime.BeginTime.HasValue) { continue; } if (rescueTime.BeginTime.Value >= _XAxis.MaxTime) { continue; } if (rescueTime.EndTime.HasValue) { rescueEndTime = rescueTime.EndTime.Value; } else { rescueEndTime = DateTime.Now; } } if (rescueEndTime > _XAxis.MaxTime) { rescueEndTime = _XAxis.MaxTime; } x1 = _XAxis.LocalTransform(rescueTime.CameraTime.HasValue ? rescueTime.CameraTime.Value:rescueTime.BeginTime.Value, out isOverMin, out isOverMax); x2 = _XAxis.LocalTransform(rescueEndTime, out isOverMin, out isOverMax); if (rescueTime.CameraTime.HasValue) { image = new Image(); image.Width = x2 - x1; image.Source = bi3; image.Height = _drawHeight * TicAreaHeightPercent; image.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; image.VerticalAlignment = System.Windows.VerticalAlignment.Top; image.Margin = new Thickness(x1, TicStartY, 0, 0); image.Tag = rescueTime; image.MouseLeftButtonDown += Image_MouseLeftButtonDown; _Container.Children.Add(image); _TimeProcessUI.Add(image); } else { processBorder = new Border(); processBorder.Width = x2 - x1; processBorder.Height = _drawHeight * TicAreaHeightPercent; processBorder.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; processBorder.VerticalAlignment = System.Windows.VerticalAlignment.Top; processBorder.CornerRadius = new CornerRadius(5); processBorder.Background = bgBrush; processBorder.Margin = new Thickness(x1, TicStartY, 0, 0); processBorder.Tag = rescueTime; processBorder.MouseLeftButtonDown += processBorder_MouseLeftButtonDown; _Container.Children.Add(processBorder); _TimeProcessUI.Add(processBorder); } } }
protected override void OnRender(DrawingContext drawingContext) { double width = base.ActualWidth; double height = base.ActualHeight; double minimum = this.Minimum; double maximum = this.Maximum; double range = maximum - minimum; bool flag = base.Orientation == Orientation.Vertical; double tickFrequency = this.TickFrequency; double majorTicksOffset = this.MajorTicksOffset; var stops = this.RangeColors; var ticks = this.Ticks; int minTicksCount = this.MinTicksCount; int count = ticks.Count == 0 ? Convert.ToInt32((maximum - minimum) / tickFrequency) : ticks.Count; if (stops.Count != 0) { double num5; double num4 = 0.0; if (minimum < 0.0) { num4 = Math.Abs(minimum); } GradientStopCollection gradientStopCollection = new GradientStopCollection(); for (int i = 0; i < stops.Count; i++) { GradientStop stop = stops[i].Clone(); stop.Offset = (stop.Offset + num4) / range; gradientStopCollection.Add(stop); } num5 = flag ? -90.0 : 0.0; var brush = new LinearGradientBrush(gradientStopCollection, new Point(0.0, 0.5), new Point(1.0, 0.5)); brush.RelativeTransform = new RotateTransform(num5, 0.5, 0.5); brush.Freeze(); drawingContext.DrawRectangle(brush, null, new Rect(0, 0, width, height)); } string text = ""; Pen pen2 = new Pen(base.Foreground, this.StrokeThickness * 2.0); double num = flag ? height / count : width / count; double scaleX = 1.0; double scaleY = 1.0; if (this.Flipping == SelectiveScrollingOrientation.Horizontal || this.Flipping == SelectiveScrollingOrientation.Both) { scaleX = -1.0; } if (this.Flipping == SelectiveScrollingOrientation.Vertical || this.Flipping == SelectiveScrollingOrientation.Both) { scaleY = -1.0; } for (int i = 0; i <= count; i++) { double y = i * num; text = (i == count ? minimum : ticks.Count != 0 ? ticks[i] : maximum - i * tickFrequency).ToString(this.TickStringFormat); FormattedText formattedText = new FormattedText(text, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight, new Typeface(base.FontFamily, base.FontStyle, base.FontWeight, base.FontStretch), base.FontSize, base.Foreground); if (flag) { drawingContext.DrawLine(pen2, new Point(0.0, y), new Point(width, y)); drawingContext.PushTransform(new ScaleTransform(scaleX, scaleY, majorTicksOffset - (formattedText.Width / 2.0), y)); drawingContext.DrawText(formattedText, new Point(majorTicksOffset - formattedText.Width, y - (formattedText.Height / 2.0))); drawingContext.Pop(); } else { drawingContext.DrawLine(pen2, new Point(y, 0.0), new Point(y, height)); drawingContext.PushTransform(new ScaleTransform(scaleX, scaleY, y, majorTicksOffset - (formattedText.Height / 2.0))); drawingContext.DrawText(formattedText, new Point(y - (formattedText.Width / 2.0), majorTicksOffset - formattedText.Height)); drawingContext.Pop(); } } if (minTicksCount > 0) { count *= minTicksCount; num = flag ? height / count : width / count; Pen pen = new Pen(base.Foreground, this.StrokeThickness); for (int i = 0; i < count; i++) { if (flag) { drawingContext.DrawLine(pen, new Point(width / 2, i * num), new Point(width, i * num)); } else { drawingContext.DrawLine(pen, new Point(i * num, height / 2), new Point(i * num, height)); } } } }
internal override WpfBrush RealizeWpfBrush() { //if (dirty) //{ // if (brush == null) // brush = new SolidBrush(color.ToGdiColor()); // else // { // brush.Color = color.ToGdiColor(); // } // dirty = false; //} System.Windows.Media.LinearGradientBrush brush; if (_useRect) { #if !SILVERLIGHT brush = new System.Windows.Media.LinearGradientBrush(_color1.ToWpfColor(), _color2.ToWpfColor(), new SysPoint(0, 0), new SysPoint(1, 1));// rect.TopLeft, this.rect.BottomRight); //brush = new System.Drawing.Drawing2D.LinearGradientBrush(rect.ToRectangleF(), // color1.ToGdiColor(), color2.ToGdiColor(), (LinearGradientMode)linearGradientMode); #else GradientStop gs1 = new GradientStop(); gs1.Color = _color1.ToWpfColor(); gs1.Offset = 0; GradientStop gs2 = new GradientStop(); gs2.Color = _color2.ToWpfColor(); gs2.Offset = 1; GradientStopCollection gsc = new GradientStopCollection(); gsc.Add(gs1); gsc.Add(gs2); brush = new LinearGradientBrush(gsc, 0); brush.StartPoint = new Point(0, 0); brush.EndPoint = new Point(1, 1); #endif } else { #if !SILVERLIGHT brush = new System.Windows.Media.LinearGradientBrush(_color1.ToWpfColor(), _color2.ToWpfColor(), _point1, _point2); //brush = new System.Drawing.Drawing2D.LinearGradientBrush( // point1.ToPointF(), point2.ToPointF(), // color1.ToGdiColor(), color2.ToGdiColor()); #else GradientStop gs1 = new GradientStop(); gs1.Color = _color1.ToWpfColor(); gs1.Offset = 0; GradientStop gs2 = new GradientStop(); gs2.Color = _color2.ToWpfColor(); gs2.Offset = 1; GradientStopCollection gsc = new GradientStopCollection(); gsc.Add(gs1); gsc.Add(gs2); brush = new LinearGradientBrush(gsc, 0); brush.StartPoint = _point1; brush.EndPoint = _point2; #endif } if (!_matrix.IsIdentity) { #if !SILVERLIGHT brush.Transform = new MatrixTransform(_matrix.ToWpfMatrix()); #else MatrixTransform transform = new MatrixTransform(); transform.Matrix = _matrix.ToWpfMatrix(); brush.Transform = transform; #endif } return(brush); }
void CreateDeviceResources() { uint width = (uint)host.ActualWidth; uint height = (uint)host.ActualHeight; // If we don't have a device, need to create one now and all // accompanying D3D resources. CreateDevice(); Factory dxgiFactory = Factory.Create(); SwapChainDescription swapDesc = new SwapChainDescription { BufferDescription = new ModeDescription { Width = width, Height = height, Format = Format.R8G8B8A8UNorm, RefreshRate = new Rational { Numerator = 60, Denominator = 1 } }, SampleDescription = new SampleDescription { Count = 1, Quality = 0 }, BufferUsage = UsageOptions.RenderTargetOutput, BufferCount = 1, OutputWindowHandle = host.Handle, Windowed = true }; swapChain = dxgiFactory.CreateSwapChain( device, swapDesc); // Create rasterizer state object RasterizerDescription rsDesc = new RasterizerDescription(); rsDesc.AntiAliasedLineEnable = false; rsDesc.CullMode = CullMode.None; rsDesc.DepthBias = 0; rsDesc.DepthBiasClamp = 0; rsDesc.DepthClipEnable = true; rsDesc.FillMode = D3D10.FillMode.Solid; rsDesc.FrontCounterclockwise = false; // Must be FALSE for 10on9 rsDesc.MultisampleEnable = false; rsDesc.ScissorEnable = false; rsDesc.SlopeScaledDepthBias = 0; rasterizerState = device.CreateRasterizerState( rsDesc); device.RS.State = rasterizerState; // If we don't have a D2D render target, need to create all of the resources // required to render to one here. // Ensure that nobody is holding onto one of the old resources device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { null }); InitializeDepthStencil(width, height); // Create views on the RT buffers and set them on the device RenderTargetViewDescription renderDesc = new RenderTargetViewDescription(); renderDesc.Format = Format.R8G8B8A8UNorm; renderDesc.ViewDimension = RenderTargetViewDimension.Texture2D; Texture2DRenderTargetView renderView = renderDesc.Texture2D; renderView.MipSlice = 0; renderDesc.Texture2D = renderView; using (D3DResource spBackBufferResource = swapChain.GetBuffer <D3DResource>(0)) { renderTargetView = device.CreateRenderTargetView( spBackBufferResource, renderDesc); } device.OM.RenderTargets = new OutputMergerRenderTargets(new RenderTargetView[] { renderTargetView }, depthStencilView); SetViewport(width, height); // Create a D2D render target which can draw into the surface in the swap chain RenderTargetProperties props = new RenderTargetProperties( RenderTargetType.Default, new PixelFormat(Format.Unknown, AlphaMode.Premultiplied), 96, 96, RenderTargetUsages.None, FeatureLevel.Default); // Allocate a offscreen D3D surface for D2D to render our 2D content into Texture2DDescription tex2DDescription = new Texture2DDescription { ArraySize = 1, BindingOptions = BindingOptions.RenderTarget | BindingOptions.ShaderResource, CpuAccessOptions = CpuAccessOptions.None, Format = Format.R8G8B8A8UNorm, Height = 4096, Width = 512, MipLevels = 1, MiscellaneousResourceOptions = MiscellaneousResourceOptions.None, SampleDescription = new SampleDescription { Count = 1, Quality = 0 }, Usage = Usage.Default }; offscreenTexture = device.CreateTexture2D(tex2DDescription); using (Surface dxgiSurface = offscreenTexture.GraphicsSurface) { // Create a D2D render target which can draw into our offscreen D3D surface renderTarget = d2DFactory.CreateGraphicsSurfaceRenderTarget( dxgiSurface, props); } PixelFormat alphaOnlyFormat = new PixelFormat(Format.A8UNorm, AlphaMode.Premultiplied); opacityRenderTarget = renderTarget.CreateCompatibleRenderTarget(CompatibleRenderTargetOptions.None, alphaOnlyFormat); // Load pixel shader // Open precompiled vertex shader // This file was compiled using DirectX's SDK Shader compilation tool: // fxc.exe /T fx_4_0 /Fo SciFiText.fxo SciFiText.fx shader = LoadResourceShader(device, "SciFiTextDemo.SciFiText.fxo"); // Obtain the technique technique = shader.GetTechniqueByName("Render"); // Obtain the variables worldMatrixVariable = shader.GetVariableByName("World").AsMatrix; viewMatrixVariable = shader.GetVariableByName("View").AsMatrix; projectionMarixVariable = shader.GetVariableByName("Projection").AsMatrix; diffuseVariable = shader.GetVariableByName("txDiffuse").AsShaderResource; // Create the input layout PassDescription passDesc = new PassDescription(); passDesc = technique.GetPassByIndex(0).Description; vertexLayout = device.CreateInputLayout( inputLayoutDescriptions, passDesc.InputAssemblerInputSignature, passDesc.InputAssemblerInputSignatureSize ); // Set the input layout device.IA.InputLayout = vertexLayout; IntPtr verticesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.VerticesInstance)); Marshal.StructureToPtr(VertexArray.VerticesInstance, verticesDataPtr, true); BufferDescription bd = new BufferDescription(); bd.Usage = Usage.Default; bd.ByteWidth = (uint)Marshal.SizeOf(VertexArray.VerticesInstance); bd.BindingOptions = BindingOptions.VertexBuffer; bd.CpuAccessOptions = CpuAccessOptions.None; bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None; SubresourceData InitData = new SubresourceData { SystemMemory = verticesDataPtr }; vertexBuffer = device.CreateBuffer(bd, InitData); Marshal.FreeHGlobal(verticesDataPtr); // Set vertex buffer uint stride = (uint)Marshal.SizeOf(typeof(SimpleVertex)); uint offset = 0; device.IA.SetVertexBuffers( 0, new D3DBuffer[] { vertexBuffer }, new uint[] { stride }, new uint[] { offset } ); IntPtr indicesDataPtr = Marshal.AllocHGlobal(Marshal.SizeOf(VertexArray.IndicesInstance)); Marshal.StructureToPtr(VertexArray.IndicesInstance, indicesDataPtr, true); bd.Usage = Usage.Default; bd.ByteWidth = (uint)Marshal.SizeOf(VertexArray.IndicesInstance); bd.BindingOptions = BindingOptions.IndexBuffer; bd.CpuAccessOptions = CpuAccessOptions.None; bd.MiscellaneousResourceOptions = MiscellaneousResourceOptions.None; InitData.SystemMemory = indicesDataPtr; facesIndexBuffer = device.CreateBuffer( bd, InitData ); Marshal.FreeHGlobal(indicesDataPtr); // Set primitive topology device.IA.PrimitiveTopology = PrimitiveTopology.TriangleList; // Convert the D2D texture into a Shader Resource View textureResourceView = device.CreateShaderResourceView( offscreenTexture); // Initialize the world matrices worldMatrix = Matrix4x4F.Identity; // Initialize the view matrix Vector3F Eye = new Vector3F(0.0f, 0.0f, 13.0f); Vector3F At = new Vector3F(0.0f, -3.5f, 45.0f); Vector3F Up = new Vector3F(0.0f, 1.0f, 0.0f); viewMatrix = Camera.MatrixLookAtLH(Eye, At, Up); // Initialize the projection matrix projectionMatrix = Camera.MatrixPerspectiveFovLH( (float)Math.PI * 0.1f, width / (float)height, 0.1f, 100.0f); // Update Variables that never change viewMatrixVariable.Matrix = viewMatrix; projectionMarixVariable.Matrix = projectionMatrix; GradientStop[] gradientStops = { new GradientStop(0.0f, new ColorF(GetColorValues(System.Windows.Media.Colors.Yellow))), new GradientStop(1.0f, new ColorF(GetColorValues(System.Windows.Media.Colors.Black))) }; GradientStopCollection spGradientStopCollection = renderTarget.CreateGradientStopCollection( gradientStops, Gamma.StandardRgb, ExtendMode.Clamp); // Create a linear gradient brush for text textBrush = renderTarget.CreateLinearGradientBrush( new LinearGradientBrushProperties(new Point2F(0, 0), new Point2F(0, -2048)), spGradientStopCollection ); }
protected override void OnAttached() { var view = Control ?? Container; var effect = Element.Effects.OfType <GradientEffect>()?.FirstOrDefault(e => e is GradientEffect); if (effect == null) { return; } var gradientStops = new GradientStopCollection { new GradientStop() { Color = effect.StartColor.ToWindowsColor(), Offset = 0 }, new GradientStop() { Color = effect.EndColor.ToWindowsColor(), Offset = .5 } }; LinearGradientBrush background = null; switch (effect.Direction) { default: case GradientDirection.ToRight: background = new LinearGradientBrush { GradientStops = gradientStops, StartPoint = new Windows.Foundation.Point(0, 0.5), EndPoint = new Windows.Foundation.Point(1, 0.5) }; break; case GradientDirection.ToLeft: background = new LinearGradientBrush { GradientStops = gradientStops, StartPoint = new Windows.Foundation.Point(1, 0.5), EndPoint = new Windows.Foundation.Point(0, 0.5) }; break; case GradientDirection.ToTop: background = new LinearGradientBrush { GradientStops = gradientStops, StartPoint = new Windows.Foundation.Point(0.5, 1), EndPoint = new Windows.Foundation.Point(0.5, 0) }; break; case GradientDirection.ToBottom: background = new LinearGradientBrush { GradientStops = gradientStops, StartPoint = new Windows.Foundation.Point(0.5, 0), EndPoint = new Windows.Foundation.Point(0.5, 1) }; break; case GradientDirection.ToTopLeft: background = new LinearGradientBrush { GradientStops = gradientStops, StartPoint = new Windows.Foundation.Point(1, 1), EndPoint = new Windows.Foundation.Point(0, 0) }; break; case GradientDirection.ToTopRight: background = new LinearGradientBrush { GradientStops = gradientStops, StartPoint = new Windows.Foundation.Point(0, 1), EndPoint = new Windows.Foundation.Point(1, 0) }; break; case GradientDirection.ToBottomLeft: background = new LinearGradientBrush { GradientStops = gradientStops, StartPoint = new Windows.Foundation.Point(1, 0), EndPoint = new Windows.Foundation.Point(0, 1) }; break; case GradientDirection.ToBottomRight: background = new LinearGradientBrush { GradientStops = gradientStops, StartPoint = new Windows.Foundation.Point(0, 0), EndPoint = new Windows.Foundation.Point(1, 1) }; break; } if (view is LayoutRenderer renderer) { renderer.Background = background; } }
/// <summary> /// Approximate Color under mouse pointer on the Rainbow rectangle. /// </summary> /// <param name="e"></param> private void SetColorFromRainbow(MouseEventArgs e) { LinearGradientBrush br = (LinearGradientBrush)Rainbow.Fill; GradientStopCollection gs = br.GradientStops; float y = (float)(e.GetPosition(Rainbow).Y / Rainbow.ActualHeight); if (y > 1) { y = 1; } if (y < 0) { y = 0; } float rVal = 0; float gVal = 0; float bVal = 0; for (int i = 1; i < gs.Count; i++) { if (y <= gs[i].Offset) { y = (float)((y - gs[i - 1].Offset) / Math.Abs(gs[i].Offset - gs[i - 1].Offset)); rVal = (gs[i].Color.R - gs[i - 1].Color.R) * y + gs[i - 1].Color.R; gVal = (gs[i].Color.G - gs[i - 1].Color.G) * y + gs[i - 1].Color.G; bVal = (gs[i].Color.B - gs[i - 1].Color.B) * y + gs[i - 1].Color.B; break; } } Color c = Color.FromRgb((byte)rVal, (byte)gVal, (byte)bVal); byte[] pixels = new byte[3] { c.R, c.G, c.B }; // fix for setting PreviewColor, when all parts of Color are equal if ((Color.R == Color.G) && (Color.G == Color.B)) { PreviewColor.Color = c; return; } byte max = (byte)Math.Max(Color.R, Math.Max(Color.G, Color.B)); byte min = (byte)Math.Min(Color.R, Math.Min(Color.G, Color.B)); for (int i = 0; i < 3; i++) { if (pixels[i] == 255) { pixels[i] = max; } else { if (pixels[i] == 0) { pixels[i] = min; } else { double coef = (double)pixels[i] / 255; pixels[i] = (byte)(min + (max - min) * coef); } } } Color = Color.FromRgb(pixels[0], pixels[1], pixels[2]); }
/// <summary> /// Initializes a new instance of the <see cref="RadialGradientBrush"/> class with GradientStops set to the passed-in collection. /// </summary> /// <param name="gradientStopCollection"> GradientStopCollection to set on this brush. </param> public RadialGradientBrush(GradientStopCollection gradientStopCollection) : this() { GradientStops = gradientStopCollection; }
public GradientBrush() { GradientStops = new GradientStopCollection(); }
/// <summary> /// 绘制当前时间进度 /// </summary> private void DrawTimeProcess(bool isSyncProcess = false) { if (_XAxis == null) { return; } if (_TimeProcessUI != null && _TimeProcessUI.Count > 0) { _TimeProcessUI.ForEach(u => _Container.Children.Remove(u)); _TimeProcessUI.Clear(); } processButtonGrid.Children.Clear(); bool isOverMin, isOverMax; DateTime time = DateTime.Now;//DateTime.Now.Date.AddHours(9);// double x = _XAxis.LocalTransform(time, out isOverMin, out isOverMax); GradientStopCollection GradientStops = new GradientStopCollection(); LinearGradientBrush bgBrush; Border processBorder; double TicStartY = StartPoint.Y + _drawHeight * TicLabelHeightPercent; double TicEndY = TicStartY + _drawHeight * TicAreaHeightPercent; double leftMargin = -6; double rightMargin = 6; if (!isOverMin) { //LinearGradientBrush bgBrush = new LinearGradientBrush(Color.FromRgb(0x65, 0xD3, 0xAC), Color.FromRgb(0x29, 0xB9, 0xB6), new Point(0, 0), new Point(0, 1)); GradientStops.Add(new GradientStop(Color.FromRgb(0x65, 0xD3, 0xAC), 0.0)); GradientStops.Add(new GradientStop(Color.FromRgb(0x59, 0xE6, 0xCB), 0.3)); GradientStops.Add(new GradientStop(Color.FromRgb(0x45, 0xD9, 0xC7), 0.7)); GradientStops.Add(new GradientStop(Color.FromRgb(0x29, 0xB9, 0xB6), 1.0)); bgBrush = new LinearGradientBrush(GradientStops, new Point(0, 0), new Point(0, 1)); processBorder = new Border(); processBorder.Width = x - AxisStartPoint.X - leftMargin + rightMargin; processBorder.Height = _drawHeight * TicAreaHeightPercent; processBorder.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; processBorder.VerticalAlignment = System.Windows.VerticalAlignment.Top; processBorder.CornerRadius = new CornerRadius(5); processBorder.Background = bgBrush; processBorder.Margin = new Thickness(AxisStartPoint.X + leftMargin, TicStartY, 0, 0); //processBorder.Opacity = 0.5; _Container.Children.Add(processBorder); _TimeProcessUI.Add(processBorder); } DrawRescueTimes(TicStartY); //绘制抢救时间段 if (time < _XAxis.MaxTime) { GradientStops = new GradientStopCollection(); GradientStops.Add(new GradientStop(Color.FromRgb(0x31, 0xAA, 0xCE), 0.0)); GradientStops.Add(new GradientStop(Color.FromRgb(0x38, 0xBD, 0xE3), 0.3)); GradientStops.Add(new GradientStop(Color.FromRgb(0x38, 0xBC, 0xE2), 0.7)); GradientStops.Add(new GradientStop(Color.FromRgb(0x37, 0xAD, 0xD1), 1.0)); bgBrush = new LinearGradientBrush(GradientStops, new Point(0, 0), new Point(0, 1)); processBorder = new Border(); processBorder.Width = _XAxis.MaxPix - x; processBorder.Height = _drawHeight * TicAreaHeightPercent; processBorder.HorizontalAlignment = System.Windows.HorizontalAlignment.Left; processBorder.VerticalAlignment = System.Windows.VerticalAlignment.Top; processBorder.CornerRadius = new CornerRadius(5); processBorder.Background = bgBrush; processBorder.Margin = new Thickness(x, TicStartY, 0, 0); _Container.Children.Add(processBorder); _TimeProcessUI.Add(processBorder); //拉杆 if (!isOverMin && !isOverMax) { double width = processBorder.Height * 0.8; double ContainerWidth = width * 2.5; processButtonPopup.Width = ContainerWidth * 1.2; processButtonPopup.Height = ContainerWidth * 1.2; processButtonPopup.Margin = new Thickness(x, 0, 0, 0); Point startP = new Point(ContainerWidth / 2, ContainerWidth / 2); Path Circle3 = GetProcessButton(startP, new Size(width * 2.5, width * 2.5), Color.FromRgb(0xE5, 0xF6, 0xF5), Color.FromRgb(0xE5, 0xF6, 0xF5)); Circle3.Opacity = 0.7; processButtonGrid.Children.Add(Circle3); Path Circle2 = GetProcessButton(startP, new Size(width * 1.8, width * 1.8), Color.FromRgb(0xFF, 0xFF, 0xFF), Color.FromRgb(0xFF, 0xFF, 0xFF)); processButtonGrid.Children.Add(Circle2); Path Circle1 = GetProcessButton(startP, new Size(width, width), Color.FromRgb(0x00, 0xD8, 0xAE), Color.FromRgb(0x00, 0xD8, 0xAE)); processButtonGrid.Children.Add(Circle1); double y = TicStartY + processBorder.Height / 2 - ContainerWidth / 2; processButtonPopup.PlacementRectangle = new Rect(x - ContainerWidth / 2, y, ContainerWidth, ContainerWidth); processButtonPopup.IsOpen = true; } } if (isSyncProcess && DrawTimeProcessAction != null) { DrawTimeProcessAction(time); } }
public ConicGradientBrushShader() { GradientStops = new GradientStopCollection(); }
public static LinearGradientBrush ConstructBrush(SvgLinearGradientElement gradient, Rect bounds, Matrix transform) { if (gradient.Stops.Count == 0) { return(null); } double x1 = gradient.X1.AnimVal.Value; double x2 = gradient.X2.AnimVal.Value; double y1 = gradient.Y1.AnimVal.Value; double y2 = gradient.Y2.AnimVal.Value; GradientStopCollection gradientStops = ToGradientStops(gradient.Stops); LinearGradientBrush brush = new LinearGradientBrush(gradientStops, new Point(x1, y1), new Point(x2, y2)); SvgSpreadMethod spreadMethod = SvgSpreadMethod.Pad; if (gradient.SpreadMethod != null) { spreadMethod = (SvgSpreadMethod)gradient.SpreadMethod.AnimVal; GradientSpreadMethod sm; if (TryGetSpreadMethod(spreadMethod, out sm)) { brush.SpreadMethod = sm; } } SvgUnitType mappingMode = SvgUnitType.ObjectBoundingBox; if (gradient.GradientUnits != null) { mappingMode = (SvgUnitType)gradient.GradientUnits.AnimVal; if (mappingMode == SvgUnitType.ObjectBoundingBox) { brush.MappingMode = BrushMappingMode.RelativeToBoundingBox; } else if (mappingMode == SvgUnitType.UserSpaceOnUse) { brush.MappingMode = BrushMappingMode.Absolute; brush.StartPoint.Offset(bounds.X, bounds.Y); brush.EndPoint.Offset(bounds.X, bounds.Y); } } Matrix brushTransform = ToWpfMatrix(((SvgTransformList)gradient.GradientTransform.AnimVal).TotalMatrix); if (mappingMode == SvgUnitType.UserSpaceOnUse) { brushTransform *= transform; } if (!brushTransform.IsIdentity) { brush.Transform = new MatrixTransform(brushTransform); } string colorInterpolation = gradient.GetPropertyValue("color-interpolation"); if (!string.IsNullOrWhiteSpace(colorInterpolation)) { if (colorInterpolation == "linearRGB") { brush.ColorInterpolationMode = ColorInterpolationMode.ScRgbLinearInterpolation; } else { brush.ColorInterpolationMode = ColorInterpolationMode.SRgbLinearInterpolation; } } return(brush); }
private static void OnRenderPressedChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { ImageButtonChrome buttonChrome = (ImageButtonChrome)o; if (!buttonChrome.Animates) { buttonChrome._localResources = null; buttonChrome.InvalidateVisual(); return; } if ((bool)e.NewValue) { if (buttonChrome._localResources == null) { buttonChrome._localResources = new ImageButtonChrome.LocalResources(); buttonChrome.InvalidateVisual(); } Duration duration = new Duration(TimeSpan.FromSeconds(0.1)); DoubleAnimation animation = new DoubleAnimation(1.0, duration); buttonChrome.BackgroundOverlay.BeginAnimation(Brush.OpacityProperty, animation); buttonChrome.BorderOverlayPen.Brush.BeginAnimation(Brush.OpacityProperty, animation); buttonChrome.LeftDropShadowBrush.BeginAnimation(Brush.OpacityProperty, animation); buttonChrome.TopDropShadowBrush.BeginAnimation(Brush.OpacityProperty, animation); animation = new DoubleAnimation(0.0, duration); buttonChrome.InnerBorderPen.Brush.BeginAnimation(Brush.OpacityProperty, animation); ColorAnimation animation2 = new ColorAnimation(Color.FromRgb(194, 228, 246), duration); GradientStopCollection gradientStops = ((LinearGradientBrush)buttonChrome.BackgroundOverlay).GradientStops; gradientStops[0].BeginAnimation(GradientStop.ColorProperty, animation2); gradientStops[1].BeginAnimation(GradientStop.ColorProperty, animation2); animation2 = new ColorAnimation(Color.FromRgb(171, 218, 243), duration); gradientStops[2].BeginAnimation(GradientStop.ColorProperty, animation2); animation2 = new ColorAnimation(Color.FromRgb(144, 203, 235), duration); gradientStops[3].BeginAnimation(GradientStop.ColorProperty, animation2); animation2 = new ColorAnimation(Color.FromRgb(44, 98, 139), duration); buttonChrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.ColorProperty, animation2); return; } if (buttonChrome._localResources == null) { buttonChrome.InvalidateVisual(); return; } bool renderMouseOver = buttonChrome.RenderMouseOver; Duration duration2 = new Duration(TimeSpan.FromSeconds(0.1)); DoubleAnimation doubleAnimation = new DoubleAnimation(); doubleAnimation.Duration = duration2; buttonChrome.LeftDropShadowBrush.BeginAnimation(Brush.OpacityProperty, doubleAnimation); buttonChrome.TopDropShadowBrush.BeginAnimation(Brush.OpacityProperty, doubleAnimation); buttonChrome.InnerBorderPen.Brush.BeginAnimation(Brush.OpacityProperty, doubleAnimation); if (!renderMouseOver) { buttonChrome.BorderOverlayPen.Brush.BeginAnimation(Brush.OpacityProperty, doubleAnimation); buttonChrome.BackgroundOverlay.BeginAnimation(Brush.OpacityProperty, doubleAnimation); } ColorAnimation colorAnimation = new ColorAnimation(); colorAnimation.Duration = duration2; buttonChrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.ColorProperty, colorAnimation); GradientStopCollection gradientStops2 = ((LinearGradientBrush)buttonChrome.BackgroundOverlay).GradientStops; gradientStops2[0].BeginAnimation(GradientStop.ColorProperty, colorAnimation); gradientStops2[1].BeginAnimation(GradientStop.ColorProperty, colorAnimation); gradientStops2[2].BeginAnimation(GradientStop.ColorProperty, colorAnimation); gradientStops2[3].BeginAnimation(GradientStop.ColorProperty, colorAnimation); }
private static void OnRenderPressedChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { MyButtonChrome chrome = (MyButtonChrome)o; if (chrome.Animates) { if ((bool)e.NewValue) { if (chrome._localResources == null) { chrome._localResources = new LocalResources(); chrome.InvalidateVisual(); } Duration duration = new Duration(TimeSpan.FromSeconds(0.1)); DoubleAnimation animation = new DoubleAnimation(1.0, duration); chrome.BackgroundOverlay.BeginAnimation(Brush.OpacityProperty, animation); chrome.BorderOverlayPen.Brush.BeginAnimation(Brush.OpacityProperty, animation); chrome.LeftDropShadowBrush.BeginAnimation(Brush.OpacityProperty, animation); chrome.TopDropShadowBrush.BeginAnimation(Brush.OpacityProperty, animation); animation = new DoubleAnimation(0.0, duration); chrome.InnerBorderPen.Brush.BeginAnimation(Brush.OpacityProperty, animation); ColorAnimation animation2 = new ColorAnimation(Color.FromRgb(0xc2, 0xe4, 0xf6), duration); GradientStopCollection gradientStops = ((LinearGradientBrush)chrome.BackgroundOverlay).GradientStops; gradientStops[0].BeginAnimation(GradientStop.ColorProperty, animation2); gradientStops[1].BeginAnimation(GradientStop.ColorProperty, animation2); animation2 = new ColorAnimation(Color.FromRgb(0xab, 0xda, 0xf3), duration); gradientStops[2].BeginAnimation(GradientStop.ColorProperty, animation2); animation2 = new ColorAnimation(Color.FromRgb(0x90, 0xcb, 0xeb), duration); gradientStops[3].BeginAnimation(GradientStop.ColorProperty, animation2); animation2 = new ColorAnimation(Color.FromRgb(0x2c, 0x62, 0x8b), duration); chrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.ColorProperty, animation2); } else if (chrome._localResources == null) { chrome.InvalidateVisual(); } else { bool renderMouseOver = chrome.RenderMouseOver; Duration duration2 = new Duration(TimeSpan.FromSeconds(0.1)); DoubleAnimation animation3 = new DoubleAnimation { Duration = duration2 }; chrome.LeftDropShadowBrush.BeginAnimation(Brush.OpacityProperty, animation3); chrome.TopDropShadowBrush.BeginAnimation(Brush.OpacityProperty, animation3); chrome.InnerBorderPen.Brush.BeginAnimation(Brush.OpacityProperty, animation3); if (!renderMouseOver) { chrome.BorderOverlayPen.Brush.BeginAnimation(Brush.OpacityProperty, animation3); chrome.BackgroundOverlay.BeginAnimation(Brush.OpacityProperty, animation3); } ColorAnimation animation4 = new ColorAnimation { Duration = duration2 }; chrome.BorderOverlayPen.Brush.BeginAnimation(SolidColorBrush.ColorProperty, animation4); GradientStopCollection stops2 = ((LinearGradientBrush)chrome.BackgroundOverlay).GradientStops; stops2[0].BeginAnimation(GradientStop.ColorProperty, animation4); stops2[1].BeginAnimation(GradientStop.ColorProperty, animation4); stops2[2].BeginAnimation(GradientStop.ColorProperty, animation4); stops2[3].BeginAnimation(GradientStop.ColorProperty, animation4); } } else { chrome._localResources = null; chrome.InvalidateVisual(); } }
// Creates an array of brushes needed to render this private static Brush[] CreateBrushes(Color c, CornerRadius cornerRadius) { Brush[] brushes = new Brush[9]; // Create center brush brushes[Center] = new SolidColorBrush(c); brushes[Center].Freeze(); // Sides GradientStopCollection sideStops = CreateStops(c, 0); LinearGradientBrush top = new LinearGradientBrush(sideStops, new Point(0, 1), new Point(0, 0)); top.Freeze(); brushes[Top] = top; LinearGradientBrush left = new LinearGradientBrush(sideStops, new Point(1, 0), new Point(0, 0)); left.Freeze(); brushes[Left] = left; LinearGradientBrush right = new LinearGradientBrush(sideStops, new Point(0, 0), new Point(1, 0)); right.Freeze(); brushes[Right] = right; LinearGradientBrush bottom = new LinearGradientBrush(sideStops, new Point(0, 0), new Point(0, 1)); bottom.Freeze(); brushes[Bottom] = bottom; // Corners // Use side stops if the corner radius is 0 GradientStopCollection topLeftStops; if (cornerRadius.TopLeft == 0) { topLeftStops = sideStops; } else { topLeftStops = CreateStops(c, cornerRadius.TopLeft); } RadialGradientBrush topLeft = new RadialGradientBrush(topLeftStops); topLeft.RadiusX = 1; topLeft.RadiusY = 1; topLeft.Center = new Point(1, 1); topLeft.GradientOrigin = new Point(1, 1); topLeft.Freeze(); brushes[TopLeft] = topLeft; // Reuse previous stops if corner radius is the same as side or top left GradientStopCollection topRightStops; if (cornerRadius.TopRight == 0) { topRightStops = sideStops; } else if (cornerRadius.TopRight == cornerRadius.TopLeft) { topRightStops = topLeftStops; } else { topRightStops = CreateStops(c, cornerRadius.TopRight); } RadialGradientBrush topRight = new RadialGradientBrush(topRightStops); topRight.RadiusX = 1; topRight.RadiusY = 1; topRight.Center = new Point(0, 1); topRight.GradientOrigin = new Point(0, 1); topRight.Freeze(); brushes[TopRight] = topRight; // Reuse previous stops if corner radius is the same as any of the previous radii GradientStopCollection bottomLeftStops; if (cornerRadius.BottomLeft == 0) { bottomLeftStops = sideStops; } else if (cornerRadius.BottomLeft == cornerRadius.TopLeft) { bottomLeftStops = topLeftStops; } else if (cornerRadius.BottomLeft == cornerRadius.TopRight) { bottomLeftStops = topRightStops; } else { bottomLeftStops = CreateStops(c, cornerRadius.BottomLeft); } RadialGradientBrush bottomLeft = new RadialGradientBrush(bottomLeftStops); bottomLeft.RadiusX = 1; bottomLeft.RadiusY = 1; bottomLeft.Center = new Point(1, 0); bottomLeft.GradientOrigin = new Point(1, 0); bottomLeft.Freeze(); brushes[BottomLeft] = bottomLeft; // Reuse previous stops if corner radius is the same as any of the previous radii GradientStopCollection bottomRightStops; if (cornerRadius.BottomRight == 0) { bottomRightStops = sideStops; } else if (cornerRadius.BottomRight == cornerRadius.TopLeft) { bottomRightStops = topLeftStops; } else if (cornerRadius.BottomRight == cornerRadius.TopRight) { bottomRightStops = topRightStops; } else if (cornerRadius.BottomRight == cornerRadius.BottomLeft) { bottomRightStops = bottomLeftStops; } else { bottomRightStops = CreateStops(c, cornerRadius.BottomRight); } RadialGradientBrush bottomRight = new RadialGradientBrush(bottomRightStops); bottomRight.RadiusX = 1; bottomRight.RadiusY = 1; bottomRight.Center = new Point(0, 0); bottomRight.GradientOrigin = new Point(0, 0); bottomRight.Freeze(); brushes[BottomRight] = bottomRight; return(brushes); }
public LinearGradientBrush(GradientStopCollection gradientStops, Point startPoint, Point endPoint) { GradientStops = gradientStops; StartPoint = startPoint; EndPoint = endPoint; }
private void worker_DoWork_IFC4(IfcStore xModel) { //in TTValueColor hashTable we will have <TT, Color> key-value pairs //get all colors available in a list var _Colors = GetStaticPropertyBag(typeof(Colors)).ToList(); Console.WriteLine("Total of " + _Colors.Count + " Colors available!!"); // DiffuseMaterial NoTTMaterial = new DiffuseMaterial(new SolidColorBrush((Color)_Colors[_Colors.Count - 1].Value));//in case of no TT being available the Color used will be the last one in the list // Loop through Entities and visualize them in the viewport Console.WriteLine("The elements r in total " + _xModel.Instances.OfType <Xbim.Ifc4.Kernel.IfcProduct>().Count() + "."); //TTValueColorAll.Add(-1, new TTColorAvailable2(-1, -1, TTCannotBeCalculated, false));//black for the problematic ones foreach (var item in _xModel.Instances.OfType <Xbim.Ifc4.Kernel.IfcProduct>()) { TTColorAvailable2 ttColorAv = GetTTifExistsCalculateifNot_IFC4(item);//it TT-property does not exist, it calculates it // Console.WriteLine("TT = "+TT); ttColorAv.divedTT = Math.Truncate(ttColorAv.TT); Color thisColor; if (TTValueColorAll.ContainsKey(ttColorAv.divedTT)) { thisColor = ((TTColorAvailable2)TTValueColorAll[ttColorAv.divedTT]).col; } else //new TT - Material(Color) pair { if (ttColorAv.divedTT == -1) { ttColorAv.col = Colors.Black; } else { thisColor = (Color)_Colors[TTValueColorAll.Count].Value; int thisC = TTValueColorAll.Count; while (thisColor.Equals(Colors.Black) || thisColor.Equals(Colors.Green) || thisColor.Equals(Colors.Red)) { thisColor = (Color)_Colors[++thisC].Value;//black, green n red r reserved, get the next one, sorry } ttColorAv.col = thisColor; } TTValueColorAll.Add(ttColorAv.divedTT, ttColorAv); } } Console.WriteLine("The distinct TT-Values are " + TTValueColorAll.Keys.Count + " (distinct TT-Values)."); List <double> SortedTTs = TTValueColorAll.Keys.OfType <double>().ToList(); SortedTTs.Sort(); try { ((TTColorAvailable2)TTValueColorAll[SortedTTs[1]]).col = Colors.Green; } catch (ArgumentOutOfRangeException) { Console.WriteLine("Out of Range"); } try { ((TTColorAvailable2)TTValueColorAll[SortedTTs[SortedTTs.Count - 1]]).col = Colors.Red; } catch (ArgumentOutOfRangeException) { Console.WriteLine("Out of Range"); } foreach (var item in _xModel.Instances.OfType <Xbim.Ifc4.Kernel.IfcProduct>()) { var m = new MeshGeometry3D(); GetGeometryFromXbimModel_IFC4(m, item, XbimMatrix3D.Identity); DiffuseMaterial Material; TTColorAvailable2 thisOne = GetTTifExistsCalculateifNot_IFC4(item); thisOne.divedTT = Math.Truncate(thisOne.TT); Color thisColor; if (TTValueColorAll.Count >= 1) { thisColor = ((TTColorAvailable2)TTValueColorAll[thisOne.divedTT]).col; } else { thisColor = Colors.Gray; } Material = new DiffuseMaterial(new SolidColorBrush(thisColor)); var mb = new MeshBuilder(false, false); VisualizeMesh(mb, m, Material); } GradientStopCollection colorsCollection = new GradientStopCollection(); GradientStopCollection colorsCollectionAvailable = new GradientStopCollection(); GradientStopCollection colorsCollectionCalculated = new GradientStopCollection(); double i = 0; //Console.WriteLine("**"+SortedTTs.Count+"**"); SortedTTs.Remove(-1);//remove the NoTTColor(Black) we dont want it in our bar //Console.WriteLine("**" + SortedTTs.Count + "**"); double inc = 1.0 / SortedTTs.Count; for (int k = 0; k < SortedTTs.Count; k++) { // Color col = ((TTColorAvailable2)TTValueColorAll[TTRanges[k]]).col; Color col = ((TTColorAvailable2)TTValueColorAll[SortedTTs[k]]).col; colorsCollection.Add(new GradientStop(col, i)); i += inc; Console.WriteLine("**** TT of " + SortedTTs[k] + " is now in " + col + " ****"); } LinearGradientBrush colors = new LinearGradientBrush(colorsCollection, 0); // ProgressBar ColorBarAll = ControlElements[1] as ProgressBar; // ColorBarAll.Background = colors; ProgressBar ColorBarAll = ((EnergyVisualisationControl)ControlElements[0]).ColorBarAll; ColorBarAll.Background = colors; try { // var progressLabel = (SortedTTs[SortedTTs.Count - 1] + 1) / 5; // ((EnergyVisualisationControl)ControlElements[0]).MinTT.Content = "[" + 0 + "-" + (progressLabel * 1) + ")"; // 0 - 1 ((EnergyVisualisationControl)ControlElements[0]).MinTT.Content = "[" + SortedTTs[0] + "-" + (SortedTTs[0] + 1) + ")"; // ((EnergyVisualisationControl)ControlElements[0]).ProgressLabel1.Content = "[" + (progressLabel * 1) + "-" + (progressLabel * 2) + ")"; // 1,66 - 3 ((EnergyVisualisationControl)ControlElements[0]).ProgressLabel1.Content = "[" + SortedTTs[1] + "-" + (SortedTTs[1] + 1) + ")"; // ((EnergyVisualisationControl)ControlElements[0]).ProgressLabel2.Content = "[" + (progressLabel * 2) + "-" + (progressLabel * 3) + ")"; // 1,66 - 3 ((EnergyVisualisationControl)ControlElements[0]).ProgressLabel2.Content = "[" + SortedTTs[2] + "-" + (SortedTTs[2] + 1) + ")"; // ((EnergyVisualisationControl)ControlElements[0]).ProgressLabel3.Content = "[" + (progressLabel * 3) + "-" + (progressLabel * 4) + ")"; // 2,8 - 4 ((EnergyVisualisationControl)ControlElements[0]).ProgressLabel3.Content = "[" + SortedTTs[3] + "-" + (SortedTTs[3] + 1) + ")"; // ((EnergyVisualisationControl)ControlElements[0]).MaxTT.Content = "[" + (progressLabel * 4) + "-" + (SortedTTs[SortedTTs.Count - 1] + 1) + ")"; // 5 ((EnergyVisualisationControl)ControlElements[0]).MaxTT.Content = "[" + SortedTTs[4] + "-" + (SortedTTs[4] + 1) + ")"; } catch (ArgumentOutOfRangeException) { ((EnergyVisualisationControl)ControlElements[0]).MinTT.Visibility = Visibility.Hidden; ((EnergyVisualisationControl)ControlElements[0]).ProgressLabel1.Visibility = Visibility.Hidden; ((EnergyVisualisationControl)ControlElements[0]).ProgressLabel3.Visibility = Visibility.Hidden; ((EnergyVisualisationControl)ControlElements[0]).MaxTT.Visibility = Visibility.Hidden; ((EnergyVisualisationControl)ControlElements[0]).ColorBarAll.Visibility = Visibility.Hidden; ((EnergyVisualisationControl)ControlElements[0]).ProgressLabel2.Content = "Problems while Reading"; } }
public static bool Draw(ref System.Windows.Media.Imaging.WriteableBitmap bmp, List <Color> colors, bool horizontal) { if (colors.Count == 0) { return(false); } if (colors.Count == 1) { Rect rect = new Rect(); rect.Width = bmp.Width; rect.Height = bmp.Height; SolidColorBrush brush = new SolidColorBrush(colors[0]); RenderTargetBitmap bmp1 = new RenderTargetBitmap((int)(bmp.Width), (int)(bmp.Height), 96, 96, PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); Pen pen = new Pen(brush, 1.0); drawingContext.DrawRectangle(brush, pen, rect); drawingContext.Close(); bmp1.Render(drawingVisual); bmp = new System.Windows.Media.Imaging.WriteableBitmap(bmp1); } else if (horizontal) { int gradRectNum = colors.Count - 1; Rect rect = new Rect(); rect.Width = bmp.Width; rect.Height = bmp.Height; GradientStopCollection coll = new GradientStopCollection(); double step = 1.0 / gradRectNum; double x = 0.0; LinearGradientBrush brush = new LinearGradientBrush(); brush.StartPoint = new Point(0, 0); brush.EndPoint = new Point(1, 1); for (int j = 0; j < colors.Count(); ++j) { GradientStop stop = new GradientStop(colors[j], x); //coll.Add(stop); brush.GradientStops.Add(stop); x += step; } //LinearGradientBrush brush = new LinearGradientBrush(coll, 180.0); RenderTargetBitmap bmp1 = new RenderTargetBitmap((int)(bmp.Width), (int)(bmp.Height), 96, 96, PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); Pen pen = new Pen(brush, 1.0); drawingContext.DrawRectangle(brush, pen, rect); drawingContext.Close(); bmp1.Render(drawingVisual); bmp = new System.Windows.Media.Imaging.WriteableBitmap(bmp1); } else { int gradRectNum = colors.Count - 1; Rect rect = new Rect(); rect.Width = bmp.Width; rect.Height = bmp.Height; GradientStopCollection coll = new GradientStopCollection(); double step = 1.0 / gradRectNum; double x = 0.0; for (int j = 0; j < colors.Count(); ++j) { GradientStop stop = new GradientStop(colors[j], x); coll.Add(stop); x += step; } LinearGradientBrush brush = new LinearGradientBrush(coll, 90.0); RenderTargetBitmap bmp1 = new RenderTargetBitmap((int)(bmp.Width), (int)(bmp.Height), 96, 96, PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); Pen pen = new Pen(brush, 1.0); drawingContext.DrawRectangle(brush, pen, rect); drawingContext.Close(); bmp1.Render(drawingVisual); bmp = new System.Windows.Media.Imaging.WriteableBitmap(bmp1); } return(true); }
//</SnippetDocSerContentChanged> // ----------------------- AddBookmarkOrComment ----------------------- private void AddBookmarkOrComment(ListBox collection, Annotation ann) { if (ann.Cargos.Count <= 1) { ann.Cargos.Add( new AnnotationResource(FDPV.MasterPageNumber.ToString())); } Assembly a = System.Reflection.Assembly.GetExecutingAssembly(); string path = System.IO.Path.Combine( a.Location.Remove(a.Location.LastIndexOf('\\')), "GoButton.xaml"); StackPanel EntryInList = XamlReader.Load(File.OpenRead(path)) as StackPanel; EntryInList.Width = BookmarkList.Width - 10; Button GoToMark = LogicalTreeHelper.FindLogicalNode( EntryInList, "GoToMark") as Button; if (GoToMark != null) { GoToMark.Tag = ann; GoToMark.Click += new RoutedEventHandler(GoToMark_Click); } MenuItem GoToMenu = LogicalTreeHelper.FindLogicalNode( GoToMark.ContextMenu, "GoToMenu") as MenuItem; GoToMenu.Click += new RoutedEventHandler(GoToMark_Click); GoToMenu.Tag = ann; MenuItem DeleteMark = LogicalTreeHelper.FindLogicalNode( GoToMark.ContextMenu, "DeleteMark") as MenuItem; DeleteMark.Click += new RoutedEventHandler(DeleteMark_Click); DeleteMark.Tag = ann; System.Windows.Shapes.Path markPath = LogicalTreeHelper.FindLogicalNode(EntryInList, "MarkPath") as System.Windows.Shapes.Path; if ((collection == CommentsList) && (markPath != null)) { LinearGradientBrush lBrush = new LinearGradientBrush(); GradientStopCollection gColl = new GradientStopCollection(); GradientStop gStop = new GradientStop(Colors.LightGreen, 0); gColl.Add(gStop); lBrush.GradientStops = gColl; markPath.Fill = lBrush; } collection.Items.Add(EntryInList); TextBlock spText = LogicalTreeHelper.FindLogicalNode(EntryInList, "TB") as TextBlock; string MarkText = ""; if (spText != null) { ContentLocator cloc = ann.Anchors[0].ContentLocators[0] as ContentLocator; if (cloc == null) { return; } if (cloc.Parts.Count < 2) { return; } ContentLocatorPart cPart = cloc.Parts[1]; if (cPart == null) { return; } if (cPart.NameValuePairs["Segment0"] != null) { string[] charPos = cPart.NameValuePairs["Segment0"].Split(','); FlowDocument fd = FDPV.Document as FlowDocument; TextPointer tp = fd.ContentStart.GetPositionAtOffset( int.Parse(charPos[0]), LogicalDirection.Forward); if (tp == null) { return; } if (tp.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text) { MarkText += tp.GetTextInRun(LogicalDirection.Forward); } spText.Text = MarkText.Substring(0, (MarkText.Length > 150) ? 150 : MarkText.Length); } } }// end:AddBookmarkOrComment()
// Create the extruded text effect public MainWindow() { InitializeComponent(); // Create the outline strategy which is going to shift blit diagonally var strategyOutline = TextDesignerWpf.CanvasHelper.TextOutline(MaskColor.Blue, MaskColor.Blue, 4); WriteableBitmap canvas = TextDesignerWpf.CanvasHelper.GenImage((int)(image1.Width), (int)(image1.Height), Colors.White, 0); // Text context to store string and font info to be sent as parameter to Canvas methods TextContext context = new TextContext(); FontFamily fontFamily = new FontFamily("Arial Black"); context.fontFamily = fontFamily; context.fontStyle = FontStyles.Normal; context.fontWeight = FontWeights.Regular; context.nfontSize = 40; context.pszText = "CODING MONKEY"; context.ptDraw = new Point(0, 0); // the single mask outline WriteableBitmap maskOutline = TextDesignerWpf.CanvasHelper.GenMask(strategyOutline, (int)(image1.Width), (int)(image1.Height), new Point(0, 0), context); // the mask to store all the single mask blitted diagonally WriteableBitmap maskOutlineAll = TextDesignerWpf.CanvasHelper.GenImage((int)(image1.Width) + 10, (int)(image1.Height) + 10); RenderTargetBitmap bmp = new RenderTargetBitmap((int)(maskOutlineAll.Width), (int)(maskOutlineAll.Height), 96, 96, PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); DrawingContext drawingContext = drawingVisual.RenderOpen(); // blit diagonally for (int i = 0; i < 7; ++i) { drawingContext.DrawImage(maskOutline, new Rect((double)(i), (double)(i), maskOutline.Width, maskOutline.Height - 0.0)); } drawingContext.Close(); bmp.Render(drawingVisual); maskOutlineAll = new WriteableBitmap(bmp); // Measure the dimension of the big mask in order to generate the correct sized gradient image //============================================================================================= uint top = 0; uint bottom = 0; uint left = 0; uint right = 0; TextDesignerWpf.CanvasHelper.MeasureMaskLength(maskOutlineAll, MaskColor.Blue, ref top, ref left, ref bottom, ref right); right += 2; bottom += 2; // Generate the gradient image for the diagonal outline //======================================================= WriteableBitmap gradImage = TextDesignerWpf.CanvasHelper.GenImage((int)(right - left), (int)(bottom - top)); List <Color> listColors = new List <Color>(); listColors.Add(Colors.DarkGreen); listColors.Add(Colors.YellowGreen); DrawGradient.Draw(ref gradImage, listColors, false); // Because Canvas::ApplyImageToMask requires all image to have same dimensions, // we have to blit our small gradient image onto a temp image as big as the canvas //=================================================================================== WriteableBitmap gradBlitted = TextDesignerWpf.CanvasHelper.GenImage((int)(image1.Width), (int)(image1.Height)); byte[] pixels2 = new byte[gradImage.PixelHeight * gradImage.PixelWidth * gradImage.Format.BitsPerPixel / 8]; gradImage.CopyPixels(pixels2, gradImage.BackBufferStride, 0); gradBlitted.WritePixels(new Int32Rect((int)left, (int)top, (int)(gradImage.Width), (int)(gradImage.Height)), pixels2, gradImage.BackBufferStride, 0); TextDesignerWpf.CanvasHelper.ApplyImageToMask(gradBlitted, maskOutlineAll, canvas, MaskColor.Blue, false); // Create strategy and mask image for the text body //=================================================== var strategyText = TextDesignerWpf.CanvasHelper.TextNoOutline(MaskColor.Blue); WriteableBitmap maskText = TextDesignerWpf.CanvasHelper.GenMask(strategyText, (int)(image1.Width), (int)(image1.Height), new Point(0, 0), context); // Measure the dimension required for text body using the mask //============================================================= top = 0; bottom = 0; left = 0; right = 0; TextDesignerWpf.CanvasHelper.MeasureMaskLength(maskText, MaskColor.Blue, ref top, ref left, ref bottom, ref right); top -= 2; left -= 2; right += 2; bottom += 2; GradientStopCollection coll = new GradientStopCollection(); GradientStop stop = new GradientStop(Colors.Orange, 0.0); coll.Add(stop); stop = new GradientStop(Colors.OrangeRed, 1.0); coll.Add(stop); // Create the gradient brush for the text body LinearGradientBrush gradTextbrush = new LinearGradientBrush(coll, 90.0); // Create the actual strategy for the text body used for rendering, with the gradient brush var strategyText2 = TextDesignerWpf.CanvasHelper.TextNoOutline(gradTextbrush); // Draw the newly created strategy onto the canvas TextDesignerWpf.CanvasHelper.DrawTextImage(strategyText2, ref canvas, new Point(0, 0), context); // Finally blit the rendered image onto the window by assigning canvas to the image control image1.Source = canvas; }
public void SetProperties(List <wColor> ColorSet, List <double> GradientParameters, List <string> LegendTitles, int GradientWidth, bool IsHorizontalOrientation, int Position, bool IsExtentLabeled, bool HasTickMarks, bool IsLight, bool IsFlipped) { canvas = new Canvas(); AnnotationBar = new Grid(); TopLabel = new Label(); Labels = new List <Label>(); Element.Children.Clear(); AnnotationBar.Children.Clear(); Labels.Clear(); Parameters = GradientParameters; Titles = LegendTitles; BarWidth = GradientWidth; IsHorizontal = IsHorizontalOrientation; IsExtent = IsExtentLabeled; HasTick = HasTickMarks; Gradient = new wGradient(ColorSet, Parameters, !IsHorizontal).ToMediaGradient(); SetFontColor(IsLight); SetTickOrientation(IsFlipped); if (IsFlipped) { TextRotation = 90.0; } else { TextRotation = 0.0; } if (IsHorizontal) { TopLabel.Content = Titles[0]; } else { TopLabel.Content = Titles[Titles.Count - 1]; } if (IsHorizontal) { Element.ColumnDefinitions[0].Width = new GridLength(0, GridUnitType.Auto); Element.ColumnDefinitions[1].Width = new GridLength(100, GridUnitType.Star); Element.RowDefinitions[0].Height = new GridLength(0, GridUnitType.Auto); Element.RowDefinitions[1].Height = new GridLength(100, GridUnitType.Star); switch (Position) { case 0: SetDirections(true, false); SetLabel(new Tuple <int, int>(0, 0)); SetLabels(new Tuple <int, int>(1, 0), false); SetGradient(Gradient, new Tuple <int, int>(1, 1), true); break; case 1: SetDirections(true, true); SetLabel(new Tuple <int, int>(0, 1)); SetLabels(new Tuple <int, int>(1, 1), false); SetGradient(Gradient, new Tuple <int, int>(1, 0), true); break; case 2: SetLabel(new Tuple <int, int>(0, 0)); SetLabels(new Tuple <int, int>(1, 0), true); break; } } else { Element.ColumnDefinitions[0].Width = new GridLength(100, GridUnitType.Star); Element.ColumnDefinitions[1].Width = new GridLength(0, GridUnitType.Auto); Element.RowDefinitions[0].Height = new GridLength(0, GridUnitType.Auto); Element.RowDefinitions[1].Height = new GridLength(100, GridUnitType.Star); switch (Position) { case 0: SetDirections(true, false); SetLabel(new Tuple <int, int>(1, 0)); SetLabels(new Tuple <int, int>(1, 1), false); SetGradient(Gradient, new Tuple <int, int>(0, 1), true); break; case 1: SetDirections(false, false); SetLabel(new Tuple <int, int>(0, 0)); SetLabels(new Tuple <int, int>(0, 1), false); SetGradient(Gradient, new Tuple <int, int>(1, 1), true); break; case 2: SetLabel(new Tuple <int, int>(1, 0)); SetLabels(new Tuple <int, int>(1, 1), true); break; } } Labels.Insert(0, TopLabel); Element.Children.Add(canvas); Element.Children.Add(TopLabel); Element.Children.Add(AnnotationBar); }
private void DrawArc(DrawingContext context) { //arc Point startPoint = arcStartPoint; Point endPoint = arcEndPoint; double sValue1 = 0; double sValue2 = 0; Color sColor1 = Colors.White; Color sColor2 = Colors.White; double gradientAngle; switch (nodePart) { case NodePart.NorthEast: startPoint.Offset(-10, 5); endPoint.Offset(-12, 5); gradientAngle = -45; sValue1 = 0; sValue2 = 0.45; sColor1 = Colors.Transparent; sColor2 = Configurations.GradientBlue; break; case NodePart.North: case NodePart.NorthWest: startPoint.Offset(10, 5); endPoint.Offset(12, 5); gradientAngle = 45; sValue1 = 0.2; sValue2 = 0.75; sColor1 = Configurations.GradientBlue; sColor2 = Colors.Transparent; break; case NodePart.South: startPoint.Offset(0, -10); endPoint.Offset(12, 0); gradientAngle = 135; sValue1 = 0; sValue2 = 0.4; sColor2 = Configurations.GradientBlue; sColor1 = Colors.Transparent; break; default: gradientAngle = -45; break; } ArcSegment arc = new ArcSegment(startPoint, new Size(this.radius, this.radius), 45, false, SweepDirection.Counterclockwise, true); PathFigure pathFigure = new PathFigure(); pathFigure.StartPoint = endPoint; PathSegmentCollection collection = new PathSegmentCollection(); collection.Add(arc); pathFigure.Segments = collection; PathFigureCollection figureCollection = new PathFigureCollection(); figureCollection.Add(pathFigure); PathGeometry geom = new PathGeometry(); geom.Figures = figureCollection; RadialGradientBrush radialGradient = new RadialGradientBrush(Configurations.ArcColor, Colors.Transparent); radialGradient.SpreadMethod = GradientSpreadMethod.Reflect; radialGradient.RadiusX = 0.9; radialGradient.RadiusY = 0.9; Pen Curve = new Pen(radialGradient, 2); context.DrawGeometry(null, Curve, geom); //shadow of arc startPoint.Offset(0, 1); endPoint.Offset(0, 1); ArcSegment arc1 = new ArcSegment(startPoint, new Size(this.radius, this.radius), 45, false, SweepDirection.Counterclockwise, true); LineSegment p1 = new LineSegment(startPoint, true); LineSegment p2 = new LineSegment(endPoint, true); pathFigure = new PathFigure(); pathFigure.StartPoint = endPoint; collection = new PathSegmentCollection(); collection.Add(arc1); collection.Add(p1); collection.Add(p2); pathFigure.Segments = collection; figureCollection = new PathFigureCollection(); figureCollection.Add(pathFigure); geom = new PathGeometry(); geom.Figures = figureCollection; GradientStopCollection gradientStopCollection = new GradientStopCollection(); GradientStop stopValue1 = new GradientStop(sColor1, sValue1); GradientStop stopValue2 = new GradientStop(sColor2, sValue2); gradientStopCollection.Add(stopValue1); gradientStopCollection.Add(stopValue2); LinearGradientBrush gradientBrush = new LinearGradientBrush(gradientStopCollection, gradientAngle); //context.DrawRectangle(gradientBrush, null, new Rect(startPoint, endPoint)); context.DrawGeometry(gradientBrush, null, geom); }
public virtual void UpdateGradientStops( GradientStopCollection stops) { }