【WPF】绘制水平尺
储备知识
Pen、Brushes、绘图类Drawing、DrawingVisual类的使用
效果
源代码
using System; using System.Collections.Generic; using Drawing = System.Drawing; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls.Primitives; using System.Windows.Media; namespace VisualPlay { public class CustomTickBar : TickBar { ///隔N个Frequency 写上刻度文字 public int IntervalText { get { return (int)GetValue(IntervalTextProperty); } set { SetValue(IntervalTextProperty, value); } } // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... public static readonly DependencyProperty IntervalTextProperty = DependencyProperty.Register("IntervalText", typeof(int), typeof(CustomTickBar), new PropertyMetadata(5)); public int StartAxisY { get { return (int)GetValue(StartAxisYProperty); } set { SetValue(StartAxisYProperty, value); } } // Using a DependencyProperty as the backing store for StartAxisY. This enables animation, styling, binding, etc... public static readonly DependencyProperty StartAxisYProperty = DependencyProperty.Register("StartAxisY", typeof(int), typeof(CustomTickBar), new PropertyMetadata(0)); void OnRenderHorizontalRuler(DrawingContext dc) { Double tickFrequencySize; Brush foreBrush = this.Fill; Pen line_Pen = new Pen(foreBrush, 1); FormattedText font = null; Size size = new Size(base.ActualWidth, base.ActualHeight); int tickCount = (int)((this.Maximum - this.Minimum) / this.TickFrequency) + 1; if ((this.Maximum - this.Minimum) % this.TickFrequency == 0) tickCount -= 1; tickFrequencySize = (size.Width * this.TickFrequency / (this.Maximum - this.Minimum)); string text = ""; double num = this.Maximum - this.Minimum; int i = 0; for (i = 0; i <= tickCount; i++) { ///隔N个Frequency 写上刻度 if (i % IntervalText == 0) { text = Convert.ToString(Convert.ToInt32(this.Minimum + this.TickFrequency * i), 10); font = new FormattedText(text, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface("Verdana"), 14, foreBrush); dc.DrawText(font, new Point(tickFrequencySize * i, 20)); // Point startpoint = new Point(tickFrequencySize * i, StartAxisY + 4); Point endpoint = new Point(tickFrequencySize * i, StartAxisY + 24); dc.DrawLine(line_Pen, startpoint, endpoint); } else { dc.DrawLine(line_Pen, new Point(tickFrequencySize * i, StartAxisY + 14), new Point(tickFrequencySize * i, StartAxisY + 24)); } } } protected override void OnRender(DrawingContext dc) { OnRenderHorizontalRuler(dc); } } }
编程是个人爱好