首页 新闻 赞助 找找看

winform中重绘字符宽度有偏差?

0
悬赏园豆:20 [已解决问题] 解决于 2014-06-21 17:04

希望在dataGridView的单元格内对我要查找的关键字及其单元格背景进行重绘,以便查看时可以快速定位,现在背景和文字重绘已经做到了,但关键字高亮显示有问题,横向定位不准,请求支援?

关键代码如下:

private void dgvListItems_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.Value != null
                && !string.IsNullOrEmpty(txtSearchKey.Text)
                && e.Value.ToString().ToUpper().Contains(txtSearchKey.Text.ToUpper()))
            {
                using (Brush foreColorBrush = new SolidBrush(e.CellStyle.ForeColor), keywordColorBrush = new SolidBrush(Color.DodgerBlue))
                {
                    var cellText = e.Value.ToString();
                    var searchKey = txtSearchKey.Text;

                    // 绘制背景 
                    e.PaintBackground(e.ClipBounds, false);

                    //绘制自定义背景
                    var bounds = e.CellBounds;
                    bounds.Inflate(new Size(-1, -1));
                    e.Graphics.FillRectangle(new SolidBrush(Color.Yellow), bounds);

                    // 绘制背景(被选中时) 
                    if (e.State == (DataGridViewElementStates.Selected | DataGridViewElementStates.Displayed | DataGridViewElementStates.Visible))
                        e.PaintBackground(e.ClipBounds, true);

                    // 绘制原文本 
                    e.Graphics.DrawString(cellText, e.CellStyle.Font, foreColorBrush, e.CellBounds, StringFormat.GenericDefault);

                    //获取关键字之前的文字
                    var searchKeyIndex = cellText.ToUpper().IndexOf(searchKey.ToUpper());
                    var textBeforeSearchKey = cellText.Substring(0,searchKeyIndex);
                    
                    //获取高亮关键字之前的文字的长度
                    var searchKeyIndentSize = e.Graphics.MeasureString(textBeforeSearchKey, e.CellStyle.Font);
                    var searchKeyCellBounds = new RectangleF(e.CellBounds.Location, e.CellBounds.Size);
                    searchKeyCellBounds.X += searchKeyIndentSize.Width;

                    // 在原文本上绘制红色关键字 
                    e.Graphics.DrawString(searchKey, e.CellStyle.Font, keywordColorBrush, searchKeyCellBounds, StringFormat.GenericDefault);

                    // 已完成事件处理,继续本身处理 
                    e.Handled = true;
                }

            }
        }
空明流光的主页 空明流光 | 初学一级 | 园豆:106
提问于:2014-06-21 13:43
< >
分享
最佳答案
0

已经解决了!

空明流光 | 初学一级 |园豆:106 | 2014-06-21 17:03
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册