L
L
Lev Aleksandrov2021-07-13 20:03:29
C++ / C#
Lev Aleksandrov, 2021-07-13 20:03:29

How to smoothly change an integer over some time from one value to another?

There is a color that is specified as an integer value in the extended HEX format with an alpha channel (HEXA).
For example, 0x12ABCDFF. Here alpha channel = 0xFF, i.e. without transparency.
You need to write a function with the following prototype:
void fadeColor(int &hexa, int duration, bool in = false);
The essence of its work:
The color itself is accepted (or rather, the address of the variable where it is stored), the transparency of which (alpha channel) should change during the duration time (in ms) or from the current value (taken from hexa) to 0xFF (then the argument in == true , which means fade in - smooth appearance), or from the current value to 0x00 (argument in == false, which means fade out - smooth disappearance)
Here is the pseudocode of what I wrote:

void fadeColor(int &hexa, int duration, bool in = false)
{
    int from = hexa; // начальное значение цвета
    int to = (in) ? (from | 0xFF) : (from - (from & 0xFF)); // конеченое значение цвета
    // у конечного значения альфа меняется либо на 00 либо на FF в зависимости от in.
    int update_rate = (to - from)/duration; // шаг изменения цвета за 1 мс

    SetTimer("_onColorFade", 1, "ddd", from, to, update_rate); // внизу объясню, что это за функция
}

void _onColorFade(int &from, int to, int update_rate)
{
    from += update_rate; // меняем цвет

    if (from == to) // если дошли до конечного цвета, то останавливаемся
        return;
    // иначе продолжаем менять цвет
    SetTimer("_onColorFade", 1, "ddd", from, to, update_rate); // снова запускаем 
}


SetTimer function:
1st argument is a function that will be called after the time in ms specified in the 2nd argument (1 time), followed by the parameters passed to this function with their format.

It turned out that the function does not work correctly, because update_rate (color change step per 1 ms) may turn out to be a fractional number, which is subsequently cut off and, as a result, the algorithm does not work correctly. And the colors are given only by an integer.

In short, the task is as follows:
smoothly decrease the number from 255 to 0 in the specified time, or smoothly increase the number from 0 to 255 in the specified time in milliseconds (only integer intermediate values ​​are allowed!)
Is there any ready-made algorithm for solving such a problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
Wataru, 2021-07-13
@wataru

Count in floats and round before returning the result.
Or calculate according to the formulaans = from + (to-from+0.0)*time/duration

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question