Reputation:
I'm currently trying to take in a hex value for a color, ie #0000ff
or #0000ffff
if it's in hexadecimal (if this is right), and then pass it into my Paint object with paintObject.setColor().
However, whenever I try to do something of the following, I always get a failure message saying parseInt() failed with the following inputs:
String hexColor = "#0000ff";
String longerColor = "#0000ffff";
paintObject.setColor(Integer.parseInt(hexColor));
paintObject.setColor(Integer.parseInt(longerColor));
paintObject.setColor(Integer.parseInt("0x" + hexColor.substring(1)));
paintObject.setColor(Integer.parseInt("0x" + longerColor.substring(1)));
Manually plugging in an integer, ie something like 0xFFFFA500
allows me to just set the color as orange, so I'm pretty confused here. I'm sure its a tiny error that I'm making.
Upvotes: 1
Views: 335
Reputation: 1471
Most direct solution would be to use Color.parseColor:
String hexColor = "#0000ff"; String longerColor = "#0000ffff";
paintObject.setColor(Color.parseColor(hexColor));
which accepts the strings you have specified (both rgb and argb).
If the hex strings are not validated for format then be sure to handle the IllegalArgumentException
thrown by parseColor
.
Alternatively, to follow along your attempts, specify the radix in Integer.parseInt()
:
paintObject.setColor(Integer.parseInt(hexColor.substring(1),16));
As you have used it, the Integer.parseInt(s)
assumes a radix of 10 and the only non-digit characters it accepts are a +
or -
in the first position.
Upvotes: 3