简体   繁体   中英

WPF - Size rectangle by its ImageBrush opacity mask

I have a rectangle which has an ImageBrush opacity mask (basically a coloured icon).

This is my current code:

<Rectangle Fill="Black">
  <Rectangle.OpacityMask>
    <ImageBrush ImageSource="/Path/To/Icon.png"/>
  </Rectangle.OpacityMask>
</Rectangle>

This produces no result without setting a fixed width and height for the rectangle. Is it possible to size the rectangle according to the ImageBrush image size?

Thanks for your help. Sorry if this is a silly question, I am still learning WPF.

Edit : To clarify, what I am trying to achieve is for the rectangle to behave same as this:

<Image Source="/Path/To/Icon.png"/>

It should be sized according to the dimensions of the image source file.

Stretch="None" keep image size. Rectangle with binding ActualWidth and ActualHeight resize from ImageBrush size. Result is same if we don't use both. On both case rectangle resize to true ImageBrush size. Hope I understand your problem.

<Rectangle Fill="Black" Width="{Binding ActualWidth, ElementName=image}" Height="{Binding ActualHeight, ElementName=image}">
    <Rectangle.OpacityMask>
        <ImageBrush ImageSource="/Path/To/Icon.png" x:Name="image" Stretch="None">
        </ImageBrush>
    </Rectangle.OpacityMask>
</Rectangle>
 <Rectangle Width="{Binding ActualWidth, ElementName=image}" Height="{Binding ActualHeight, ElementName=image}">
    <Rectangle.Fill>
        <ImageBrush ImageSource="C:\Users\neeraj\Pictures\Img1.jpg" x:Name="image" Stretch="None">
        </ImageBrush>
    </Rectangle.Fill>
</Rectangle>

Try this snippet. I am not sure why you wanted the fill black. If idea was to have a Black surrounding, use Background="Black" on the outer Grid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM