Jetpack Compose 如何实现图片边缘深色中心透明的矩形渐变边框
Compose 矩形渐变边框实现方案
你需要的矩形等宽渐变边框无法直接通过系统自带的 border 修饰符实现,核心原因是 radialGradient 是基于中心点向外扩散的渐变,天然为圆形/椭圆形态,即使调整缩放比例也无法保证四个边的渐变宽度完全一致。
推荐采用自定义绘制的方案实现,完全规避渐变重叠问题,且支持圆角适配:
步骤1:自定义渐变边框扩展修饰符
fun Modifier.rectGradientBorder( // 渐变边框宽度 borderWidth: Dp, // 圆角半径,和图片裁剪圆角保持一致 cornerRadius: Dp, // 边框边缘颜色 edgeColor: Color, // 渐变靠近中心一侧的颜色,默认全透明 centerColor: Color = Color.Transparent ) = this.then( Modifier.drawWithContent { // 先绘制原始图片内容 drawContent() val borderPx = borderWidth.toPx() val cornerPx = cornerRadius.toPx() // 绘制顶部垂直渐变 drawRect( brush = Brush.verticalGradient( colors = listOf(edgeColor, centerColor), startY = 0f, endY = borderPx ), size = size.copy(height = borderPx) ) // 绘制底部垂直渐变 drawRect( brush = Brush.verticalGradient( colors = listOf(centerColor, edgeColor), startY = size.height - borderPx, endY = size.height ), top = size.height - borderPx ) // 绘制左侧水平渐变,排除上下已绘制区域避免重叠 drawRect( brush = Brush.horizontalGradient( colors = listOf(edgeColor, centerColor), startX = 0f, endX = borderPx ), top = borderPx, size = size.copy(width = borderPx, height = size.height - 2 * borderPx) ) // 绘制右侧水平渐变,排除上下已绘制区域避免重叠 drawRect( brush = Brush.horizontalGradient( colors = listOf(centerColor, edgeColor), startX = size.width - borderPx, endX = size.width ), top = borderPx, left = size.width - borderPx, size = size.copy(width = borderPx, height = size.height - 2 * borderPx) ) // 圆角适配:填充四个角的渐变过渡,不需要圆角可删除以下四段代码 // 左上角 drawCircle( brush = Brush.radialGradient( colors = listOf(edgeColor, centerColor), center = Offset(cornerPx, cornerPx), radius = cornerPx ), center = Offset(cornerPx, cornerPx), radius = cornerPx ) // 右上角 drawCircle( brush = Brush.radialGradient( colors = listOf(edgeColor, centerColor), center = Offset(size.width - cornerPx, cornerPx), radius = cornerPx ), center = Offset(size.width - cornerPx, cornerPx), radius = cornerPx ) // 左下角 drawCircle( brush = Brush.radialGradient( colors = listOf(edgeColor, centerColor), center = Offset(cornerPx, size.height - cornerPx), radius = cornerPx ), center = Offset(cornerPx, size.height - cornerPx), radius = cornerPx ) // 右下角 drawCircle( brush = Brush.radialGradient( colors = listOf(edgeColor, centerColor), center = Offset(size.width - cornerPx, size.height - cornerPx), radius = cornerPx ), center = Offset(size.width - cornerPx, size.height - cornerPx), radius = cornerPx ) } )
步骤2:替换原有逻辑使用自定义修饰符
Image( painter = ..., contentScale = ContentScale.Inside, modifier = Modifier .clip(RoundedCornerShape(48.dp)) // 调用自定义渐变边框修饰符 .rectGradientBorder( borderWidth = 24.dp, cornerRadius = 48.dp, edgeColor = MaterialTheme.colors.background ) .wrapContentHeight() .fillMaxWidth() )
补充说明
- 如果需要渐变边框绘制在图片外围而非覆盖在图片上方,只需在
clip修饰符前添加对应宽度的padding即可,例如padding(24.dp)。 - 不需要圆角效果时,直接删除扩展函数中四个角的
drawCircle绘制逻辑即可。
内容的提问来源于stack exchange,提问作者Qalterra
相关产品推荐
相关产品推荐

