Silverlight中Image.OpacityMask上的矩形

时间:2013-10-10 11:44:02

标签: c# silverlight windows-phone-7 windows-phone-8

我想在WinPhone中为Image.OpacityMask添加Rectangle。

WPF很容易:

<Image 
      Grid.Row="4" Grid.Column="5"
      Height="150"
      Width="200"
      Source="sampleImages/Waterlilies.jpg">
  <Image.OpacityMask>
    <DrawingBrush>
      <DrawingBrush.Drawing>
        <GeometryDrawing>
          <GeometryDrawing.Geometry>
            <RectangleGeometry Rect="0.05,0.05 0.9,0.9" />
          </GeometryDrawing.Geometry>
      </GeometryDrawing>
      </DrawingBrush.Drawing>
    </DrawingBrush>
  </Image.OpacityMask>
</Image>

但是在WinPhone上我们不能使用DrawingBrush。

如何在WinPhone上为Image上的OpasityMask添加Rectangle?

2 个答案:

答案 0 :(得分:0)

似乎您只是想剪切图像,因此您可以使用可以设置为几何体的Clip属性。
如果你实际上想要实现更复杂的东西,那么你可以使用WriteableBitmap将Geometry渲染成Bitmap并使用OpacityMask中的可写位图。 以下附加属性可以帮助您实现这一目标:

public class MyAttached
{

    public static readonly DependencyProperty GeometryOpacityMaskProperty =
        DependencyProperty.RegisterAttached("GeometryOpacityMask", typeof(Path), typeof(MyAttached), new PropertyMetadata(default(Path), GeometryOpacityMaskChanged));

    private static void GeometryOpacityMaskChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        FrameworkElement uiElement = d as FrameworkElement;

        Path path = e.NewValue as Path;
        if (path != null && uiElement != null)
        {
            WriteableBitmap writeableBitmap = new WriteableBitmap((int)uiElement.Width, (int)uiElement.Height);
            writeableBitmap.Render(path, new CompositeTransform());
            writeableBitmap.Invalidate();

            ImageBrush imageBrush=new ImageBrush();
            imageBrush.ImageSource = writeableBitmap;
            uiElement.OpacityMask = imageBrush;
        }
    }

    public static void SetGeometryOpacityMask(UIElement element, Path value)
    {
        element.SetValue(GeometryOpacityMaskProperty, value);
    }

    public static Path GetGeometryOpacityMask(UIElement element)
    {
        return (Path)element.GetValue(GeometryOpacityMaskProperty);
    }
}

你可以像这样使用:

<Image 

  Height="150"
  Width="200"
  Source="sampleImages/Waterlilies.jpg"
        Stretch="UniformToFill"
        >
        <phoneApp1:MyAttached.GeometryOpacityMask>
            <Path>
                <Path.Data>
                    <RectangleGeometry Rect="0.05,0.05 0.9,0.9" />
                </Path.Data>
            </Path>
        </phoneApp1:MyAttached.GeometryOpacityMask>
    </Image>

答案 1 :(得分:0)

使用Image.Clip剪切部分图像。

剪辑椭圆:

<Image Name="Img" Source="/UntitledImage.jpg">
  <Image.Clip>
    <EllipseGeometry Center="115,115" RadiusX="50" RadiusY="50"></EllipseGeometry>
  </Image.Clip>
</Image>

剪辑矩形:

<Image Name="oldImg" Source="/UntitledImage.jpg">
  <Image.Clip>
    <RectangleGeometry Rect="115,115,50,50"></RectangleGeometry>
  </Image.Clip>
</Image>