I'm doing custom drawing in datagridview cells and I have items that can vertically span across multiple cells. An item displays text and the issue at hand is how can I draw just the cell's part of the text? I have the item's rectangle and the cellBounds.
Currently, I am drawing all the text on each cell paint i.e. I'm drawing over cells other than the one I'm currently painting from. This requires me to clear out the previous text (so it doesn't get blurry and bolded)...so I'm actually drawing the string twice per cell paint. Not very efficient.
//get the actual bounds of this entire item spanning across multiple cells
RectangleF sRectF = GetItemRectF(startX + leftMargin + 2, widthForItem, cellBounds, calItem);
//we clear it out first, otherwise the text looks bolded if we keep drawing a black string over and over
//todo should figure out how to only draw this cells section? cellBounds subsection of sRectF somehow
graphics.DrawString(calItem.Description, new Font("Tahoma", 8), new SolidBrush(itemBackColor), sRectf);
graphics.DrawString(calItem.Description, new Font("Tahoma", 8), new SolidBrush(Color.Black), sRectF);
Could I draw the string on some temp graphics and then snatch out the cell bounds part and draw that on the actual graphics? Is there a better way?
Thanks
Answer
Region tempRegion = graphics.Clip;
graphics.Clip = new Region(cellBounds);
graphics.DrawString(calItem.Description, new Font("Tahoma", 8), new SolidBrush(Color.Black), sRectF);
graphics.Clip = tempRegion;