How to implement vertical likert scale with jetpack compose - android

I am attempting to create a vertical Likert scale using Jetpack Compose. Each field should include a vertical line that extends beyond its boundaries. I have also included an image to give an idea of what I am trying to achieve.

You can use a Box to put a Canvas on top of the row items.
Something like:
Box(Modifier.fillMaxWidth()){
//Just a simple for the row items
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(16.dp)
){
for (i in 1..5) {
RoundedIem()
}
}
//vertical Likert scale
Canvas(modifier = Modifier.fillMaxWidth()){
val height = 60.dp.toPx() //height of items
val verticalOffset = 76.dp.toPx() //height + vertical padding
val strokeWidthCircle =1f //stroke circle width
val radiusCircle = 30f //radius circle
for (i in 0..4) {
val circleCenterX = size.width-100f
val circleCenterY = height/2+ i*verticalOffset
//Inner white circle
drawCircle(
color = White,
radius = radiusCircle,
center = Offset(circleCenterX ,circleCenterY),
)
//Stroke circle
drawCircle(
color = DarkGray,
radius = radiusCircle,
center = Offset(circleCenterX, circleCenterY),
style = Stroke(width = strokeWidthCircle)
)
//vertical line
if (i < 4) {
val startY = circleCenterY + radiusCircle + strokeWidthCircle
drawLine(
color = DarkGray,
start = Offset(
x = circleCenterX,
y = startY),
end = Offset(
x = circleCenterX,
y = startY + verticalOffset - strokeWidthCircle),
strokeWidth = strokeWidthCircle
)
}
}
}
}
#Composable
fun RoundedIem(){
Row(
modifier= Modifier
.padding(horizontal = 16.dp)
.fillMaxWidth()
.height(60.dp)
.clip(RoundedCornerShape(8.dp))
.background(LightGray.copy(alpha = 0.5f))
.padding(start = 10.dp),
verticalAlignment = Alignment.CenterVertically,
){
Text("Option")
}
}
If you want to add also an icon in the circle you can draw the icon in the Canvas using:
//Icon
val painter = rememberVectorPainter(Icons.Default.Done)
Canvas(modifier = Modifier.fillMaxWidth()){
//previous code
val iconSize = 60f
//circle center - iconSize/2
translate(
left = circleCenterX - iconSize/2,
top = circleCenterY - iconSize/2
) {
with(painter) {
draw(
size = Size(iconSize,iconSize),//painter.intrinsicSize,
colorFilter = ColorFilter.tint(Color.Blue)
)
}
}
}
With a background:
drawCircle(
color = Blue,
radius = radiusCircle-8f,
center = Offset(circleCenterX,circleCenterY),
)
//circle center - iconSize/2
val iconSize = 48f
translate(
left = circleCenterX- iconSize/2,
top = circleCenterY -iconSize/2
) {
with(painter) {
draw(
size = Size(iconSize,iconSize),//painter.intrinsicSize,
colorFilter = ColorFilter.tint(Color.White)
)
}
}

Related

Add a border for top half of a card in compose with corner radius

I want to add a border to the top half of the Card component that has a corner radius (10dp).
So, only the bottom part is missing rest of the card has a stroke of 1dp. (kind of like U and inverted U)
And I want to do the same for card that has a bottom corner radius and the top part is missing.
I tried to design a custom shape but it's not respecting the shape of the card.
// this is just a line but it doesn't respect the card corner radius?
private fun createShape(thickness: Float) : Shape {
return GenericShape { size, _ ->
moveTo(0f,0f)
lineTo(0f, size.height)
lineTo(thickness, size.height)
lineTo(thickness, 0f)
lineTo(0f, thickness)
}
}
val thickness = with(LocalDensity.current) {
1.dp.toPx()
}
Card(
shape = RoundedCornerShape(topEnd = 10.dp, topStart = 10.dp, bottomEnd = 0.dp, bottomStart = 0.dp),
modifier = Modifier
.border(BorderStroke(width = 1.dp, color = Color.Black), createShape(thickness))
) {
...
}
Border doesn't seem to allow open shapes, forces shape to be closed even if you draw 3 lines because of that you need to use Modifier.drawBehind or Modifier.drawWithContent.
Created a Modifier that draws u shaped border as
fun Modifier.semiBorder(strokeWidth: Dp, color: Color, cornerRadiusDp: Dp) = composed(
factory = {
val density = LocalDensity.current
val strokeWidthPx = density.run { strokeWidth.toPx() }
val cornerRadius = density.run { cornerRadiusDp.toPx() }
Modifier.drawBehind {
val width = size.width
val height = size.height
drawLine(
color = color,
start = Offset(x = 0f, y = height),
end = Offset(x = 0f, y = cornerRadius),
strokeWidth = strokeWidthPx
)
// Top left arc
drawArc(
color = color,
startAngle = 180f,
sweepAngle = 90f,
useCenter = false,
topLeft = Offset.Zero,
size = Size(cornerRadius * 2, cornerRadius * 2),
style = Stroke(width = strokeWidthPx)
)
drawLine(
color = color,
start = Offset(x = cornerRadius, y = 0f),
end = Offset(x = width - cornerRadius, y = 0f),
strokeWidth = strokeWidthPx
)
// Top right arc
drawArc(
color = color,
startAngle = 270f,
sweepAngle = 90f,
useCenter = false,
topLeft = Offset(x = width - cornerRadius * 2, y = 0f),
size = Size(cornerRadius * 2, cornerRadius * 2),
style = Stroke(width = strokeWidthPx)
)
drawLine(
color = color,
start = Offset(x = width, y = height),
end = Offset(x = width, y = cornerRadius),
strokeWidth = strokeWidthPx
)
}
}
)
Usage
#Composable
private fun UShapeBorderSample() {
Card(
shape = RoundedCornerShape(
topEnd = 10.dp,
topStart = 10.dp,
bottomEnd = 0.dp,
bottomStart = 0.dp
),
modifier = Modifier
.semiBorder(1.dp, Color.Black, 10.dp)
) {
Box(
modifier = Modifier
.size(150.dp)
.background(Color.White),
contentAlignment = Alignment.Center
) {
Text("Hello World")
}
}
Spacer(modifier = Modifier.height(10.dp))
Card(
shape = RoundedCornerShape(
topEnd = 20.dp,
topStart = 20.dp,
bottomEnd = 0.dp,
bottomStart = 0.dp
),
modifier = Modifier
.semiBorder(1.dp, Color.Black, 20.dp)
) {
Box(
modifier = Modifier
.size(150.dp)
.background(Color.White),
contentAlignment = Alignment.Center
) {
Text("Hello World")
}
}
}
You need to use arc to create rounded corners. And when creating shape you don't pass thickness but radius of shape. Thickness is required when drawing border. What you draw is a rectangle with 1.dp width.
#Composable
private fun createShape(cornerRadius: Dp): Shape {
val density = LocalDensity.current
return GenericShape { size, _ ->
val width = size.width
val height = size.height
val cornerRadiusPx = density.run { cornerRadius.toPx() }
moveTo(0f, height)
// Vertical line on left size
lineTo(0f, cornerRadiusPx * 2)
arcTo(
rect = Rect(
offset = Offset.Zero,
size = Size(cornerRadiusPx * 2, cornerRadiusPx * 2)
),
startAngleDegrees = 180f,
sweepAngleDegrees = 90f,
forceMoveTo = false
)
lineTo(width - cornerRadiusPx * 2, 0f)
arcTo(
rect = Rect(
offset = Offset(width - cornerRadiusPx * 2, 0f),
size = Size(cornerRadiusPx * 2, cornerRadiusPx * 2)
),
startAngleDegrees = 270f,
sweepAngleDegrees = 90f,
forceMoveTo = false
)
// Vertical line on right size
lineTo(width, height)
}
}
Usage
#Composable
private fun UShapeBorderSample() {
Card(
shape = RoundedCornerShape(
topEnd = 10.dp,
topStart = 10.dp,
bottomEnd = 0.dp,
bottomStart = 0.dp
),
modifier = Modifier
.border(BorderStroke(width = 1.dp, color = Color.Black), createShape(10.dp))
) {
Box(modifier = Modifier
.size(200.dp)
.background(Color.White),
contentAlignment = Alignment.Center
) {
Text("Hello World")
}
}
}
Border doesn't respect shape because it's a drawing but Card is a Box under the hood that uses shape with Modifier.clip() which itself is Modifier.graphicsLayer{clip} that applies operations on a layer.
You can check out this answer about clip and border for the difference.
https://stackoverflow.com/a/73091667/5457853

Jetpack Compose - CardView with Arc Shape on border

I'm trying to achieve below cardview arc shape on cardview border/stroke.
Already tried to search on google but didn't find any relevant answer that suits with requirement.
Any lead or help will be appriciated.
Answer from Cirilo Bido and Raghunandan is good place to start, you round corners of rectangle with arcTo but you can't draw curved edges on top of clipped out shape. You need to use cubicTo to draw rounded edge and curve to clip out bottom shape
val shape = GenericShape {size: Size, layoutDirection: LayoutDirection ->
// draw cubic on left and right sides for button space
cubicTo()
}
You can check out this answer for drawing with cubic to. By combining both you can draw that path.
Jetpack Compose: How to draw a path / line like this
I created this path based on article shared by
Raghunandan initially, even though that is amazing answer for animating BottomBar it doesn't create a rounded shape if you look closely, at the bottom it's creating a triangular shape at the bottom instead of rounded one and shape OP requires and in article is also different.
So i used sliders to create bezier from the link i shared above. It's available as tutorial here too. Still it can be tweaked to more precise shape if you wish to.
I used x0, y0 as reference point to set control points and created this Path extension function.
fun Path.roundedRectanglePath(
size: Size,
cornerRadius: Float,
fabRadius: Float,
) {
val centerX = size.width / 2
val x0 = centerX - fabRadius * 1.15f
val y0 = 0f
// offset of the first control point (top part)
val topControlX = x0 + fabRadius * .5f
val topControlY = y0
// offset of the second control point (bottom part)
val bottomControlX = x0
val bottomControlY = y0 + fabRadius
// first curve
// set the starting point of the curve (P2)
val firstCurveStart = Offset(x0, y0)
// set the end point for the first curve (P3)
val firstCurveEnd = Offset(centerX, fabRadius * 1f)
// set the first control point (C1)
val firstCurveControlPoint1 = Offset(
x = topControlX,
y = topControlY
)
// set the second control point (C2)
val firstCurveControlPoint2 = Offset(
x = bottomControlX,
y = bottomControlY
)
// second curve
// end of first curve and start of second curve is the same (P3)
val secondCurveStart = Offset(
x = firstCurveEnd.x,
y = firstCurveEnd.y
)
// end of the second curve (P4)
val secondCurveEnd = Offset(
x = centerX + fabRadius * 1.15f,
y = 0f
)
// set the first control point of second curve (C4)
val secondCurveControlPoint1 = Offset(
x = secondCurveStart.x + fabRadius,
y = bottomControlY
)
// set the second control point (C3)
val secondCurveControlPoint2 = Offset(
x = secondCurveEnd.x - fabRadius / 2,
y = topControlY
)
// Top left arc
val radius = cornerRadius * 2
arcTo(
rect = Rect(
left = 0f,
top = 0f,
right = radius,
bottom = radius
),
startAngleDegrees = 180.0f,
sweepAngleDegrees = 90.0f,
forceMoveTo = false
)
lineTo(x = firstCurveStart.x, y = firstCurveStart.y)
// bezier curve with (P2, C1, C2, P3)
cubicTo(
x1 = firstCurveControlPoint1.x,
y1 = firstCurveControlPoint1.y,
x2 = firstCurveControlPoint2.x,
y2 = firstCurveControlPoint2.y,
x3 = firstCurveEnd.x,
y3 = firstCurveEnd.y
)
// bezier curve with (P3, C4, C3, P4)
cubicTo(
x1 = secondCurveControlPoint1.x,
y1 = secondCurveControlPoint1.y,
x2 = secondCurveControlPoint2.x,
y2 = secondCurveControlPoint2.y,
x3 = secondCurveEnd.x,
y3 = secondCurveEnd.y
)
lineTo(x = size.width - cornerRadius, y = 0f)
// Top right arc
arcTo(
rect = Rect(
left = size.width - radius,
top = 0f,
right = size.width,
bottom = radius
),
startAngleDegrees = -90.0f,
sweepAngleDegrees = 90.0f,
forceMoveTo = false
)
lineTo(x = 0f + size.width, y = size.height - cornerRadius)
// Bottom right arc
arcTo(
rect = Rect(
left = size.width - radius,
top = size.height - radius,
right = size.width,
bottom = size.height
),
startAngleDegrees = 0f,
sweepAngleDegrees = 90.0f,
forceMoveTo = false
)
lineTo(x = cornerRadius, y = size.height)
// Bottom left arc
arcTo(
rect = Rect(
left = 0f,
top = size.height - radius,
right = radius,
bottom = size.height
),
startAngleDegrees = 90.0f,
sweepAngleDegrees = 90.0f,
forceMoveTo = false
)
lineTo(x = 0f, y = cornerRadius)
close()
}
Composable that uses this shape
#Composable
private fun CustomArcShape(
modifier: Modifier,
elevation: Dp = 4.dp,
color: Color = MaterialTheme.colorScheme.surface,
contentColor: Color = contentColorFor(color),
content: #Composable () -> Unit
) {
val diameter = 60.dp
val radiusDp = diameter / 2
val cornerRadiusDp = 10.dp
val density = LocalDensity.current
val cutoutRadius = density.run { radiusDp.toPx() }
val cornerRadius = density.run { cornerRadiusDp.toPx() }
val shape = remember {
GenericShape { size: Size, layoutDirection: LayoutDirection ->
this.roundedRectanglePath(
size = size,
cornerRadius = cornerRadius,
fabRadius = cutoutRadius * 2
)
}
}
Spacer(modifier = Modifier.height(diameter / 2))
Box(contentAlignment = Alignment.TopCenter) {
FloatingActionButton(
shape = CircleShape,
containerColor = Color(0xffD32F2F),
modifier = Modifier
.offset(y = -diameter / 5)
.size(diameter)
.drawBehind {
drawCircle(
Color.Red.copy(.5f),
radius = 1.3f * size.width / 2
)
drawCircle(
Color.Red.copy(.3f),
radius = 1.5f * size.width / 2
)
}
.align(Alignment.TopCenter),
onClick = { /*TODO*/ }
) {
Icon(
tint = Color.White,
imageVector = Icons.Filled.Close,
contentDescription = "Close"
)
}
Surface(
modifier = modifier,
shape = shape,
shadowElevation = elevation,
color = color,
contentColor = contentColor
) {
Column {
Spacer(modifier = Modifier.height(diameter))
content()
}
}
}
}
And demonstration
#Composable
private fun CustomArcShapeSample() {
Column(
modifier = Modifier
.fillMaxSize()
) {
CustomArcShape(
modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
.height(250.dp)
) {
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
"Payment Failed",
color = MaterialTheme.colorScheme.error,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(10.dp))
Text("Sorry !", fontSize = 24.sp, fontWeight = FontWeight.Bold)
Spacer(modifier = Modifier.height(10.dp))
Text("Your transfer to bank failed", color = Color.LightGray)
}
}
Spacer(modifier = Modifier.height(40.dp))
CustomArcShape(
modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
.height(250.dp)
) {
Column(
modifier = Modifier
.fillMaxSize()
.border(1.dp, Color.Green),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
"Payment Failed",
color = MaterialTheme.colorScheme.error,
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.height(10.dp))
Text("Sorry !", fontSize = 24.sp, fontWeight = FontWeight.Bold)
Spacer(modifier = Modifier.height(10.dp))
Text("Your transfer to bank failed", color = Color.LightGray)
}
}
}
}
You probably need to draw that arc in a custom composable, I found this article that can help you to understand the process of drawing in compose!
turtorial article: https://github.com/JeckOnly/passage/blob/master/Android/Widget/Compose/%E9%A1%B6%E9%83%A8%E5%87%B9%E9%99%B7Shape.md
code:https://gist.github.com/JeckOnly/54936415d1670103a4d400f66c8b31a1
hope this can help you though it is in Chinese language.

Jetpack Compose inner shadow

How to create an inner shadow with Jetpack Compose? The gradient should run from black on the outside to transparent on the inside. Modifier.shadow() is just for outer shadows. Using negative elevation is not working.
fun Modifier.innerShadow(
color: Color = Color.Black,
cornersRadius: Dp = 0.dp,
spread: Dp = 0.dp,
blur: Dp = 0.dp,
offsetY: Dp = 0.dp,
offsetX: Dp = 0.dp
) = drawWithContent {
drawContent()
val rect = Rect(Offset.Zero, size)
val paint = Paint()
drawIntoCanvas {
paint.color = color
paint.isAntiAlias = true
it.saveLayer(rect, paint)
it.drawRoundRect(
left = rect.left,
top = rect.top,
right = rect.right,
bottom = rect.bottom,
cornersRadius.toPx(),
cornersRadius.toPx(),
paint
)
val frameworkPaint = paint.asFrameworkPaint()
frameworkPaint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT)
if (blur.toPx() > 0) {
frameworkPaint.maskFilter = BlurMaskFilter(blur.toPx(), BlurMaskFilter.Blur.NORMAL)
}
val left = if (offsetX > 0.dp) {
rect.left + offsetX.toPx()
} else {
rect.left
}
val top = if (offsetY > 0.dp) {
rect.top + offsetY.toPx()
} else {
rect.top
}
val right = if (offsetX < 0.dp) {
rect.right + offsetX.toPx()
} else {
rect.right
}
val bottom = if (offsetY < 0.dp) {
rect.bottom + offsetY.toPx()
} else {
rect.bottom
}
paint.color = Color.Black
it.drawRoundRect(
left = left + spread.toPx() / 2,
top = top + spread.toPx() / 2,
right = right - spread.toPx() / 2,
bottom = bottom - spread.toPx() / 2,
cornersRadius.toPx(),
cornersRadius.toPx(),
paint
)
frameworkPaint.xfermode = null
frameworkPaint.maskFilter = null
}
}
Usage:
Box(
modifier = Modifier
.width(240.dp)
.height(180.dp)
.outerShadow(
color = Color(0xff000000),
alpha = 0.5f,
cornersRadius = 20.dp,
shadowBlurRadius = 30.dp,
offsetX = 0.dp,
offsetY = 15.dp
)
.clip(RoundedCornerShape(20.dp))
.background(Color(0xFF282A2F))
.innerShadow(
blur = 1.dp,
color = Color(0xff00FFFF),
cornersRadius = 20.dp,
offsetX = (-40.5).dp,
offsetY = (-10.5).dp
)
.innerShadow(
blur = 20.dp,
color = Color(0xffff0000),
cornersRadius = 20.dp,
offsetX = 0.5.dp,
offsetY = 0.5.dp
)
.padding(14.dp),
contentAlignment = Alignment.Center
) {
Text(
text = stringResource(id = R.string.notification_service),
modifier = Modifier,
color = Color.White
)
}
I hope it helps.
outerShadow is custom modifier too, copied from other websites.
Position of Modifier.shadow relative to Modifier.background places shadow inside your component. Also you can create Modifier.drawWithContent and frameworkPaint a show with blur.
Column(
modifier = Modifier
.fillMaxSize()
.padding(20.dp)
) {
ComponentWithInnerShadow()
Spacer(modifier = Modifier.height(12.dp))
ComponentWithOuterShadow()
Spacer(modifier = Modifier.height(12.dp))
ComponentWithCustomInnerShadow()
}
#Composable private fun ComponentWithInnerShadow() {
Column(
modifier = Modifier
.clip(RoundedCornerShape(5.dp))
.background(Color.Yellow)
.shadow(2.dp, shape = RoundedCornerShape(5.dp))
) {
Text(text = "Hello World", modifier = Modifier.padding(12.dp))
} }
#Composable
private fun ComponentWithOuterShadow() {
Column(
modifier = Modifier
.shadow(2.dp, shape = RoundedCornerShape(5.dp))
.background(Color.Yellow)
) {
Text(text = "Hello World", modifier = Modifier.padding(12.dp))
}
}
#Composable
private fun ComponentWithCustomInnerShadow() {
Column(
modifier = Modifier.innerShadow()
) {
Text(text = "Hello World", modifier = Modifier.padding(12.dp))
}
}
And with composed modifier. I didn't set parameters just set arbitrary numbers you can set your own parameters, and set color if you want to. This one looks better than standard inner shadow though. You need to provide color for foreground and shape with this one either. I set color and drew Rounded rectangle for demonstration
fun Modifier.innerShadow() = composed(
inspectorInfo = {
},
factory = {
val paint = remember() {
Paint()
}
val foregroundPaint = remember() {
Paint().apply {
color = Color.Yellow
}
}
val frameworkPaint = remember {
paint.asFrameworkPaint()
}
Modifier.drawWithContent {
this.drawIntoCanvas {
val color = Color.LightGray
val radius = 2.dp.toPx()
val shadowColor = color
.copy(alpha = .7f)
.toArgb()
val transparent = color
.copy(alpha = 0f)
.toArgb()
frameworkPaint.color = transparent
frameworkPaint.setShadowLayer(
radius,
0f,
0f,
shadowColor
)
val shadowRadius = 4.dp.toPx()
it.drawRoundRect(
left = 0f,
top = 0f,
right = this.size.width,
bottom = this.size.height,
radiusX = 5.dp.toPx(),
radiusY = 5.dp.toPx(),
paint = foregroundPaint
)
it.drawRoundRect(
left = 0f,
top = 0f,
right = this.size.width,
bottom = this.size.height,
radiusX = 5.dp.toPx(),
radiusY = 5.dp.toPx(),
paint = paint
)
it.drawRoundRect(
left = shadowRadius,
top = shadowRadius,
right = this.size.width - shadowRadius,
bottom = this.size.height - shadowRadius,
radiusX = 5.dp.toPx(),
radiusY = 5.dp.toPx(),
paint = foregroundPaint
)
drawContent()
}
}
}
)
This is not supported but you have alternative options:
Use a border modifier with a gradient brush
Use Android Canvas
Use a gradient and Modifier.drawBehind to draw the inset shadow underneath the content
Source

How to draw circle shape border stroke drawn with separated lines?

I'm trying to achieve this custom shape with Compose
But for some reason the separator offseted circle is drawn with a dotted line and here is the code
#Preview
#Composable
private fun ReceiptSeparator () {
Row(modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp) ,
verticalAlignment = Alignment.CenterVertically ,) {
Box(
modifier = Modifier
.requiredSize(50.dp)
.background(Color.White)
.offset(-40.dp)
.clip(CircleShape)
.border(BorderStroke(2.dp, Color.Gray))
){}
Box(
Modifier
.height(1.dp)
.requiredWidth(250.dp)
.weight(3f)
.background(Color.Gray, shape = DottedShape(step = 20.dp))
){}
Box(
modifier = Modifier
.offset(40.dp)
.clip(CircleShape)
.border(BorderStroke(2.dp, Color.Gray))
.background(Color.White)
.size(50.dp)
){}
}
}
Why the circle is drawn with a dotted line and how to achieve this shape correctly?
Your circle is not drawn correctly, because Modifier.border draws a rectangle border by default, and then you clip it with your Modifier.clip. Instead, if you need to apply shape to the border, you need to pass the shape into Modifier.border, like this:
.border(BorderStroke(2.dp, Color.Gray), shape = CircleShape)
But this won't solve your problem. To draw the shadow correctly like shown in your image, you need to apply a custom Shape to your container.
You can use Modifier.onGloballyPositioned to get position of your cutoffs:
var separatorOffsetY by remember { mutableStateOf<Float?>(null) }
val cornerRadius = 20.dp
Card(
shape = RoundedCutoutShape(separatorOffsetY, cornerRadius),
backgroundColor = Color.White,
modifier = Modifier.padding(10.dp)
) {
Column {
Box(modifier = Modifier.height(200.dp))
Box(
Modifier
.padding(horizontal = cornerRadius)
.height(1.dp)
.requiredWidth(250.dp)
// DottedShape is taken from this answer:
// https://stackoverflow.com/a/68789205/3585796
.background(Color.Gray, shape = DottedShape(step = 20.dp))
.onGloballyPositioned {
separatorOffsetY = it.boundsInParent().center.y
}
)
Box(modifier = Modifier.height(50.dp))
}
}
Using this information you can create a shape like following:
class RoundedCutoutShape(
private val offsetY: Float?,
private val cornerRadiusDp: Dp,
) : Shape {
override fun createOutline(
size: Size,
layoutDirection: LayoutDirection,
density: Density,
) = Outline.Generic(run path#{
val cornerRadius = with(density) { cornerRadiusDp.toPx() }
val rect = Rect(Offset.Zero, size)
val mainPath = Path().apply {
addRoundRect(RoundRect(rect, CornerRadius(cornerRadius)))
}
if (offsetY == null) return#path mainPath
val cutoutPath = Path().apply {
val circleSize = Size(cornerRadius, cornerRadius) * 2f
val visiblePart = 0.25f
val leftOval = Rect(
offset = Offset(
x = 0 - circleSize.width * (1 - visiblePart),
y = offsetY - circleSize.height / 2
),
size = circleSize
)
val rightOval = Rect(
offset = Offset(
x = rect.width - circleSize.width * visiblePart,
y = offsetY - circleSize.height / 2
),
size = circleSize
)
addOval(leftOval)
addOval(rightOval)
}
return#path Path().apply {
op(mainPath, cutoutPath, PathOperation.Difference)
}
})
}
Result:
Get rid of:
shape = DottedShape(step = 20.dp)

how to add border on bottom only in jetpack compose

I want to add border on bottom of the layout. I know i can use Divider composable but i just want to learn how to draw a border.
Currently, I can add border for all sides which is not what I want.
Row(
modifier = Modifier
.border(border = BorderStroke(width = 1.dp, Color.LightGray))
) {
TextField(value = "", onValueChange = {}, modifier = Modifier.weight(1f))
Switch(checked = true, onCheckedChange = {})
Icon(Icons.Filled.Close, "Remove", tint = Color.Gray)
}
You can use the drawBehind modifier to draw a line.
Something like:
Row(
modifier = Modifier
.drawBehind {
val strokeWidth = indicatorWidth.value * density
val y = size.height - strokeWidth / 2
drawLine(
Color.LightGray,
Offset(0f, y),
Offset(size.width, y),
strokeWidth
)
}){
//....
}
If you prefer you can build your custom Modifier with the same code above
fun Modifier.bottomBorder(strokeWidth: Dp, color: Color) = composed(
factory = {
val density = LocalDensity.current
val strokeWidthPx = density.run { strokeWidth.toPx() }
Modifier.drawBehind {
val width = size.width
val height = size.height - strokeWidthPx/2
drawLine(
color = color,
start = Offset(x = 0f, y = height),
end = Offset(x = width , y = height),
strokeWidth = strokeWidthPx
)
}
}
)
and then just apply it:
Row(
modifier = Modifier
.padding(horizontal = 8.dp)
.fillMaxWidth()
.bottomBorder(1.dp, DarkGray)
){
//Row content
}
You can draw a line in a draw scope. In my opinion, a divider looks cleaner in code.
Row(modifier = Modifier
.drawWithContent {
drawContent()
clipRect { // Not needed if you do not care about painting half stroke outside
val strokeWidth = Stroke.DefaultMiter
val y = size.height // - strokeWidth
// if the whole line should be inside component
drawLine(
brush = SolidColor(Color.Red),
strokeWidth = strokeWidth,
cap = StrokeCap.Square,
start = Offset.Zero.copy(y = y),
end = Offset(x = size.width, y = y)
)
}
}
) {
Text("test")
}
Yeah this oughta do it:-
#Suppress("UnnecessaryComposedModifier")
fun Modifier.topRectBorder(width: Dp = Dp.Hairline, brush: Brush = SolidColor(Color.Black)): Modifier = composed(
factory = {
this.then(
Modifier.drawWithCache {
onDrawWithContent {
drawContent()
drawLine(brush, Offset(width.value, 0f), Offset(size.width - width.value, 0f))
}
}
)
},
inspectorInfo = debugInspectorInfo {
name = "border"
properties["width"] = width
if (brush is SolidColor) {
properties["color"] = brush.value
value = brush.value
} else {
properties["brush"] = brush
}
properties["shape"] = RectangleShape
}
)
You can define a rectangular Shape on the bottom of your element, using the bottom line thickness as parameter:
private fun getBottomLineShape(bottomLineThickness: Float) : Shape {
return GenericShape { size, _ ->
// 1) Bottom-left corner
moveTo(0f, size.height)
// 2) Bottom-right corner
lineTo(size.width, size.height)
// 3) Top-right corner
lineTo(size.width, size.height - bottomLineThickness)
// 4) Top-left corner
lineTo(0f, size.height - bottomLineThickness)
}
}
And then use it in the border modifier like this:
val lineThickness = with(LocalDensity.current) {[desired_thickness_in_dp].toPx()}
Row(
modifier = Modifier
.height(rowHeight)
.border(width = lineThickness,
color = Color.Black,
shape = getBottomLineShape(lineThickness))
) {
// Stuff in the row
}
Using a "Divider" worked for me,
Column {
Divider (
color = Color.White,
modifier = Modifier
.height(1.dp)
.fillMaxHeight()
.fillMaxWidth()
)
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
) {
// Something else
}
}

Categories

Resources