Search code examples
xamlwindows-phone

How to clip an image in a round way, without knowing its dimensions in XAML


I have an image element in my XAML, and I don't want to specify its dimensions because I'd like it to scale according to the resolution of the display size.

I need to clip the image in a circle, how can I do it without explicitly stating its dimensions?


Solution

  • I interpret your question that you want to make a circular image which fills the parent container. Using an ellipse with Stretch="Uniform" to create a circle and then set the Fill to the image which is placed inside a Grid for example it will fill it's parent, example:

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <Ellipse Stretch="Uniform">
            <Ellipse.Fill>
                <ImageBrush ImageSource="/Assets/avatarpic-l.png" />
            </Ellipse.Fill>
        </Ellipse>
    </Grid>
    

    This will give the following result:

    enter image description here

    There is also an alternative method which produces the same result using OpacityMask (by varying the Offset parameters you can also get some nice fade effects):

    <Image Source="/Assets/avatarpic-l.png">
        <Image.OpacityMask>
            <RadialGradientBrush GradientOrigin="0.5,0.5" Center="0.5,0.5" RadiusX="0.5" RadiusY="0.5">
                <GradientStop Color="#ffffffff" Offset="1.0" />
                <GradientStop Color="#00ffffff" Offset="1.0" /> 
            </RadialGradientBrush>
        </Image.OpacityMask>
    </Image>
    

    With this second approach if you set <Image Source="/Assets/avatarpic-l.png" Stretch="None" >...</Image> you can get the image to maintain its original dimensions too.