views:

138

answers:

2

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.

A: 

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.

ChrisF
That's what I was hoping to avoid but I may not have any other options.
Micah
@Micah - I've just thought of something else - updating answer.
ChrisF
Not a bad idea. I might try that. I'm using the icons in the WP7 sdk. Maybe I can conver the vector file to xaml.
Micah
+3  A: 

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.

Denis
Awesome!!! That totally worked. I'll need to figure out how to incorporate it into my solution, but huge thanks!!
Micah