I want to draw a little gradient on one of my comp...
# compose
s
I want to draw a little gradient on one of my components, but I specifically want to draw it just outside of the current bounds of my composable, a bit to the right. I am having trouble getting anything to be drawn outside of my bounds when using
drawWithContent
. Am I typically not allowed to draw outside of my canvas' bounds perhaps? More details in thread 🧵
When I try to do this
Copy code
.drawWithContent {
  drawContent()
  drawRect(
    brush = Brush.horizontalGradient(
      colors = listOf(someColor, someOtherColor),
      startX = size.width,
      endX = size.width + 4.dp.toPx(), // I tried just `4.dp.toPx(),` too but that's not it either.
    ),
  )
}
It seems to sort of "overflow" and just draws the first color over the entire item instead, never painting with any of the
someOtherColor
.
Nvm I am just being silly. Actually using the
topLeft
parameter on the
drawRect
function fixes this. So do instead
Copy code
drawRect(
  topLeft = Offset(size.width, 0f),
  size = Size(4.dp.toPx(), size.height),
  brush = SolidColor(Color.Red),
)
r
Compose doesn't do clipping by default
But it can happen in scroll containers or if there's an offscreen graphics layer (or an explicit clip modifier of course)
s
Yeap, it was not clipping in my scenario at all. It was just be making a mistake there! Final code looks like this and works just fine rendering outside of the parent composable's content
Copy code
val mySizeInPx = ...
val myColor = ...
drawRect(
  topLeft = Offset(size.width, 0f),
  size = Size(mySizeInPx, size.height),
  brush = Brush.horizontalGradient(
    colors = listOf(myColor, Color.Transparent),
    startX = size.width,
    endX = size.width + mySizeInPx,
  ),
)
What I was doing originally was that the size parameters defaulted to the content's size, so I was constraining my drawing of my rect to the incoming
size
due to those. Since I was passing nothing to
topLeft
and to
size
And then on my brush I was giving it an endX which was outside of those bounds. No wonder it was acting not even close to what I wanted it to do 😅
😅 2