Search code examples
c#uwpavataruwp-xamlavatars

Avatar contact Image how to dynamically display user profile image and the last name with random color UWP?


I'm writing Avatar for the contact list. The design is like this, if I can get the contact's image then I display the image. If not I need to show capital letter of the last name with random color. I know how to display round image

<Button>
    <Button.Content>
        <Ellipse>
             <Ellipse.Fill>
                 <ImageBrush ImageSource="{Binding Image}"/>
             </Ellipse.Fill>
         </Ellipse>
     </Button.Content>
</Button>

I'm wondering what is the direction to display those without image and I have to display letter of last name and fill the ellipse with random color. My idea is that in the Image's getter write some conditional code to decide what to display. But how to make the image with given letter and random color.


Solution

  • You could always go ahead and generate the required image in code but that might get unnecessarily complicated.

    I would suggest a simpler approach

    <Button>
        <Button.Content>       
            <Grid>
                <Ellipse Fill="{x:Bind FillBrush}"/>
                <TextBlock Text="{x:Bind Initials}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </Grid>
         </Button.Content>
    </Button>
    

    In your ViewModel you would have something like this:

    public Brush FillBrush { get; set; }
    public string Initials { get; set; }
    

    And some logic to figure out how to populate those properties. If you have an image, leave the Initials property empty and set the FillBrush to an ImageBrush. If yo don't have an image, set the FillBrush to a new SolidColorBrush initialized with a random color, and set the Intials to the right value.

    *You will of course need to set the proper style to the TextBlock and raise the proper NotifyPropertyChanged events in your ViewModel.

    **Bonus points if you can either generate only random background colors that work with whatever foreground you choose for the TextBlock, or depending on desired design, choose White or Black foreground based on the random Background color.

    I think this would be much easier to code and maintain and be faster at runtime than generating images when you don't have one already.