Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Algorithm for coloring a line based on its length

edited August 2013 in Questions Posts: 38

I'm having trouble figuring out the math involved in changing a line's stroke color based on its variable length. The goal is that when the line gets shorter it will be gradually drawn red and when it gets longer it gradually draws blue. And there is a middle ground where in between shorter and longer it is just white. For example:

-- line test
supportedOrientations(LANDSCAPE_ANY)

function setup()
    parameter.integer( "length", 100, 600, 350 )
    parameter.watch( "i" )

    RED_MIN = 200
    RED_MAX = 100
    BLUE_MIN = 500
    BLUE_MAX = 600
end

function draw()

    if length <= RED_MIN then
--      i = 255 - (255 * a value between 0 and 1, where 0 is f(length=RED_MIN) and 1 is f(length=RED_MAX)
        c = color(255, i, i, 255)
    elseif length >= BLUE_MIN then
--      i = 255 - (255 * a value between 0 and 1, where 0 is f(length=BLUE_MIN) and 1 is f(length=BLUE_MAX)
        c = color(i, i, 255, 255)
    else
        c = color(255,255,255,255)
    end

    background(40, 40, 50)

    strokeWidth(5)
    stroke(c)
    line(70, HEIGHT/2, 70+length, HEIGHT/2)
end

Thanks again guys!

Tagged:

Comments

  • Posts: 2,161
    function interp(l,m,n)
        return math.max(0,math.min(1,(l-m)/(n-m))
    end
    

    call as interp(length,RED_MIN,RED_MAX) and you get out a number between 0 and 1 so that if length is in between then it is the correct proportion, but it is "clamped" to the end points in that it never goes below 0 or above 1.

  • Jmv38Jmv38 Mod
    Posts: 3,297

    Check this:


    -- line test supportedOrientations(LANDSCAPE_ANY) function setup()     parameter.integer( "length", 100, 600, 350 )     parameter.watch( "i" )     RED_MIN = 200     RED_MAX = 100     BLUE_MIN = 500     BLUE_MAX = 600 end function draw()     background(40, 40, 50)     strokeWidth(5)     local r,g,b,i     if length < RED_MAX then         r,g,b = 255,0,0     elseif length < RED_MIN then         i = 255*(length-RED_MAX)/(RED_MIN-RED_MAX)         r,g,b = 255,i,i     elseif length < BLUE_MIN then         r,g,b = 255,255,255     elseif length < BLUE_MAX then         i = 255*(length-BLUE_MAX)/(BLUE_MIN-BLUE_MAX)         r,g,b = i,i,255     else         r,g,b = 0,0,255     end     c = color(r,g,b,255)     stroke(c)     line(70, HEIGHT/2, 70+length, HEIGHT/2) end
  • Posts: 38

    @Andrew_Stacey and @Jmv38

    Excellent solutions guys! Exactly what I was hoping for from this forum! Thanks so much!

Sign In or Register to comment.