自定义圆角矩形渐变背景边框

概述

自定义一个layout实现背景的渐变以及边框的渐变,同时半圆角。效果图如下:

image

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.widget.LinearLayout

class GradientBackgroundView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
private val mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
private var mPath = Path()
private var backGradient: LinearGradient? = null
private var strokeGradient: LinearGradient? = null
private val radiusArray = floatArrayOf(0f, 0f, 0f, 0f, 0f, 0f, 0f, 0f)

init {
//设置抗锯齿
mPaint.isAntiAlias = true
//设置防抖动
mPaint.isDither = true
mPaint.style = Paint.Style.FILL
}
/**
* 设置四个角的圆角半径
*/
fun setRadius(leftTop: Float, rightTop: Float, rightBottom: Float, leftBottom: Float) {
radiusArray[0] = leftTop
radiusArray[1] = leftTop
radiusArray[2] = rightTop
radiusArray[3] = rightTop
radiusArray[4] = rightBottom
radiusArray[5] = rightBottom
radiusArray[6] = leftBottom
radiusArray[7] = leftBottom
}

fun setGradient(backGradientColors: IntArray?, strokeGradientcolors: IntArray?) {
backGradient = LinearGradient(0f, 0f, width.toFloat(), 0f, backGradientColors, null, Shader.TileMode.CLAMP)
strokeGradient = LinearGradient(0f, 0f, width.toFloat(), 0f, strokeGradientcolors, null, Shader.TileMode.CLAMP)
}

fun showBackgroundColor() {
setBackgroundColor(Color.TRANSPARENT)
}

override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (canvas == null) {
return
}
canvas.save()
//渐变边框
mPaint.shader = strokeGradient
mPaint.style = Paint.Style.STROKE
mPaint.strokeWidth = 4f
mPath = Path()
mPath.addRoundRect(RectF(0f, 0f, width.toFloat(), height.toFloat()), radiusArray, Path.Direction.CW)
canvas.clipPath(mPath)
canvas.drawPath(mPath, mPaint)

//渐变背景色
mPaint.shader = backGradient
mPaint.style = Paint.Style.FILL
mPath = Path()
mPath.addRoundRect(RectF(2f, 2f, (width - 2).toFloat(), (height - 2).toFloat()), radiusArray, Path.Direction.CW)
canvas.clipPath(mPath)
canvas.drawPath(mPath, mPaint)
canvas.restore()
}
}
1
2
3
mBarrageLayout.setRadius(mRadius,0,0,mRadius);
mBarrageLayout.setGradient(new int[]{0xffff53a3,0xfd316a},new int[]{0xffFFC92B,0x979797});
mBarrageLayout.showBackgroundColor();

参考资料

一种android中实现“圆角矩形”的方法