How did I do?*

Add custom icons to MudBlazor

Blazor comes with a large library of icons using Material UI, which you can use as standalone icons, or as part of other components like icon buttons, but sometimes you want to use an image which doesn't come included.

The following example shows you how to add an image of GOV.UK's crown logo to a MudBlazor component, MudChip.

MudBlazor Icon objects are simply strings consisting of the SVG markup needed to draw the image.

First start with the image you want to add - the format doesn't really matter at this stage but you need to be able to convert it to an SVG if it isn't already, so PNG or JPG are fine, but even newer formats such as WebP can be used.

There are lots of online tools available for conversion, and we'll be using two free ones I just found from a quick Google search:

  1. convert a WebP image into SVG: WebP to SVG Converter
  2. shrink larger images to the required dimensions: I🩶IMG resizer

I'll be using a MudChip component, and MudBlazor icons need to be 24x24 pixels to fit in this element without additional styling rules.

I started off with this image of the GOV.UK crest which I found online, which is a WebP file, with dimensions of 512x512 pixels.

GOV.UK crest
GOV.UK crest

First step is to upload it to converter to convert it to an SVG, then once that is done it can be uploaded to the resizer to reduce the dimensions to 24x24 pixels.

There's likely a better option to load this SVG in a more refined manner, but the simplest way is to save the string as a variable and reference it in the component. Open the SVG in a text editor, copy the markup, then define a string variable with it as the value:

// String condensed for brevity
const string govUkLogo =
    @"<svg width=""24px"" height=""24px"" viewBox=""0 0 24 24"">
        <g id=""surface1"">
            <path fill-rule=""evenodd"" clip-rule=""evenodd"" fill=""#FFFFFF"" d=""M 5.90625 11.484375 C 6.554688 ...""/>
        </g>
    </svg>";

Note the double quotation marks around each attribute

Add a MudBlazor component, referencing the new variable as the Icon parameter:

<MudChip T="string" Icon="@govUkLogo" Color="@Color.Success" Style="font-weight:bold;">
GOV.UK logo in a MudBlazor MudChip element
GOV.UK logo in a MudBlazor MudChip element