Skip to content
This repository has been archived by the owner on Dec 21, 2023. It is now read-only.

Color: add overloads so int does not get clamped like a float #310

Merged
merged 5 commits into from
Feb 12, 2022

Conversation

swharden
Copy link
Contributor

@swharden swharden commented Feb 7, 2022

This PR adds overloads for the Color constructor, FromRgb(), and FromRgba() that accept int.

Reported by @PureWeen in #253 and @davidbritch in #308, there exists a problem where int values (expected to be 0-255) are interpreted as float and clamped between 0 and 1.0, demonstrated here:

// fill a circle with a random color using a fluent method
canvas.FillColor = Color.FromRgba(rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255), rand.Next(100, 200));
canvas.FillCircle(pt1, radius);

// fill a circle with a random color using a constructor
canvas.FillColor = new Color(rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255), rand.Next(100, 200));
canvas.FillCircle(pt2, radius);
Full source code
using Microsoft.Maui.Graphics;
using Microsoft.Maui.Graphics.Skia;

Random rand = new(0);
using BitmapExportContext bmp = new SkiaBitmapExportContext(300, 200, 1.0f);
ICanvas canvas = bmp.Canvas;

// draw a test pattern in the background
canvas.FillColor = Colors.DarkGray;
canvas.FillRectangle(0, 0, bmp.Width, bmp.Height);
canvas.StrokeSize = 3;
canvas.StrokeColor = Colors.Black;
for (int i = 0; i < bmp.Width * 2; i += 50)
    canvas.DrawLine(0, i, i, 0);

// define a pair of circles
PointF pt1 = new(100, 100);
PointF pt2 = new(200, 100);
float radius = 75;

// fill a circle with a random color using a fluent method
canvas.FillColor = Color.FromRgba(rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255), rand.Next(100, 200));
canvas.FillCircle(pt1, radius);

// fill a circle with a random color using a constructor
canvas.FillColor = new Color(rand.Next(0, 255), rand.Next(0, 255), rand.Next(0, 255), rand.Next(100, 200));
canvas.FillCircle(pt2, radius);

string filePath = Path.GetFullPath("test.png");
using FileStream fs = new(filePath, FileMode.Create);
bmp.WriteToStream(fs);
Console.WriteLine(filePath);
Original Behavior New Behavior
before after

Without these overloads it is possible that integers (expected to be 0-255) are interpreted as floats and clamped between 0 and 1.0 dotnet#308, dotnet#253
Without these overloads it is possible that integers (expected to be 0-255) are interpreted as floats and clamped between 0 and 1.0 dotnet#308, dotnet#253
Since methods FromRgb() and FromRgba() have overloads that accept bytes it seems logical that there are matching constructors that accept this data type. dotnet#308, dotnet#253
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants