```val xOffset by infiniteTransition.animateFloat(...
# compose
u
Copy code
val xOffset by infiniteTransition.animateFloat(
    ...
    animationSpec = infiniteRepeatable(
        animation = tween(durationMillis = 1500, easing = LinearEasing),
        repeatMode = RepeatMode.Restart
    )
)

val brush = Brush.linearGradient( <--------
    colors = ...,
    start = Offset(xOffset, 0f),
    end = Offset(xOffset + widthPx, 0f)
)
I have a infinite transition animation thats needs to animate gradient. Is there a way to not allocate
Brush
instance every frame?
r
There isn't but you could cache them and reuse them if your animation repeats.
But first you should check it's an actual issue
u
I don't think it is an issue, its just my reflex to not allocate during animations it does repeat but how would I cache it though? is float a good cache key?
r
Float is not a good cache key, you'd have to round to ints. But again, I wouldn't bother in this case
One thing you can do too is use
ShaderBrush.transform
to apply a scale to your gradient instead
In your case you'd declare the gradient brush to be between 0 and 1 for instance, and apply a transform
Matrix
to translate it by
xOffset
and scale by
widthPx
This only works when you can apply a linear transform (so if you change the colors for instance, it won't help you)
u
interesting, will try! thanks