Klaas Kabini
03/07/2020, 7:32 AMBox(modifier = modifier + ImagePainter(image = image).toModifier(),
shape = CircleShape,
border = Border(borderWidth, borderColor))
Vinay Gaba
03/07/2020, 7:36 AMKlaas Kabini
03/07/2020, 7:59 AMval imageModifier = ImagePainter(image).toModifier(
scaleFit = ScaleFit.FillMaxDimension,
colorFilter = tintColor?.let { ColorFilter(it, BlendMode.srcIn) }
)
Box(modifier = modifier + ClipModifier + imageModifier,
shape = shape)
private object ClipModifier : DrawModifier {
override fun draw(density: Density, drawContent: () -> Unit, canvas: Canvas, size: PxSize) {
canvas.save()
val radius = Radius.circular((min(size.width, size.height)/2).value)
canvas.clipRRect(RRect(size.toRect(), radius))
drawContent()
canvas.restore()
}
}
@Composable
fun Image(modifier: Modifier = Modifier.None,
image: Image,
shape: Shape,
tintColor: Color? = null,
borderColor: Color = Color.Transparent,
borderWidth: Dp = 0.dp) {
val imageModifier = ImagePainter(image).toModifier(
scaleFit = ScaleFit.FillMaxDimension,
colorFilter = tintColor?.let { ColorFilter(it, BlendMode.srcIn) }
)
val clipModifier = when (shape) {
is RoundedCornerShape -> RoundedCornerClipModifier(shape.topLeft, shape.topRight, shape.bottomLeft, shape.bottomRight)
else -> RectangleClipModifier
}
Box(modifier = modifier + clipModifier + imageModifier,
shape = shape,
border = Border(borderWidth, borderColor))
}
private object RectangleClipModifier : DrawModifier {
override fun draw(density: Density, drawContent: () -> Unit, canvas: Canvas, size: PxSize) {
canvas.save()
canvas.clipRect(size.toRect())
drawContent()
canvas.restore()
}
}
private data class RoundedCornerClipModifier(val topLeftCornerSize: CornerSize,
val topRightCornerSize: CornerSize,
val bottomLeftCornerSize: CornerSize,
val bottomRightCornerSize:CornerSize) : DrawModifier {
override fun draw(density: Density, drawContent: () -> Unit, canvas: Canvas, size: PxSize) {
canvas.save()
val topLeft = topLeftCornerSize.toPx(size, density)
val topRight = topRightCornerSize.toPx(size, density)
val bottomLeft = bottomLeftCornerSize.toPx(size, density)
val bottomRight = bottomRightCornerSize.toPx(size, density)
canvas.clipRRect(RRect(rect = size.toRect(),
topLeft = topLeft.toRadius(),
topRight = topRight.toRadius(),
bottomLeft = bottomLeft.toRadius(),
bottomRight = bottomRight.toRadius()))
drawContent()
canvas.restore()
}
}
private fun Px.toRadius() = Radius.circular(this.value)
Vinay Gaba
03/07/2020, 6:29 PMKlaas Kabini
03/07/2020, 6:42 PMVinay Gaba
03/07/2020, 10:10 PMRoundedCornerClipModifier
but unfortunately it’s not clipping the image. I think your code looks correct though!FILL_WIDTH
if the box width is not specified.