Microsoft.Maui.Graphics icon indicating copy to clipboard operation
Microsoft.Maui.Graphics copied to clipboard

Color class lacks FromRGB method that takes ints

Open davidbritch opened this issue 3 years ago • 1 comments

In Xamarin.Forms you could specify a Color with int arguments in both the constructor and FromRGB(A) methods. You can't do this in the Color class in MAUI. There's no constructor that takes ints, and no FromRGB(A) method that takes ints. Instead, the the nearest FromRGB method takes bytes.

Initially I accepted this as one of those paper cuts that everyone will have to put up with when moving an app from Forms to MAUI. There may be sound engineering reasons for it. But it's tripped me up, and made me mad, so many times now that I'm creating this issue.

What tends to happen is this: you have Forms code that calls FromRGB(A) with int arguments:

Random random = new Random();
var color = Color.FromRGB(random.Next(255), random.Next(255), random.Next(255));

random.Next(255) returns an int with a max value of 255.

This code worked in Forms and created the correct color. In MAUI, this code builds. You run the code but you don't get the color you expected. You ruminate about this and debug your code. Then you discover the Color that's created has component values all equal to 1. You check the int values being passed to FromRGB - all good. What the hell's going on? Then you discover that there's no FromRGB that takes ints (either from intellisense, or having to inspect the MAUI source because you know not to trust intellisense). But you notice there's a FromRGB that takes bytes. You hoped that your ints would be converted to bytes correctly, but they aren't. You cast your ints to bytes and it all works as expected. Then you curse that you burnt 10 mins on such a simple problem with one line of code, and wonder what you did to deserve this speed bump being put in your path.

Even once you know about this, its through gritted teeth when you have to cast ints to bytes in other Color code. Repeatedly.

Note: if you do Color.FromRGB(128,128,128) you get the expected color. The problem is when you don't use literals. You don't get the expected color when your arguments are ints returned by methods, or int variables.

davidbritch avatar Feb 07 '22 09:02 davidbritch

Hi @davidbritch, at first glance this seems like it may be an oversight and not an intentional design decision. I'll add some links to source code for context.

Related issues

  • ⚠️ This issue is a duplicate of #253
  • #63
  • #58
  • #56
  • #280
  • #281

Constructors that accept int

There's no constructor that takes ints

Fluent methods that accept int

there's no FromRGB that takes ints

It seems like this issue may be resolved by creating overloads that accept int that expect values between 0 and 255.

I'll look into this more tonight and create a PR that adds these overloads 👍

swharden avatar Feb 07 '22 13:02 swharden