rubymotion-community / sugarcube

Some sugar for your cocoa. RubyMotion helpers.
Other
421 stars 66 forks source link

Add .darken and .lighten methods to UIColor. #181

Closed silasjmatson closed 9 years ago

silasjmatson commented 9 years ago

Changes the brightness using the HSB values.

colinta commented 9 years ago

I love the idea! I think we'll ned to tweak the implementation a bit. For instance, this doesn't use the existing brightness value, so calling darken(10).darken(10) is the same as just .darken(10). Also, any positive value for lighten will result in "white", no matter what color you start with. This is because new_brightness = (100 + percent) / 100 will be > 1 if percent is positive.

(main)> '#ffffff'.uicolor.darken(10.0)
=> '#e5e5e5'.uicolor
(main)> '#ffffff'.uicolor.darken(10.0).darken(10.0)  # calling darken a second time
=> '#e5e5e5'.uicolor
(nil)? '#e5e5e5'.uicolor.lighten(10.0)
=> :white.uicolor
(main)> '#e5e5e5'.uicolor.lighten(1)
=> :white.uicolor
(main)> '#000000'.uicolor.lighten(1)
=> :white.uicolor
colinta commented 9 years ago

I'm thinking that we should encourage the "raw values" that the brightness: argument accepts, too. What do you think about this:

  def darken(amount=0.1)
    change_brightness -amount
  end

  def lighten(amount=0.1)
    change_brightness amount
  end

  def change_brightness(amount)
    new_brightness = brightness + amount
    UIColor.colorWithHue(hue, saturation: saturation, brightness: new_brightness, alpha: alpha)
  end
silasjmatson commented 9 years ago

I apparently didn't test as well as I thought. :tongue: My original implementation used the original brightness, but somehow it changed to not include it. Probably one of my "let's simplify things" refactors.

I think using raw values works just as well. We are programmers, after all. And it makes the implementation easy!

silasjmatson commented 9 years ago

Is this behavior expected?

(main)> "#ffffff".uicolor.darken(0.1).lighten(0.1)
=> :white.uicolor
(main)> "#ffffff".uicolor.darken(0.1).lighten(0.1).hex
=> "#ffffff"
(nil)? '#e5e5e5'.uicolor.lighten(0.1).hex
=> "#fefefe"

It makes sense when I think about it (limitations of RGB color space), but colors make my head hurt. Maybe we want to find an actual algorithm and allow adjusting using either RGB or HSB?

colinta commented 9 years ago

Meh, I think just pushing the brightness up and down works well. Thoughts on this? ad13a6a

silasjmatson commented 9 years ago

:+1: :shipit: Looks good to me!

colinta commented 9 years ago

Done! Available in 3.0.5. Thanks!