Precise OpacityMask - wpf

Suppose I need to set an opacity mask on a WPF control that highlights a portion of it in precise position (suppose a 50x50 square at (50;50) position). To do that I create a DrawingGroup containing 2 GeometryDrawing objects: 1 semi-transparent rectangle for the whole actual size of the control and 1 opaque rectangle for highlighted area. Then I create a DrawingBrush from this DrawingGroup, set it's Stretch property to None and set this brush as OpacityMask of the control that needs to be masked.
All this works fine while nothing is "sticking" out of bounds of said control. But if control draws something outside of it's bounds the outer point becomes a starting point from where opacity mask is applied (if the brush is aligned to that side) and the whole mask shifts by that distance resulting in unexpected behavior.
I can't seem to find a way to force mask to be applied from control's bounds or at least get the actual bounds of the control (including sticking parts) so I can adjust my mask accordingly.
Any ideas highly appreciated!
Update: Here's a simple test-case XAML and screenshots demonstrating the issue:
We have 2 nested Borders and Canvas in the last one with the above mentioned square:
<Border Padding="20" Background="DarkGray" Width="240" Height="240">
<Border Background="LightBlue">
<Canvas>
<Rectangle Canvas.Left="50" Canvas.Top="50" Width="50" Height="50"
Stroke="Red" StrokeThickness="2"
Fill="White"
/>
</Canvas>
</Border>
</Border>
Here's how it looks:
(source: ailon.org)
Now we add an OpacityMask to the second border so that every part of it except our square is semi-transparent:
<Border.OpacityMask>
<DrawingBrush Stretch="None" AlignmentX="Left" AlignmentY="Top">
<DrawingBrush.Drawing>
<DrawingGroup>
<GeometryDrawing Brush="#30000000">
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="0,0,200,200" />
</GeometryDrawing.Geometry>
</GeometryDrawing>
<GeometryDrawing Brush="Black">
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="50,50,50,50" />
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
</Border.OpacityMask>
Everything looks as expected:
(source: ailon.org)
And now we add a line to the canvas that sticks 10 pixels out on the left of our border:
<Line X1="-10" Y1="150" X2="120" Y2="150"
Stroke="Red" StrokeThickness="2"
/>
And the mask shifts 10 pixels to the left:
(source: ailon.org)
Update2: As a workaround I add a ridiculously large transparent rectangle outside of bounds and adjust my mask accordingly but that is a really nasty workaround.
Update3: Note: The canvas with rectangle and line is there just as an example of some object that has something outside of it bounds. In context of this sample it should be treated as some sort of a black box. You can't change it's properties to solve the general issue. This would be the same as just moving the line so it doesn't stick out.

Interesting issue indeed - here's what I've figured: The effect you are experiencing seems to be determined by the Viewport concept/behavior of TileBrush (see Viewbox too for the complete picture). Apparently the implicit bounding box of a FrameworkElement (i.e. the Canvas in your case) is affected/expanded by elements sticking out of bounds in a subtle way, that is, the dimensions of the box expand but the coordinate system of the box does not scale, rather expands too into the out of bounds direction.
It might be easier to illustrate that graphically, but due to time constraints I'll just offer a solution first and will explain the steps I've taken for the moment in order to get you started:
Solution:
<Border Background="LightBlue" Width="198" Height="198">
<Border.OpacityMask>
<DrawingBrush Stretch="None" AlignmentX="Center" AlignmentY="Center"
Viewport="-10,0,222,202" ViewportUnits="Absolute">
<DrawingBrush.Drawing>
<DrawingGroup>
<GeometryDrawing Brush="#30000000">
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="-10,0,220,200" />
</GeometryDrawing.Geometry>
</GeometryDrawing>
<GeometryDrawing Brush="Black">...</GeometryDrawing>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
</Border.OpacityMask>
<Canvas x:Name="myGrid">...</Canvas>
</Border>
Please note that I've adjusted units by +/- 2 pixels here and there for pixel precision without knowing where the offset originates, but I think this can be ignored for the purpose of the example and resolved later if need be.
Explanation:
To simplify the illustration one should usually make all related implied/auto properties explicit first.
The inner border receives auto dimensions of 198 from the outer border (240 - 20 padding - 2 pixels deduced by experiment; don't know their origin, but ignorable right now), that is if you specify this as follows nothing should change, while using other values yields graphical changes:
<Border Background="LightBlue" Width="198" Height="198">...</Border>
Further the default implied Viewport and ViewportUnits like so:
<DrawingBrush Stretch="None" AlignmentX="Left" AlignmentY="Top"
Viewport="0,0,1,1" ViewportUnits="RelativeToBoundingBox">...</DrawingBrush>
You are enforcing the DrawingBrush size by overriding Stretch with None, while keeping the position and dimension of the base tile at default and relative to its bounding box. In addition you (understandably) are overriding AlignmentX/AlignmentY, which determine the placement within the base tile, that is within its bounding box. Resetting those to their defaults of Center is already telling: The mask shifts accordingly, meaning it has to be smaller than the bounding box, else their would be nothing to center within.
This can be taken further by changing ViewportUnits to Absolute, which will yield no graphics at all until the units are properly adjusted of course; again, by experiment the following explicit values are matching the auto ones, while using other values yields graphical changes:
<DrawingBrush Stretch="None" AlignmentX="Center" AlignmentY="Center"
Viewport="0,0,202,202" ViewportUnits="Absolute">...</DrawingBrush>
Now the opacity mask already aligns properly with the control. Obviously there is one problem left though, as the mask is clipping the line now, which is no surprise given its size and the absence of any Stretch effect. Adjusting its size and position accordingly resolves this:
<RectangleGeometry Rect="-10,0,220,200" />
and
<DrawingBrush Stretch="None" AlignmentX="Center" AlignmentY="Center"
Viewport="-10,0,222,202" ViewportUnits="Absolute">...</DrawingBrush>
Finally the opacity mask matches the control bounds as desired!
Supplement:
The required offsets determined by deduction and experiment in the explanation above can be retrieved at runtime by means of the VisualTreeHelper Class:
Rect descendantBounds = VisualTreeHelper.GetDescendantBounds(myGrid);
Depending on your visual element composition and needs you may need to factor in the LayoutInformation Class and build the union of both to get the all-encompassing bounding box:
Rect descendantBounds = VisualTreeHelper.GetDescendantBounds(myGrid);
Rect layoutSlot = LayoutInformation.GetLayoutSlot(myGrid);
Rect boundingBox = descendantBounds;
boundingBox.Union(layoutSlot);
See the following links for more details on both topics:
Windows Presentation Foundation
Graphics Rendering Overview,
especially VisualTreeHelper
Class
The Layout System, especially
Element Bounding Boxes

On your Canvas object add ClipToBounds="True".
<Canvas ClipToBounds="True">
<Rectangle Canvas.Left="50" Canvas.Top="50" Width="50" Height="50"
Stroke="Red" StrokeThickness="2"
Fill="White" />
<Line X1="-10" Y1="150" X2="120" Y2="150"
Stroke="Red" StrokeThickness="2"/>
</Canvas>

One workaround that may be more ideal than your current one would be to simply apply the OpacityMask at a higher level. Using this demo code for example, you could remove the mask from the Border and apply it to the Window instead. With a bit of tweaking it fits properly:
<Window.OpacityMask>
<DrawingBrush AlignmentX="Left" AlignmentY="Top" Stretch="None">
<DrawingBrush.Drawing>
<DrawingGroup>
<GeometryDrawing Brush="#30000000">
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="0,0,300,300"/>
</GeometryDrawing.Geometry>
</GeometryDrawing>
<GeometryDrawing Brush="Black">
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="92,82,50,50"/>
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
</Window.OpacityMask>
You would have to write some code to move the mask when the Window is resized, and for that reason you may be better off generating the mask dynamically in the code-behind.
My question for you is, why do you need to handle geometries that go outside the bounds of your Canvas?

Since you have parts that stick out from the control, one idea is to separate control image from the control mask.
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Border Padding="20" Background="DarkGray" Width="240" Height="240"> <!-- user container -->
<Grid> <!-- the control -->
<Border Background="LightBlue" HorizontalAlignment="Stretch"> <!-- control mask-->
<Canvas>
<Rectangle Canvas.Left="50" Canvas.Top="50" Width="50" Height="50"
Stroke="Red" StrokeThickness="2"
Fill="White"
/>
<Canvas.OpacityMask>
<DrawingBrush Stretch="None" AlignmentX="Left" AlignmentY="Top" TileMode="None">
<DrawingBrush.Drawing>
<DrawingGroup>
<GeometryDrawing Brush="#30000000">
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="0,0,200,200" />
</GeometryDrawing.Geometry>
</GeometryDrawing>
<GeometryDrawing Brush="Black">
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="50,50,50,50" />
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
</Canvas.OpacityMask>
</Canvas>
</Border>
<Canvas> <!-- control image-->
<Line X1="-10" Y1="150" X2="120" Y2="150" Stroke="Red" StrokeThickness="2"/>
</Canvas>
</Grid>
</Border>
</Window>

Related

XAML icons in menu items look shifted

I would like to use Visual Studio 2022 Image Library in my project. The one that the VS2022 IDE uses (surprise!). But when I add an icon to a menu item, it doesn't look as pretty as it does in a VS menu:
<MenuItem.Icon>
<Rectangle Width="16" Height="16">
<Rectangle.Fill>
<DrawingBrush>
<DrawingBrush.Drawing>
<DrawingGroup>
<GeometryDrawing Brush="{DynamicResource canvas}" Geometry="F1M16,16H0V0H16Z" />
<DrawingGroup Opacity="{DynamicResource cls-1}">
<GeometryDrawing Brush="{DynamicResource light-defaultgrey-10}" Geometry="F1M14.5,4.5v10H3.5V7.95A4.984,4.984,0,0,0,8,3a4.966,4.966,0,0,0-.254-1.5H11.5Z" />
<GeometryDrawing Brush="{DynamicResource light-defaultgrey}" Geometry="F1M15,4.5v10l-.5.5H3.5L3,14.5V8a4.988,4.988,0,0,0,1-.1V14H14V5H11V2H7.9a4.968,4.968,0,0,0-.321-1H11.5l.354.146,3,3Z" />
</DrawingGroup>
<GeometryDrawing Brush="{DynamicResource light-yellow}" Geometry="F1M3,2,3,0H4L4,2l-.5.5Zm.5,2.5L3,5V7H4V5Zm1-1L5,4,7,4V3L5,3Zm-2,0L2,3,0,3V4L2,4Zm1.708-.7h.708L6.328,1.378,5.62.671,4.208,2.088ZM2.792,4.206H2.085L.673,5.623l.707.706L2.793,4.913Zm1.414,0v.708L5.623,6.328l.706-.708L4.913,4.208ZM2.794,2.792V2.085L1.378.673.671,1.38,2.088,2.793Z" />
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
</Rectangle.Fill>
</Rectangle>
</MenuItem.Icon>
Compare the IDE's and my renders (scaled):
As you can see, my icons seem to be shifted horizontally by a fraction of a pixel. Perhaps it's just because Microsoft guys used PNG instead of XAML.
I've tried adding SnapsToDevicePixels wherever possible, but it doesn't change anything. Obviously, specifying a correct offset will be enough for the solution, but I don't know that offset. And I don't want to look through the Magnifier every time I add a new icon to make sure I need to subtract a hundredth of a pixel from the offset I guessed.
Could you suggest an elegant solution to removing the subpixel effect when rendering these XAML icons?

How to create and use ResourceDictionary of external XAML images

I would like to use icons from Visual Studio icon set for a WPF app and I would like to do it properly using ResourceDictionaries, but it seems more challenging than I thought.
The example icon is a ViewBox provided in a separate XAML file, it's named home_16x.xaml and the XAML content looks like this:
<Viewbox Width="16" Height="16" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<Rectangle Width="16" Height="16">
<Rectangle.Fill>
<DrawingBrush>
<DrawingBrush.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Brush="#00FFFFFF" Geometry="F1M16,16L0,16 0,0 16,0z" />
<GeometryDrawing Brush="#FFF6F6F6" Geometry="F1M7.8786,-0.000199999999999534L-0.000399999999999956,7.8798 -0.000399999999999956,9.4138 0.9996,10.4138 0.9996,15.9998 15.0006,15.9998 15.0006,10.4138 16.0006,9.4138 16.0006,7.8798 8.1206,-0.000199999999999534z" />
<GeometryDrawing Brush="#FFF0EFF1" Geometry="F1M13,14L10,14 10,9 6,9 6,14 3,14 3,7.707 8,2.707 13,7.707z" />
<GeometryDrawing Brush="#FF424242" Geometry="F1M0.6462,8.6461L1.3532,9.3531 2.0002,8.7071 2.0002,15.0001 7.0002,15.0001 7.0002,10.0001 9.0002,10.0001 9.0002,15.0001 14.0002,15.0001 14.0002,8.7071 14.6462,9.3531 15.3532,8.6461 8.0002,1.2931z M3.0002,7.7071L8.0002,2.7071 12.9992,7.7071 12.9992,14.0001 10.0002,14.0001 10.0002,9.0001 6.0002,9.0001 6.0002,14.0001 3.0002,14.0001z" />
</DrawingGroup.Children>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
</Rectangle.Fill>
</Rectangle>
</Viewbox>
If I use the following on my page then it works, but that's not what I am after. It doesn't seem elegant and I would like to keep the option open for switching ResourceDictionaries (for themes).
<Viewbox Width="400" Height="400">
<Frame Source="\Media\Icons\Home_16x.xaml"/>
</Viewbox>
It also shows the following in design view, which is quite confusing:
I would really like to be able to build a dictionary of the icons, that I could call with something like (or cleaner, if possible):
<Viewbox Width="400" Height="400">
<Frame Content="{StaticResource ResourceKey=Icons.Home}"/>
</Viewbox>
My current Icons ResourceDictionary looks like this:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Viewbox x:Key="Home">
<Viewbox.Resources>
<ResourceDictionary>
<Frame x:Key="Home" Source="\Media\Icons\Home_16x.xaml"/>
</ResourceDictionary>
</Viewbox.Resources>
</Viewbox>
</ResourceDictionary>
I admit I am quite lost. Any help would be much appreciated.
If you use a visualbrush on say a rectangle as fill, that will stretch to whatever size the rectangle is.
Hence you could have a visualbrush in a resource dictionary:
<DrawingBrush x:Key="HomeBrush">
<DrawingBrush.Drawing>
<DrawingGroup>
<DrawingGroup.Children>
<GeometryDrawing Brush="#00FFFFFF" Geometry="F1M16,16L0,16 0,0 16,0z" />
<GeometryDrawing Brush="#FFF6F6F6" Geometry="F1M7.8786,-0.000199999999999534L-0.000399999999999956,7.8798 -0.000399999999999956,9.4138 0.9996,10.4138 0.9996,15.9998 15.0006,15.9998 15.0006,10.4138 16.0006,9.4138 16.0006,7.8798 8.1206,-0.000199999999999534z" />
<GeometryDrawing Brush="#FFF0EFF1" Geometry="F1M13,14L10,14 10,9 6,9 6,14 3,14 3,7.707 8,2.707 13,7.707z" />
<GeometryDrawing Brush="#FF424242" Geometry="F1M0.6462,8.6461L1.3532,9.3531 2.0002,8.7071 2.0002,15.0001 7.0002,15.0001 7.0002,10.0001 9.0002,10.0001 9.0002,15.0001 14.0002,15.0001 14.0002,8.7071 14.6462,9.3531 15.3532,8.6461 8.0002,1.2931z M3.0002,7.7071L8.0002,2.7071 12.9992,7.7071 12.9992,14.0001 10.0002,14.0001 10.0002,9.0001 6.0002,9.0001 6.0002,14.0001 3.0002,14.0001z" />
</DrawingGroup.Children>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
And use that:
<Rectangle Fill="{StaticResource HomeBrush}" Width="16" Height="16"/>
Or you could let your rectangle fill whatever cell of a grid it's in and omit width and height.
You don't need a viewbox to scale vectors, they can stretch.
You can also use a visualbrush within a path. The path can define one shape with a geometry ( which could be from a resource ) and within that your drawingbrush could put another geometry drawing with a different colour.
An example geometry out a resource file I have:
<Geometry x:Key="BeeIcon">
M15.551045,25.144995L16.748029,25.144995 ....
</Geometry>
I removed a big chunk of the geometry there.
That BeeIcon can then be re-used in different drawinggroups which is useful if you want to construct icons with several parts.
Brushes and colours for them can also be from a resource dictionary so you can switch them out for different themes or branding.

Relative coordinates in DrawingBrush

I am somewhat confused about how relative coordinates work in WPF, especially in scenarios with DrawingBrushes.
Let's say I want to paint the background of a square area, which is flexible in it's size. I want to paint the background with a special "shape", let's say a kind of "T" laying on the side, with the vertical stroke going through the middle of the area.
Using relative coordinates (the size of the area is flexible), I came up with the following XAML:
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="722" Width="722" UseLayoutRounding="True">
<Window.Resources>
<DrawingBrush x:Key="EdgeGrid">
<DrawingBrush.Drawing>
<GeometryDrawing>
<GeometryDrawing.Geometry>
<!-- draw a single T laying on the side -->
<GeometryGroup>
<!-- top to bottom -->
<LineGeometry StartPoint="0.5,0.0" EndPoint="0.5,1"/>
<!-- left to right -->
<LineGeometry StartPoint="0.5,0.5" EndPoint="1,0.5"/>
</GeometryGroup>
</GeometryDrawing.Geometry>
<GeometryDrawing.Pen>
<Pen Thickness="0.01" Brush="Black" />
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingBrush.Drawing>
</DrawingBrush>
</Window.Resources>
<Grid Name="LayoutRoot">
<Rectangle Width="400" Height="400" Stroke="Black" StrokeThickness="1" Fill="{StaticResource EdgeGrid}">
</Rectangle>
</Grid>
But the result I get looks like this:
(source: bilder-hochladen.net)
Shouldn't the vertical stroke go right through the middle (X coordinate is 0.5)?
And also how can I set the pen thickness to be 1 or 2 pixels in relative mode?
Any ideas?
You'll have to set the ViewboxUnits property of the DrawingBrush to Absolute (instead of the default RelativeToBoundingBox). The Viewbox would still be (0,0,1,1).
See the TileBrush Overview article on MSDN for details about a brush's viewbox and viewport.
<DrawingBrush x:Key="EdgeGrid" ViewboxUnits="Absolute">
<DrawingBrush.Drawing>
<GeometryDrawing>
<GeometryDrawing.Geometry>
<GeometryGroup>
<LineGeometry StartPoint="0.5,0.0" EndPoint="0.5,1"/>
<LineGeometry StartPoint="0.5,0.5" EndPoint="1,0.5"/>
</GeometryGroup>
</GeometryDrawing.Geometry>
<GeometryDrawing.Pen>
<Pen Thickness="0.01" Brush="Black" />
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingBrush.Drawing>
</DrawingBrush>
Of course this won't let you define stroke widths in pixels. Making the drawing in absolute coordinates and then putting the whole thing in a Viewbox won't also help much, because strokes would still be scaled.
In order to get a scalable drawing with fixed stroke width, you would have to use a Path element, where you set the StrokeThickness and Data properties and assign a ScaleTransform to the Transform property of the Geometry used as Data.
In your special case of drawing a centered, T-shaped figure with fixed stroke width, you may simply draw two (very long) Lines in a Canvas, where the coordinate origin is centered by putting the Canvas in a 2x2 Grid. You may even choose to have different strokes and stroke widths for the two Lines.
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Canvas Grid.Column="1" Grid.Row="1">
<Line Y1="-10000" Y2="10000" Stroke="Black" StrokeThickness="1"/>
<Line X2="10000" Stroke="Black" StrokeThickness="1"/>
</Canvas>
</Grid>
To get vertical stroke right you need to do it like this:
<GeometryGroup>
<!-- top to bottom -->
<LineGeometry StartPoint="0.75,0.0"
EndPoint="0.75,1" />
<!-- left to right -->
<LineGeometry StartPoint="0.5,0.5"
EndPoint="1,0.5" />
</GeometryGroup>
But that won't help you with pen thickness. In general, if you want to scale a geometry - first create it using absolute coordinates you like (say in 0-100 range), then put that into ViewBox or use ScaleTransform, like this:
<Viewbox Width="400"
Height="400">
<Path Stroke="Black"
StrokeThickness="1">
<Path.Data>
<GeometryGroup>
<!-- top to bottom -->
<LineGeometry StartPoint="75,0"
EndPoint="75, 100" />
<!-- left to right -->
<LineGeometry StartPoint="50,50"
EndPoint="100, 50" />
</GeometryGroup>
</Path.Data>
</Path>
</Viewbox>
Let's see how the proposed solution would look like.
Let's assume we want to show the shapes in a kind of grid and draw various shapes depending on the data (by selecting an appropriate DateTemplate). For simplicity, in this example, let's draw only one kind of shape (a cross, as in my initial question):
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="722" Width="722" UseLayoutRounding="True">
<ItemsControl ItemsSource="{Binding data}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="10" Rows="10">
</UniformGrid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid x:Name="Cell">
<Path StrokeThickness="2" Stroke="Blue" SnapsToDevicePixels="True">
<Path.Data>
<GeometryGroup>
<GeometryGroup.Transform>
<ScaleTransform ScaleX="{Binding ElementName=Cell, Path=ActualWidth}" ScaleY="{Binding ElementName=Cell, Path=ActualHeight}"/>
</GeometryGroup.Transform>
<!-- top to bottom -->
<LineGeometry StartPoint="0.5,0.0" EndPoint="0.5,1"/>
</GeometryGroup>
</Path.Data>
</Path>
<Path StrokeThickness="1" Stroke="Black" SnapsToDevicePixels="True">
<Path.Data>
<GeometryGroup>
<GeometryGroup.Transform>
<ScaleTransform ScaleX="{Binding ElementName=Cell, Path=ActualWidth}" ScaleY="{Binding ElementName=Cell, Path=ActualHeight}"/>
</GeometryGroup.Transform>
<!-- left to right -->
<LineGeometry StartPoint="0,0.5" EndPoint="1,0.5"/>
</GeometryGroup>
</Path.Data>
</Path>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Window>
#Clemens Is this the solution you had in mind? Is this the correct way of doing it?
The only problem I have with the result is that the lines are blurry and there is even a break to be seen in the horizontal line. Is there any solution for this?

Problems drawing an "x" in the center of a circle using XAML

I am trying to create a red circle with a black x through it using XAML.
My problem is that they aren't aligned correctly.
What is the right way to do this?
This is what I've got so far:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Image>
<Image.Source>
<DrawingImage>
<DrawingImage.Drawing>
<DrawingGroup>
<GeometryDrawing Brush="Red">
<GeometryDrawing.Pen>
<Pen Brush="Transparent" Thickness="0"/>
</GeometryDrawing.Pen>
<GeometryDrawing.Geometry>
<EllipseGeometry Center="8,8" RadiusX="8" RadiusY="8"/>
</GeometryDrawing.Geometry>
</GeometryDrawing>
<GeometryDrawing>
<GeometryDrawing.Pen>
<Pen Brush="Black" Thickness="2.5"/>
</GeometryDrawing.Pen>
<GeometryDrawing.Geometry>
<PathGeometry>
<PathFigure StartPoint="4,4">
<LineSegment Point="12,12"/>
</PathFigure>
<PathFigure StartPoint="4,12">
<LineSegment Point="12,4"/>
</PathFigure>
</PathGeometry>
</GeometryDrawing.Geometry>
</GeometryDrawing>
</DrawingGroup>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
</Grid>
Simply putting an ellipse in the same grid with a black X the X isn't quite centered on the ellipse because the coordinates of each line you draw are really coordinates within the space allotted for it.
I think they needed to be in some sort of geometry or drawing aggregate to give them the same coordinate system. The geometry group and path are aggregators but both require their contents to have the same fill and stroke and the stroke and fill is different for the red circle (no stroke) and the black X (no fill).
The only aggregator that gives common coordinate systems and allows different fills & strokes for its members that I could find was the DrawingGroup.
The string shortcuts that work for creating a Path via its Data property don't appear to work for creating a PathGeometry so all had to be filled in by hand.
OK, so three hundred ways to skin a cat. Without fully understanding your use case I just came up with the fastest way to draw what you requested.
<Grid HorizontalAlignment="Left"
Height="80"
Margin="80,80,0,0"
VerticalAlignment="Top"
Width="80">
<Ellipse Fill="Red"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" />
<Path Data="M40,53 L48,69 62,69 49,46 61,24 48,24 C48,24 40,39 40,39 40,39 32,24 32,24 L18,24 30,46 17,69 31,69 z"
Fill="Black"
Margin="15"
Stretch="Fill"
HorizontalAlignment="Center"
VerticalAlignment="Center"
/>
</Grid>
This is probably outside what exactly you're looking for, but hopefully it at least gives you another way to think about it.
I had the same issue when trying to center text within an ellipse. The problem with using something like a TextBlock is that the kerning and escapement of each character is slightly different and so while the TextBlock element itself might be technically centered within the ellipse, this does not mean that the character will be centered in the ellipse. The character always appears to be too low and to the right of center in most situations.
I have had some success by wrapping the TextBlock in a ViewBox. While I am not fully versed in the technical implementation of the ViewBox, the ViewBox appears to wrap the visual rendering of the content which allows me to center that rendering more easily than trying to center to layout elements together.
I also seem to have better luck using an outer element that is of odd width/height rather than even width and height.
<Grid Width="19"
Height="19">
<Ellipse Fill="#FFB1413F"
StrokeThickness="0"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" />
<Viewbox HorizontalAlignment="Center"
VerticalAlignment="Stretch">
<TextBlock Text="X"
Margin="1"
FontWeight="Bold"
Foreground="White"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Viewbox>
</Grid>

How do I set the absolute position of a WPF GeometryDrawing?

How do I set the absolute position of a GeometryDrawing?
Currently the line is always drawn in the center.
I guess the LineGeometery is always following the Alignments on Image control.
Here is some (now edited) code I am working with:
<Window x:Class="WpfProblem.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" >
<Grid Width="450" Height="160" Background="Beige" VerticalAlignment="Stretch">
<Border BorderBrush="Lime" BorderThickness="1" CornerRadius="80" Background="#1AFF0000" Margin="0">
<Image Width="420" Height="120" Stretch="None" >
<Image.Source>
<DrawingImage>
<DrawingImage.Drawing>
<GeometryDrawing>
<GeometryDrawing.Geometry>
<LineGeometry StartPoint="0,30" EndPoint="299,30"/>
</GeometryDrawing.Geometry>
<GeometryDrawing.Pen>
<Pen Thickness="5" Brush="Black"/>
</GeometryDrawing.Pen>
</GeometryDrawing>
</DrawingImage.Drawing>
</DrawingImage>
</Image.Source>
</Image>
</Border>
</Grid>
</Window>
I believe that your problem (aside from the code above that does not compile, since Image.Source does not have Width and Height attributes) isn't that your GeometryDrawing is centered, it's that your Canvas is centered.
To prove it, just make the Background of your Canvas Red:
<Canvas Width="350" Height="180" Background="Red">
Your GeometryDrawing is at the appropriate position within this centered Canvas.
If you want the Canvas to fit the entire window, don't set explicit width and height, set HorizontalAlignment and VerticalAlignment to Stretch:
<Canvas HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Background="Blue">
to get:
It looks like Vertical & HorizontalAlignment affects the internal drawing of a DrawImage. So depending on VerticalAlignment, a single horizontal line will be drawn at the top, center, or bottom of the final Image. I am now embedding the Drawing in a FrameworkElement with the needed absolute positioning.
Corrected per Liz's comment.
If you change Stretch="None" to Stretch="Fill" on your Image it will use the whole space. It won't fill up the whole size of the border, because you have specified a height and width.
Now if you use a GeometryGroup you can specify as many types of lines, paths, whatever. This will then be stretched to fill your image space.
<GeometryGroup>
<LineGeometry StartPoint="0,0" EndPoint="410,0"/>
<LineGeometry StartPoint="0, 100" EndPoint="410, 0"/>
</GeometryGroup>
The lines will be drawn to "fit" your image.
Which is a little closer to what you want, I think. Leaving the the Stretch to None, will draw the objects at the center of the image, and will not stretch them when the image is re-sized.
That seems to be the two alternatives of using the ImageDrawing, either center, or draw to fit.

Resources