Jetpack Compose:drawBehind绘制的RoundRect与Button背景高度不匹配求助
解决方案
问题原因
Button组件默认包含内部内容边距,其背景绘制区域由内部逻辑控制。你当前用drawBehind绘制的虚线框基于外层Modifier尺寸,和Button实际背景区域不匹配,导致高度对齐问题。
推荐方案:使用Button自带的border参数
直接利用Button的border属性设置虚线边框,无需额外drawBehind,这种方式能自动保证边框与Button背景的尺寸、圆角完全对齐,代码更简洁:
Button( modifier = Modifier .fillMaxWidth() .padding(horizontal = 32.dp, vertical = 16.dp), shape = RoundedCornerShape(25.dp), // 统一圆角大小 border = BorderStroke( width = 3.dp, color = Color.Blue, pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f) ), colors = ButtonDefaults.buttonColors( containerColor = Color.Yellow, contentColor = MaterialTheme.colorScheme.onSurfaceVariant ), onClick = { isErrorBank = isBankEmpty if (!isErrorBank) { saveButtonClicked = "gespeichert" onEvent(AccountEvent.SaveAccount) navHostController.popBackStack() } } )
备选方案:用Modifier控制背景与边框
如果坚持使用drawBehind,可以将Button的背景改为通过Modifier.background实现,确保背景和边框共享同一尺寸空间,同时调整边框绘制位置避免裁剪:
Button( modifier = Modifier .fillMaxWidth() .padding(horizontal = 32.dp, vertical = 16.dp) .background(Color.Yellow, shape = RoundedCornerShape(25.dp)) .drawBehind { val strokeWidth = 3f val halfStroke = strokeWidth / 2 // 向内偏移半线宽,防止边框被裁剪 drawRoundRect( color = Color.Blue, topLeft = Offset(halfStroke, halfStroke), size = Size(size.width - strokeWidth, size.height - strokeWidth), style = Stroke( width = strokeWidth, pathEffect = PathEffect.dashPathEffect(floatArrayOf(10f, 10f), 0f) ), cornerRadius = CornerRadius(25.dp.toPx()) ) }, colors = ButtonDefaults.buttonColors( containerColor = Color.Transparent, // 禁用Button自带背景 contentColor = MaterialTheme.colorScheme.onSurfaceVariant ), onClick = { isErrorBank = isBankEmpty if (!isErrorBank) { saveButtonClicked = "gespeichert" onEvent(AccountEvent.SaveAccount) navHostController.popBackStack() } } )
内容的提问来源于stack exchange,提问作者Erdem
相关产品推荐
相关产品推荐

