Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hex() helper function #12

Open
joeworkman opened this issue Apr 12, 2018 · 4 comments
Open

hex() helper function #12

joeworkman opened this issue Apr 12, 2018 · 4 comments

Comments

@joeworkman
Copy link

What about adding a hex() helper function? Something like this...

/**
 * @param mixed ...$args
 * @return string
 */
function hex(...$args) : string
{
    $rgb = color(...$args)->getRgb();
    return sprintf("#%02x%02x%02x", $rgb->getRed(), $rgb->getGreen(), $rgb->getBlue());
}
@joeworkman
Copy link
Author

I would do a pull request but am pretty sure that there is a better way to do this with your setup. I have not had time to familiarize myself with how you setup the code.

@ssnepenthe
Copy link
Owner

ssnepenthe commented Apr 12, 2018

I had considered this at one point but was undecided as to whether a hex helper would be best for converting hex strings to color objects or vice versa... Let me think on this a little more.

For now, color objects actually expose a toHexString method that should do the trick:

echo color("rebeccapurple")->toHexString(); // "#663399"

@joeworkman
Copy link
Author

I should have mentioned that I tried that method. But with color that have an alpha channel, it does not return the correct hex value. It appends an 80 to the end. I did not look into why.

@ssnepenthe
Copy link
Owner

ssnepenthe commented Apr 13, 2018

Oh I see... As of 72ebf7e this package supports rrggbbaa hex notation (caniuse, MDN), so that 80 on the end represents an alpha value of 0.5.

For better or worse, this was added primarily so that name('rgba(102, 51, 153, 0.5)') !== name('rgb(102, 51, 153)').

For the moment a (less than ideal) workaround would be to adjust the alpha value manually before calling toHexString():

$color = color('rgba(102, 51, 153, 0.5)');
$hexWithAlpha = $color->toHexString(); // "#66339980"

// ...

$hexWithoutAlpha = $color->with(['alpha' => 1.0])->toHexString(); // "#663399"

// OR

$hexWithoutAlpha = rgba($color, 1.0)->toHexString(); // "#663399"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants