Abstract

Drawable XML is one of the most complex XML drawable in UI development. Different views have the same background style, but because of some design differences, you have to write a new set of XML drawable. Write or not write? The more you write, the more redundant code you have, because you changed the height a little bit?

Set the Stroke gradient in the code

  • The actual effect is as follows

Code implementation

class StrokeGradientLRDrawable(colors: IntArray, radius: Float, strokeWidth: Float) : ShapeDrawable() {init {val outerR = floatArrayOf(radius, radius, radius, radius, radius, radius, radius, Val inset = RectF(strokeWidth, strokeWidth, strokeWidth, StrokeWidth val innerRadii = radius-strokeWidth val innerRadii = floatArrayOf(innerRadius, innerRadius, innerRadius, innerRadius, innerRadius, innerRadius, innerRadius, innerRadius) val rr = RoundRectShape(outerR, inset, innerRadii) shape = rr shaderFactory = object : ShaderFactory() { override fun resize(width: Int, height: Int): Shader { return LinearGradient(0f, 0f, width.toFloat(), 0f, colors, null, Shader.TileMode.CLAMP) } } } }Copy the code

Drawable is very simple, three arguments.

Gradient color array; Fillet radius; Line width of Stroke

How to use
  • To achieve the effect shown in Figure 1, where the radius is exactly half the height, just set radius to a larger value. Just give me a thousand
view.background = StrokeGradientLRDrawable(intArrayOf(Color.RED, Color.BLUE), 1000f, 5f)
Copy the code
  • Normal rounded corners just set the value
view.background = StrokeGradientLRDrawable(intArrayOf(Color.RED, Color.BLUE), 50f, 5f)
Copy the code