-
-
Save guiled/4407a4e7cd21025aec3f to your computer and use it in GitHub Desktop.
A fixed version for animated color in Titanium
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// next two from http://stackoverflow.com/a/5624139/292947 | |
function componentToHex(c) { | |
var hex = c.toString(16); | |
return hex.length == 1 ? "0" + hex : hex; | |
} | |
function rgbToHex(r, g, b) { | |
return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b); | |
} | |
function calculateSteps(begin, end, numSteps) { | |
var colorSteps = []; | |
var startRGB = parseColor(begin), | |
endRGB = parseColor(end), | |
// We don't round the diffs variable in order to have a smooth animation, and in order to prevent some bugs. Rounds are made in the rgbToHex | |
diffR = (endRGB[0] - startRGB[0]) / numSteps, | |
diffG = (endRGB[1] - startRGB[1]) / numSteps, | |
diffB = (endRGB[2] - startRGB[2]) / numSteps, | |
current = startRGB; | |
Ti.API.info('startRGB ' + startRGB + ' endRGB ' + endRGB + ' diffR ' + diffR + 'diffG ' + diffG + ' diffB ' + diffB); | |
for (var i = 0; i < numSteps; i++) { | |
current[0] += diffR; | |
current[1] += diffG; | |
current[2] += diffB; | |
// We make the rgbToHex here in order to have a lighter animation callback | |
colorSteps.push(rgbToHex(Math.round(current[0]), Math.round(current[1]), Math.round(current[2])]); | |
} | |
startRGB = endRGB = diffR = diffG = diffB = current = null; | |
return colorSteps; | |
} | |
exports.animateColor = function (_obj, _newColor, _duration) { | |
var step = 0, steps = calculateSteps(_obj.color, _newColor, _duration); | |
var interval = setInterval(function() { | |
_obj.color = steps[step]; | |
step++; | |
if (step === steps.length) { | |
clearInterval(interval); | |
steps = null; | |
step = null; | |
_obj = null; | |
} | |
}, 1); | |
}; | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('anim').animateColor($.label, '#123456', 200); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment