DataGridView重繪單元格中某些字體顏色,大小

主要通過對單元格進行重繪,改變元單元格字體大小和顏色

        protected override void OnCellPainting(DataGridViewCellPaintingEventArgs e)
        {
            base.OnCellPainting(e);
            if (e.Value != null)
            {
                string cellWord = e.Value.ToString();//單元格原本內容
                string keyWord = e.Value.ToString();//要改變的單元格關鍵字內容

                Rectangle cellRect = e.CellBounds;//默認單元格
                Rectangle keyRect = e.CellBounds;//單元格內容區域,默認定義爲單元格大小
                float fontSizeWeight = 96 / (72 / e.CellStyle.Font.Size); // 字體實際像素寬度
                float fontSizeHeight = 96 / (72 / e.CellStyle.Font.Size); // 字體實際像素高度
                //關鍵字的座標
                keyRect.X += cellWord.Substring(0, cellWord.IndexOf(keyWord)).Length * (int)(fontSizeWeight / 2);
                keyRect.Y += (e.CellBounds.Height - (int)fontSizeHeight) / 2;
                //原文本的Y座標
                cellRect.Y = keyRect.Y;

                using (Brush foreColor = new SolidBrush(e.CellStyle.ForeColor), fontColor = new SolidBrush(this.FontColor))
                {
                    //繪製背景色
                    e.PaintBackground(e.ClipBounds, false);
                    //繪製背景色(被選中狀態下)
                    if (e.State == (DataGridViewElementStates.Displayed | DataGridViewElementStates.Selected | DataGridViewElementStates.Visible))
                        e.PaintBackground(e.ClipBounds, true);
                    //分別繪製原文本和現在改變顏色的文本
                    e.Graphics.DrawString(cellWord, this.Font, foreColor, cellRect, StringFormat.GenericDefault);
                    e.Graphics.DrawString(keyWord, this.Font, fontColor, keyRect, StringFormat.GenericDefault);
                    //提交事務
                    e.Handled = true;
                }
            }
        }
定義該重繪控件的字體,前景色和背景圖片
        #region properties
        /// <summary>
        /// 獲取或設置該控件下顯示字體的大小.
        /// </summary>
        [Browsable(true)]
        [DefaultValue(typeof(Font), "宋體,9"), Description("獲取或設置該控件下顯示字體的大小.")]
        public override Font Font
        {
            get { return this._font; }
            set { this._font = value; }
        }
        /// <summary>
        /// 獲取或設置當前字體顏色.
        /// </summary>
        [Description("獲取或設置當前字體顏色.")]
        public Color FontColor
        {
            get { return this._fontColor; }
            set { this._fontColor = value; }
        }
        /// <summary>
        /// 獲取或設置當前控件的背景圖片.
        /// </summary>
        [DefaultValue(typeof(Image), ""), Description("獲取或設置當前控件的背景圖片.")]
        public Image BackImage
        {
            get { return this._backImage; }
            set { this._backImage = value; }
        }
        #endregion
以上代碼僅供參考


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章