Question

Is there a way to hit test the pixels of characters in wpf? I want to be able to get a hit for the dot of the character 'i' but don't get a hit when I click the space between the dot and the line of 'i'. I tried to do it using DrawingContext.DrawText method and but when I hit test against the resulting DrawingVisual, which contains the text, using VisualTreeHelper.HitTest method it doesn't differentiate the space and the black pixels of the character. It gives a hit for every point in the bounding box of a character. Is there a way to do this?

Was it helpful?

Solution

I found the solution. To do this you have to go to lower level to GlyphRunDrawing. Use the code here and substitute GeometryDrawing with GlyphRunDrawing. Then get the GeometryGroup, which contains each character as Geometry, and do the hit testing with the code:

GeometryGroup ggroup = (GeometryGroup)((GlyphRunDrawing)drawing).GlyphRun.BuildGeometry();
if(ggroup.FillContains(pt))
{
    Debug.WriteLine("Contains point " + pt.ToString());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top