wpfsizeopacitymask

Set Size of Rectangle to image size


i'm using this, to show icons that can change their color

<Rectangle Width="100"
           Height="100"
           Fill="{DynamicResource WhiteBrush">
   <Rectangle.OpacityMask>
      <ImageBrush Stretch="Uniform" ImageSource={x:Static ImageResources.MyImage}"/>
   </Rectangle.OpacityMask>
</Rectangle>

The thing is, that not every Image looks good in 100x100 and if I do not fill these values, nothing is shown. What I wanted to achieve is, that the rectangle automatically takes the needed size of the Image, same as if I would use

<Image Source="{x:Static ImageResources.MyImage}"/>

Any Idea how to achieve this? I already tried to give the ImageBrush a name and reference the size from the rectangle, this doesn't work.

As a workaround I placed an Image at the same position with Visibility=Hidden and get the actualHeight and actualWidth for the Rectangle from there, but that's not an acceptable solution. Any hints welcome.


Solution

  • You could bind the Rectangle's Width and Height:

    <Rectangle Fill="{DynamicResource WhiteBrush"
               Width="{Binding Width, Source={x:Static ImageResources.MyImage}}"
               Height="{Binding Height, Source={x:Static ImageResources.MyImage}}">
        <Rectangle.OpacityMask>
            <ImageBrush ImageSource="{x:Static ImageResources.MyImage}"/>
        </Rectangle.OpacityMask>
    </Rectangle>