ajalt / colormath

Multiplatform Kotlin color conversion and manipulation
https://ajalt.github.io/colormath/
MIT License
308 stars 21 forks source link

Parsing a hex color to RGB without an explicit alpha results in NaN alpha #21

Closed saket closed 3 years ago

saket commented 3 years ago

Hey @ajalt, I am replacing my custom color parsing function with RGB(hex: String) introduced in 3.0.0 and noticed that RGB(hex) uses an alpha of NaN by default if the hex string doesn't explicitly specify an alpha. Was this intentional? This seems inconsistent with other platforms, atleast on android and on the web where, say, #FFFFFF is parsed as a white with 100% alpha.

ajalt commented 3 years ago

Yes, it was by design. From the docs:

If you don’t specify an alpha value, it will default to NaN. This makes it possible to distinguish unspecified alpha values, which can be important for operations like interpolation.

Using NaN allows the application to choose the default. That design is open for discussion, though. Is it causing problems?

saket commented 3 years ago

It isn't a big issue, but it caught me by surprise when I tried converting my RGB types into Color for Compose UI -- especially because the error only shows up at runtime. The parsing logic feels inconsistent to me when I compare it with other platforms. Is there any prior art of parsing absence of alpha as NaN on other platforms?

ajalt commented 3 years ago

Yes, but I agree that it's uncommon enough that most people would be surprised, which I'd like to avoid.

So I'm thinking of two changes that wouldn't require breaking the API:

  1. default alpha to 1 everywhere
  2. add optional subpackages with extensions for converting to and from other platforms color classes (Android ColorInt, Android Color, Compose Color, and Compose Web Color)
saket commented 3 years ago

both these changes will be very welcome!