c#画一条横线

VS中没有VB的横线控件,没关系,动手做一个丰衣足食,顺便还实现了竖线,斜线的功能

image

代码比较简单,创建一个继承Control的控件,编写代码如下:

    public partial class Line : Control
    {
        public Line()
        {
            InitializeComponent();
        }

        private LineTypeEnum lineType = LineTypeEnum.Horizontal;
        [Category("自定义"), Description("线型")]
        public LineTypeEnum LineType
        {
            set
            {
                lineType = value;
                this.Refresh();
            }
            get
            {
                return lineType;
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
            e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            e.Graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

            if (lineType == LineTypeEnum.Horizontal)
            {
                e.Graphics.DrawLine(Pens.Gray, 0, 0, this.Width, 0);
                e.Graphics.DrawLine(Pens.White, 0, 1, this.Width, 1);
            }
            else if (lineType == LineTypeEnum.Vertical)
            {
                e.Graphics.DrawLine(Pens.Gray, 0, 0, 0, this.Height);
                e.Graphics.DrawLine(Pens.White, 1, 0, 1, this.Height);
            }
            else if (lineType == LineTypeEnum.LeftTopToRightBottom)
            {
                e.Graphics.DrawLine(Pens.Gray, 0, 0, this.Width, this.Height);
                e.Graphics.DrawLine(Pens.White, 0, 1, this.Width, this.Height + 1);
            }
            else
            {
                e.Graphics.DrawLine(Pens.Gray, 0,this.Height, this.Width, 0);
                e.Graphics.DrawLine(Pens.White,0, this.Height+1, this.Width, 1 );

            }
        }
        /// <summary>
        /// 线型
        /// </summary>
        public enum LineTypeEnum
        {
            Horizontal,
            Vertical,
            LeftTopToRightBottom,
            LeftBottomToRightTop
        }
    }

 

使用时,将控件拖到窗体上,设置控件Width,Height,设置属性线性LineType即可

posted on 2017-07-26 13:53  yepoint  阅读(10251)  评论(0编辑  收藏  举报

导航