Is there a way to add a gradient to the `colorFilt...
# compose
d
Is there a way to add a gradient to the
colorFilter
of an
Image
composable? Best way I could find online was to use the
drawWithCache { }
modifier and call
drawRect
, but that doesn’t work the way I want to 😕 It creates a rect behind the image, not in the image. I’ve tried all the blend modes available and none worked. Am I missing something here?
r
You need to create a graphicsLayer with an offscreen composition strategy
And use drawWithContent to draw the content then your rectangle
Using SrcIn as the blend mode
Alternatively you could do it without the graphics layer but you must make sure your image is loaded as ALPHA_8 and you'd have then to use the native graphics objects to set your gradient on the paint
d
Damn, a bit more complex than I thought. Alright, cool! Thank you, I’ll try this 😄
Nice, the following modifiers worked like a charm:
Copy code
.graphicsLayer { alpha = 0.99F }
.drawWithContent {
    drawContent()
    drawRect(
        brush = Brush.horizontalGradient(
            0.3f to LightGrey,
            1F to Color.Transparent,
        ),
        blendMode = BlendMode.SrcIn,
    )
}
Thanks once again!
r
Yep that’s exactly it
not with Compose 1.4 you don’t need the alpha=0.99f trick
you can set the composition strategy instead
if you must set alpha, use 254.0f/255.0f instead
d
oh alright, now I understood what you said in your first reply. I didn’t know about this
compositeStrategy
parameter, I changed the alpha to this:
Copy code
.graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen }
Works too, thanks!
r
Yay!
d
Woah
307 Views