In my previous blog post we reviewed a custom adorner which allowed us to place a TextBlock into the adorner layer of a Viewbox. Putting the TextBlock in the Viewbox’s adorner layer prevented the text from being scaled by the Viewbox, so the TextBlock’s text size remained constant. In this blog post we will take the next step forward toward providing textual annotations of an Image contained in a Viewbox.
Suppose that we need to build an application which allows the user to add short “tags,” also known as annotations, to an image. The location of an annotation is just as important as the text it contains. Thus our annotations must always be “anchored” above the same meaningful part of the picture, but not necessarily the same coordinate (x,y) of the Image element. For example, consider the following three annotations and take note of how their locations help convey meaning:
Now suppose that the Image element and the two big blocks of text surrounding it are in a Viewbox. If we resize the Window all of those elements will be scaled by the Viewbox. It is important that our annotations continue to hover above the same parts of the picture and their text remains the same size, as seen below:
If we shrink the Window even more, notice that the annotations are still at the correct meaningful locations, but certainly not at the same coordinates as before:
In order to accomplish this I introduced a new class, called ViewboxAnnotation. An instance of that class is created by the Window whenever the user clicks on the Image element, as seen below:
ViewboxAnnotation has a private constructor, which does most of that class’s heavy lifting. That constructor is seen below:
Halfway into that method the two private fields ‘_horizPercent’ and ‘_vertPercent’ are set. Those fields store the percentages of the Viewbox’s width and height, respectively, by which the TextBlock in the adorner should be offset. When the Viewbox is resized those values are used to determine the new location of the annotation text. That logic is seen below:
Download the demo project here: Annotating an Image in a Viewbox (demo project) Be sure to change the file extension from .DOC to .ZIP and then decompress it.