Home > Software engineering >  Change color from one value to another based on offset
Change color from one value to another based on offset

Time:12-10

I want to change 1 color value which will be represented by offset 1.0 to another color value represented by offset 0.0.

I don't want to use ValueAnimator because animation will be made by myself (function to change color is called everytime offset changes based on scroll listener) and I don't need to really "animate" it by duration.

I tried this:

val color = ArgbEvaluator().evaluate(offset, R.color.start, R.color.end)

But color is type of Any and not color I can set as backgroundTint for example.

CodePudding user response:

You're on the right track, you're just missing a cast.

val color = ArgbEvaluator().evaluate(offset, startColor, endColor) as Int

myView.setBackgroundColor(color)

CodePudding user response:

ArgbEvaluator#evaluate takes an

Object: A 32-bit int value representing colors in the separate bytes of the parameter

as its second and third arguments. What you are using are the resource id of the colors you want. You will need to translate those resource ids into 32-bit colors.

val startColor = ResourcesCompat.getColor(resources, R.color.start, null)
val endColor = ResourcesCompat.getColor(resources, R.color.end, null)
val color = ArgbEvaluator().evaluate(offset, startColor, endColor)
binding.textView.setBackgroundColor(color as Int)
  • Related