I am trying to create a custom view in Android that has a linear gradient border with rounded corners, similar to the one shown in this image:
[![enter image description here][1]][1]
[1]: https://i.sstatic.net/z1jKI6O5.png
I've written the following custom view class in Kotlin, but I am having trouble getting the gradient border to appear correctly. Here is the code I am using:
class GradientBorderView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
enter code here
private val borderPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeWidth = 8f // Adjust the border thickness as needed
}
private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL
color = Color.TRANSPARENT // Set background to transparent
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val rect = RectF(
borderPaint.strokeWidth / 2,
borderPaint.strokeWidth / 2,
width - borderPaint.strokeWidth / 2,
height - borderPaint.strokeWidth / 2
)
// Draw the background with rounded corners
canvas.drawRoundRect(rect, 20f, 20f, backgroundPaint)
// Create a path for the gradient border
val path = Path().apply {
addRoundRect(rect, 20f, 20f, Path.Direction.CW)
}
// Set the shader with the linear gradient for the border
val gradient = LinearGradient(
0f, 0f, width.toFloat(), 0f,
intArrayOf(
Color.TRANSPARENT,
Color.TRANSPARENT,
Color.parseColor("#56A1C8"),
Color.parseColor("#3A4877"),
Color.parseColor("#E49460"),
Color.parseColor("#56A1C8")
),
floatArrayOf(0f, 0.25f, 0.5f, 0.75f, 0.9f, 1f),
Shader.TileMode.CLAMP
)
borderPaint.shader = gradient
// Draw the border with rounded corners
canvas.drawPath(path, borderPaint)
}
}
**I am using this custom view in my XML layout as follows:**
<production.zofeur.customer.app.utils.GradientBorderView
android:layout_width="match_parent"
android:layout_height="@dimen/_90sdp" />
<!-- Add more views as needed -->
What I Have Tried
Adjusting the RectF dimensions.
Tweaking the LinearGradient colors and positions.
Ensuring the strokeWidth is set properly
Problem
Despite my efforts, the gradient border does not appear as expected. The gradient does not seem to blend smoothly, and the colors do not transition as they should.
Request
Could someone help me understand what I am doing wrong and how I can achieve a smooth linear gradient border with rounded corners as shown in the image? Any suggestions or corrections to my code would be greatly appreciated!