Monday, March 7, 2011

How to draw subsection of text using .net graphics

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;
From stackoverflow
  • I don't think I quite understand the visual effect you intend to have. Is the text for the item supposed to overlap multiple cells or clipped to a single cell? If it's supposed to be clipped to the cell you can set your clipping area using Graphics.Clip to clip to a specified rectangle.

    If the problem is related to smearing due to not clearing the buffer you can use FillRectangle to clear a region cheaper than drawing text.

    dotjoe : Ahh the Clip is what I wanted...thanks.

0 comments:

Post a Comment