11
votes

I have a toggle button with a png that has a transparent background and a black foreground. If the button is selected then I want the black color of the image to change to a color chosen by the user. Is there a way to do this in Silverlight and/or wp7?

So for example:

<ToggleButton>
    <Image Source="MyImage.png" />
</ToggleButton>

MyImage.png has a transparent background and a black foreground. The user's preferred color is red. When the button is toggled on I want the black foreground of the image to turn red.

2

2 Answers

22
votes

I would try OpacityMask approach. Basicaly it should look something like this:

<Rectangle Fill="Red">
  <Rectangle.OpacityMask>
    <ImageBrush ImageSource="MyImage.png"/>
  </Rectangle.OpacityMask>
</Rectangle>

by changing rectangle's fill property you would get different colored image.

0
votes

How much control does the user have over the colour?

If they are picking from a limited set (e.g. red, green, blue, black, brown) then the simplest thing to do would be to bind the image source to a variable which holds the name of the image and then change which name is held in that variable.

If they can pick any colour then you need to do some image processing to change the black pixels of a reference image to the selected colour, write that to isolated storage and then bind the image source to that new file.

Another alternative is to draw the button in XAML and then you can have direct control over the foreground colour. This MSDN page describes the basics of drawing. You can use the same commands to define the image on a button, as described on this page from Scott Gu's blog:

image of code from blog

(this is the image of the code from the blog).

If you bind the colour to a variable then the user can change the colour of the image. It does rely on you being able to draw the image in XAML though.