简体   繁体   English

WPF-通过其ImageBrush不透明度蒙版调整矩形的大小

[英]WPF - Size rectangle by its ImageBrush opacity mask

I have a rectangle which has an ImageBrush opacity mask (basically a coloured icon). 我有一个具有ImageBrush不透明蒙版的矩形(基本上是一个彩色图标)。

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? 是否可以根据ImageBrush图像大小来调整矩形大小?

Thanks for your help. 谢谢你的帮助。 Sorry if this is a silly question, I am still learning WPF. 抱歉,如果这是一个愚蠢的问题,我仍在学习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. Stretch="None"保持图像大小。 Rectangle with binding ActualWidth and ActualHeight resize from ImageBrush size. ImageBrush大小调整绑定了ActualWidthActualHeight矩形。 Result is same if we don't use both. 如果我们不使用两者,结果是相同的。 On both case rectangle resize to true ImageBrush size. 在两种情况下,矩形都将调整为真正的ImageBrush大小。 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. 如果想法是周围有黑色,请在外部网格上使用Background =“ Black”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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