1

In a WPF User Control, I am trying to mask an Image control with a circle that can vary in position and size. The user left-drags to change the circle radius and right-drags to change the center point of the ellipse. I'm capturing all the needed values correctly and can properly set the radius of the mask. The problem is, that no matter what point I use for the center of the ellipse, it is drawn from the center of the Image control. Any ideas?

Below is the code that sets the mask:

private void SetMask(double _Radius)
{
        EllipseGeometry MaskGeometry = new EllipseGeometry(CenterPos, _Radius, _Radius);
        GeometryDrawing MaskDrawing = new GeometryDrawing(Brushes.Black, null, MaskGeometry);
        DrawingBrush MaskBrush = new DrawingBrush(MaskDrawing);
        MaskBrush.Stretch = Stretch.None;
        Img.OpacityMask = MaskBrush;  //Img is the Image control
}
4

2 回答 2

3

您还必须设置ViewboxUnitsAlignmentXAlignmentY属性:

private void SetMask(double radius)
{
    var maskGeometry = new EllipseGeometry(CenterPos, radius, radius);
    var maskDrawing = new GeometryDrawing(Brushes.Black, null, maskGeometry);
    var maskBrush = new DrawingBrush
    {
        Drawing = maskDrawing,
        Stretch = Stretch.None,
        ViewboxUnits = BrushMappingMode.Absolute,
        AlignmentX = AlignmentX.Left,
        AlignmentY = AlignmentY.Top
    };

    Img.OpacityMask = maskBrush;
}
于 2013-01-11T18:36:06.480 回答
0

您需要修改DrawingBrush 基础图块的ViewportViewportUnits属性:

private void button1_Click(object sender, RoutedEventArgs e)
    {
        EllipseGeometry MaskGeometry = new EllipseGeometry(CenterPos, _RadiusX, _RadiusY);
        GeometryDrawing MaskDrawing = new GeometryDrawing(Brushes.Black, null, MaskGeometry);
        DrawingBrush MaskBrush = new DrawingBrush(MaskDrawing);
        MaskBrush.Stretch = Stretch.None;
        MaskBrush.ViewportUnits = BrushMappingMode.Absolute;
        MaskBrush.Viewport = MaskGeometry.Bounds;
        Img.OpacityMask = MaskBrush;  //Img is the Image control

    }

这里的MSDN 文档很好地解释了如何使用 TileBrush 绘制控件。

于 2013-01-11T18:43:09.617 回答