1,效果。
2,绘制技巧。
1,流动块的实质是使用Pen的自定义DashStyle绘制的线,并使用线的偏移值呈现出流动的效果。
Pen barPen = new Pen(BarColor, BarHeight);
barPen.DashStyle = DashStyle.Custom;
barPen.DashOffset = startOffset;
barPen.DashPattern = new float[] { BarLength, GapLength };
graphicsPath.StartFigure();
g.DrawPath(barPen, graphicsPath);
2,使用GraphicsPath,绘制包含弧的多段线。
GraphicsPath graphicsPath = new GraphicsPath();
//特别需要注意角度旋转方向,如果角度旋转方向选错就形成闭环
graphicsPath.AddArc(new Rectangle(this.Height / 2, this.Height / 2 * (-1) - 1, this.Height, this.Height), 180.0f, -90.0f);
3,对于扇形区域使用渐变色时需要使用PathGradientBrush画刷而不是 LinearGradientBrush, LinearGradientBrush画刷无法实现从圆心到边缘的颜色渐变。
void PaintRectangle(Graphics g, Rectangle rec, PointF[] points, LinearGradientMode linearGradientMode = LinearGradientMode.Vertical)
{
//画刷效果呈现线型分布,注意与PathGradientBrush的区别
LinearGradientBrush brush = new LinearGradientBrush(rec, PipeEdgeColor, PipeCenterColor, linearGradientMode);
brush.InterpolationColors = new ColorBlend() { Colors = new Color[] { PipeEdgeColor, PipeCenterColor, PipeEdgeColor }, Positions = new float[] { 0, 0.5f, 1 } };
brush.InterpolationColors = new ColorBlend() { Colors = new Color[] { PipeEdgeColor, PipeCenterColor, PipeEdgeColor }, Positions = new float[] { 0, 0.5f, 1 } };
g.FillRectangle(brush, rec);
g.DrawLine(new Pen(BorderColor, BorderWidth), points[0], points[1]);
g.DrawLine(new Pen(BorderColor, BorderWidth), points[2], points[3]);
}
3,使用自定义的流动管道控件(FlowControl)
引用控件
属性窗口设置自定义的相关属性
设置后效果
4,代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace CustomControl
{
public partial class FlowControl : UserControl
{
private float startOffset = 0.0f;
private Timer mytimer = new Timer();
Graphics g;
public FlowControl()
{
InitializeComponent();
设置控件样式
this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
this.SetStyle(ControlStyles.DoubleBuffer, true);
this.SetStyle(ControlStyles.ResizeRedraw, true);
this.SetStyle(ControlStyles.Selectable, true);
this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);
this.SetStyle(ControlStyles.UserPaint, true);
mytimer.Interval = 50;
mytimer.Tick += Mytimer_Tick;
mytimer.Start();
}
private void Mytimer_Tick(object sender, EventArgs e)
{
startOffset += moveSpeed;
if (Math.Abs(startOffset) > BarLength + GapLength)
{
startOffset = 0;
}
this.Invalidate();
}
#region Fileds
private int barHeight = 5;
[Browsable(true), Category("自定义属性"), Description("流动条宽度")]
public int BarHeight
{
get { ret