SweepGradient
SweepGradient即扫描渐变,类似于雷达,颜色绕着中心点,初始颜色从0度到360度线性渐变到边缘颜色。
它有两个构造函数:
- SweepGradient(float cx, float cy, int[] colors, float[] positions)
- SweepGradient(float cx, float cy, int color0, int color1)
双色的扫描渐变
先看其所对应的构造函数:
- SweepGradient(float cx, float cy, int color0, int color1)
其各参数的意义如下:
- cx:扫描中心的x坐标
- cy:扫描中心的x坐标
- color0:在扫描开始时渲染的颜色
- cloor1:在扫描结束时渲染的颜色
现在onDraw方法中,创建一个SweepGradient,指定其扫描中心就是View的中心,在扫描开始时渲染的颜色为红色,在扫描结束时渲染的颜色为红色。
private fun onDraw(canvas: Canvas?) {
***
val widthView: Int = measuredWidth
val heightView: Int = measuredHeight
val radius = if (widthView > heightView) heightView / 2.0f else widthView / 2.0f
val colorResA = resources.getColor(android.R.color.holo_red_dark)
val colorResB = resources.getColor(android.R.color.holo_blue_dark)
val sweepGradient = SweepGradient(widthView / 2.0f, heightView / 2.0f, colorResA, colorResB)
mPaint.shader = sweepGradient
canvas?.drawCircle(widthView / 2.0f, heightView / 2.0f, radius, mPaint)
}
从效果图上可以看到,扫描开始于X轴的正向,即为扫描的0度。
多色的扫描渐变
先看其所对应的构造函数:
- SweepGradient(float cx, float cy, int[] colors, float[] positions)
其各参数的意义如下:
- cx:扫描中心的x坐标
- cy:扫描中心的x坐标
- colors:表示渲染的颜色,它是一个颜色数组,数组长度必须大于等于2
- positions:表示相对位置数组,表示colors数组中几个颜色的相对位置,是一个float类型的数组,该数组的长度必须与colors数组的长度相同。如果这个参数使用null也可以,这时系统会按照梯度线来均匀分配colors数组中的颜色。
现在onDraw方法中,创建一个SweepGradient,指定其扫描中心就是View的中心,渲染的颜色数组为[红, 蓝, 黑, 绿],相对位置数组设置为NULL:
private fun onDraw(canvas: Canvas?) {
***
val widthView: Int = measuredWidth
val heightView: Int = measuredHeight
val radius = if (widthView > heightView) heightView / 2.0f else widthView / 2.0f
val colorResA = resources.getColor(android.R.color.holo_red_dark)
val colorResB = resources.getColor(android.R.color.holo_blue_dark)
val colorResC = resources.getColor(android.R.color.black)
val colorResD = resources.getColor(android.R.color.holo_green_dark)
val colorArray = intArrayOf(colorResA, colorResB, colorResC, colorResD)
val sweepGradient = SweepGradient(widthView / 2.0f, heightView / 2.0f, colorArray, null)
mPaint.shader = sweepGradient
canvas?.drawCircle(widthView / 2.0f, heightView / 2.0f, radius, mPaint)
}
此时,颜色渐变颜色按照梯度均匀变变化。
当指定相对位置数组为[0.2f, 0.3f, 0.4f, 1.0f]
private fun onDraw(canvas: Canvas?) {
***
val positionArray = floatArrayOf(0.2f, 0.3f, 0.4f, 1.0f)
val sweepGradient = SweepGradient(widthView / 2.0f, heightView / 2.0f, colorArray, null)
mPaint.shader = sweepGradient
canvas?.drawCircle(widthView / 2.0f, heightView / 2.0f, radius, mPaint)
}
颜色的渐变并没有按照梯度均匀分布,其渐变的效果是:
- 0.0f - 0.3f:这30%的占比中,渐变的起始颜色是红色,边缘颜色是蓝色
- 0.3f - 0.4f:这10%的占比中,渐变的起始颜色是蓝色,边缘颜色是黑色
- 0.4f - 1.0f:这60%的占比中,渐变的起始颜色是黑色,边缘颜色是绿色
这里需要注意的是:
- 相对位置数组可以为NULL,当设置为NULL时,颜色沿梯度线性均匀变化
- 如果设置了相对位置数组,该数组的的大小必须与颜色数组的长度一致。因为它的值一一对应了颜色的值。
- 相对位置数组的值在0-1之间的Float值,它决定了相对应颜色的线变区间
- 颜色数组的长度必须大于2
若想了解更多Paint相关的内容,请跳入: 自定义View系列文章目录
如果觉得我的文章对您有用,请随意点赞、评论。您的支持将鼓励我继续创作!