質問

Let's suppose, that we have the following vector image consisting of two paths:

<Path Data="M 0 0 L 4 0 L 4 8 L 0 8 Z" Fill="Black" />
<Path Data="M 4 0 L 8 0 L 8 8 L 4 8 Z" Fill="Black" />

The most important fact is, that this image is supposed to be 16x16 units (despite fact, that only 8x8 square area is covered by the actual image).

I want the image to scale to desired size - for example, I want to place it somewhere with size 32x32 (then, the drawn square should be of 16x16 size). How can I do it?

The even harder part is, that I want the image to reside in the resources. This can be solved in the following way:

<Canvas Width="16" Height="16" x:Key="MyImage">
    <Path Data="M 0 0 L 4 0 L 4 8 L 0 8 Z" Fill="Black" />
    <Path Data="M 4 0 L 8 0 L 8 8 L 4 8 Z" Fill="Black" />
</Canvas>

(...)

<ContentPresenter Content="{DynamicResource MyImage}" />

But that doesn't solve the problem with scaling. If it is possible, I would like a solution not involving usage of various Transforms.

役に立ちましたか?

解決

If you want it to resize nicely to any size, place it in a Viewbox with Stretch="Fill".

<Viewbox Stretch="Fill" x:Key="MyImage">
    <Canvas Width="16" Height="16">
        <Path Data="M 0 0 L 4 0 L 4 8 L 0 8 Z" Fill="Black" />
        <Path Data="M 4 0 L 8 0 L 8 8 L 4 8 Z" Fill="Black" />
    </Canvas>
</Viewbox>

This will stretch the content to whatever the size of the Viewbox is.

If you want different stretching behaviour: System.Windows.Media.Stretch

他のヒント

I believe that you might have the wrong impression about vector graphics in WPF. While it is true that because WPF utilises vector graphics, it can smoothly scale these graphics, it should be noted that they do not scale themselves.

Therefore, you have a list of instructions that describe how to recreate an image using graphics primitives in your Path object, but it holds no resizing abilities. For resizing duties, you have two options: Use a ScaleTransform, or use a ViewBox (from the linked page on MSDN):

<Path Data="M10,100 C 60,0 100,200 150,100 z" 
    Fill="{StaticResource linearGradientBackground}"
    Stroke="Black"
    StrokeThickness="2">
    <Path.RenderTransform>
        <ScaleTransform ScaleX="3.0" ScaleY="3.0" />
    </Path.RenderTransform>
</Path>

...

<ViewBox Stretch="Uniform">
    <Path Data="M10,100 C 60,0 100,200 150,100 z" 
        Fill="{StaticResource linearGradientBackground}"
        Stroke="Black"
        StrokeThickness="2">
    </Path>
</ViewBox>
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top