0

I'm writing a WPF application. All icons I use are vector and stored in standalone ResourceDictionary as series of Viewboxes:

<ResourceDictionary>
    <ViewBox x:Shared="False" x:Key="IconKey" Stretch="Uniform">
        <Canvas Width="16" Height="16">
            <Path ... />
        </Canvas>
    </ViewBox>

    <!-- ... -->
</ResourceDictionary>

I'm implementing now a user control, which, due to very specific requirements, is drawn from scratch by me in OnRender method.

I need to render these icons on my control. One solution is to rasterize them and then draw bitmaps, but the problem is, that view in my control can be freely zoomed, and such icons would look ugly when zoomed in (as opposed to vector ones). Is there a way to render a ViewBox using the DrawingContext?

rudolph1024
  • 962
  • 1
  • 12
  • 32
Spook
  • 25,318
  • 18
  • 90
  • 167

1 Answers1

0

I don't know how you can render ViewBox but you can render Geometry and that will not be ugly when zoomed.

I have created icon in a XAML file. Build Action: Page.

File:Icon.xaml

<?xml version="1.0" encoding="UTF-8"?>
<Viewbox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Stretch="Uniform">
    <Canvas Width="25" Height="25">
        <Path Fill="#FF000000" StrokeThickness="0.4">
            <Path.Data>
                <PathGeometry Figures="M 4.9586532 4.4020592 12.198751 19.198359 V 0.91721594 H 20.200561 h 2.894515  Z" FillRule="Nonzero"/>
            </Path.Data>
        </Path>
    </Canvas>
</Viewbox>

To draw this with DrawingContext create method like this

void DrawIcon(DrawingContext context, double left, double top, double scale = 1)
{
      var transform = new MatrixTransform(scale, 0, 0, scale, left, top);
      var viewBox =  (Viewbox) Application.LoadComponent(new Uri("/MyProjectNameSpace;component/Icon.xaml", UriKind.Relative));
    
      var canvas = viewBox.Child as Canvas;
      if (canvas?.Children == null) return;
      foreach (UIElement child in canvas.Children)
           if (child is Path path)
           {
               path.Data.Transform = transform;
               context.DrawGeometry(Brushes.Black, new Pen(Brushes.Black, 1), path.Data);
           }
}
Hacko
  • 1,551
  • 1
  • 15
  • 11