Var c1 As Color
c1 = Color.RGB(255, 100, 50)
Var hexColor As String = c1.ToString // hexColor = &h00FF6432
Var c2 As Color = Color.FromString(hexColor) // &cFF643200
The above is from the Xojo Documentation. You take a color and turn it into a string and then back into a color. That works fine. But the below confuses me.
Var c3 As Color = Color.FromString("&h00FF6432") // &cFF643200
Var c4 As Color = Color.FromString("&hFAFF6432") // &c00000080
However, when I try and do this with transparency, the second line gives me the puzzling (to me) result of &c00000080.
Note that a hex color has the alpha value at the front instead of the end like an &c color does.
So what happens if you put some value other than 00 in that “alpha” area?
FA is 250 decimal and would specify a very transparent color. I was expecting to get &cFF6432FA as the result of Color.FromString("&hFAFF6432"). Instead I got &c00000080
Can someone explain to me this behavior?
I’m not sure I can explain this – this whole thing is a bit annoying – but I can offer how I worked around it. Don’t use &h – just use &c going in both directions and use variants.
To get the string, assign the Color to a Variant, then get the hex from the StringValue and move the first two characters to the end:
s = mid(s,3)+left(s,2)
To restore this as a color, simply assign it back to a variant with an “&c” prefix:
v = "&c"+s
and then use the variant’s colorvalue or assign the variant to a declared color.
I haven’t tried it, but I’d assume this scheme would work with generating a color hex string and assigning it.
I was trying to write a function to take a color and return a transparent version of that same color. My initial attempt was via extracting the hex string, manipulating it, and then returning the new version of the color via Color.FromString.
For reasons that are unclear to me, that approach failed. I might have been able to build off of Matthew’s technique. Instead, I went the direction below which seems to work and which I include should it help some future visitor.
// METHOD_NAME As String = "GetTransparentColor"
// PARAMETERS: theColor As Color, amountTransparent As Integer
// RETURN TYPE: Color
// DESCRIPTION: return a transparent version of a color
// amountTransparent: The most opaque is 0; the most transparent is 255
Const OPAQUE As Integer = 0
Const TRANSPARENT As Integer = 255
If amountTransparent < OPAQUE Then amountTransparent = OPAQUE
If amountTransparent > TRANSPARENT Then amountTransparent = TRANSPARENT
Return Color.RGB(theColor.Red, theColor.Green, theColor.Blue, amountTransparent)