從0到1自定義分段式進(jìn)度條
Eason最近遇到一個需求,需要去展示分段式的進(jìn)度條,為了給這個進(jìn)度條想要的外觀和感覺,在構(gòu)建用戶界面 (UI) 時,大家通常會依賴 SDK 提供的可用工具并嘗試通過調(diào)整SDK來適配當(dāng)前這個UI需求;但悲傷的是,大多數(shù)情況下它基本不符合我們的預(yù)期。所以Eason決定自己繪制它。
創(chuàng)建自定義視圖
在 Android 中要繪制自定義動圖,大家需要使用Paint并根據(jù)Path對象引導(dǎo)繪制到畫布上。
我們可以直接在畫布Canvas中操作上面的所有對象View。更具體地說,所有圖形的繪制都發(fā)生在onDraw()回調(diào)中。
- class SegmentedProgressBar @JvmOverloads constructor(
- context: Context,
- attrs: AttributeSet? = null,
- defStyleAttr: Int = 0
- ) : View(context, attrs, defStyleAttr) {
- override fun onDraw(canvas: Canvas) {
- // Draw something onto the canvas
- }
回到進(jìn)度條,讓我們從開始對整個進(jìn)度條的實(shí)現(xiàn)進(jìn)行分解。
整體思路是:先繪制有一組顯示不同角度的四邊形,它們彼此間隔開并且具有沒有空間的填充狀態(tài)。最后,我們有一個波浪動畫與其填充進(jìn)度同步。
在嘗試滿足上述所有這些要求之前,我們可以從一個更簡單的版本開始。不過不用擔(dān)心。我們會從基礎(chǔ)的開始并逐步深入淺出的!
繪制單段進(jìn)度條
第一步是繪制其最基本的版本:單段進(jìn)度條。
暫時拋開角度、間距和動畫等復(fù)雜元素。這個自定義動畫整體來說只需要繪制一個矩形。我們從分配 aPath和一個Paint對象開始。
- private val segmentPath: Path = Path()
- private val segmentPaint: Paint = Paint( Paint.ANTI_ALIAS_FLAG )
盡量不在onDraw()方法內(nèi)部分配對象。這兩個Path和Paint對象必須在其范圍之內(nèi)創(chuàng)建。在View很多時候調(diào)用這個onDraw回調(diào)時將導(dǎo)致你內(nèi)存逐漸減少。編譯器中的 lint 消息也會警告大家不要這樣做。
要實(shí)現(xiàn)繪圖部分,我們可能要選擇Path的drawRect()方法。因?yàn)槲覀儗⒃诮酉聛淼牟襟E中繪制更復(fù)雜的形狀,所以更傾向于逐點(diǎn)繪制。
- moveTo():將畫筆放置到特定坐標(biāo)。
- lineTo(): 在兩個坐標(biāo)之間畫一條線。
- 這兩種方法都接受Float值作為參數(shù)。
從左上角開始,然后將光標(biāo)移動到其他坐標(biāo)。
下圖表示將繪制的矩形,給定一定的寬度 ( w ) 和高度 ( h )。
在Android中,繪制時,Y軸是倒置的。在這里,我們從上到下計算。
繪制這樣的形狀意味著將光標(biāo)定位在左上角,然后在右上角畫一條線。
- path.moveTo(0f, 0f)
- path.lineTo(w, 0f)
在右下角和左下角重復(fù)這個過程。
- path.lineTo(w, h)
- path.lineTo(0f, h)
最后,關(guān)閉路徑完成形狀的繪制。
- path.close()
計算階段已經(jīng)完成。是時候用paint給它涂上顏色了!
針對Paint對象的處理,大家可以使用顏色、Alpha 通道和其他選項(xiàng)。Paint.Style枚舉決定形狀是否將被填充(默認(rèn))、空心有邊框或兩者兼而有之。在示例中,將繪制一個帶有半透明灰色的填充矩形:
- paint.color = color
- paint.alpha = alpha.toAlphaPaint()
對于 alpha 屬性,Paint需要Integer從 0 到 255。由于更習(xí)慣于Float從 0 到 1操作 a ,我創(chuàng)建了這個簡單的轉(zhuǎn)換器
- fun Float.toAlphaPaint(): Int = (this * 255).toInt()
上面已準(zhǔn)備好呈現(xiàn)我們的第一個分段進(jìn)度條。我們只需要將我們的Paint按照計算出的x和y方向繪制在canvas上。
- canvas.drawPath(path,paint)
下面是部分代碼:
- class SegmentedProgressBar @JvmOverloads constructor(
- context: Context,
- attrs: AttributeSet? = null,
- defStyleAttr: Int = 0
- ) : View(context, attrs, defStyleAttr) {
- @get:ColorInt
- var segmentColor: Int = Color.WHITE
- var segmentAlpha: Float = 1f
- private val segmentPath: Path = Path()
- private val segmentPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
- override fun onDraw(canvas: Canvas) {
- val w = width.toFloat()
- val h = height.toFloat()
- segmentPath.run {
- moveTo(0f, 0f)
- lineTo(w, 0f)
- lineTo(w, h)
- lineTo(0f, h)
- close()
- }
- segmentPaint.color = segmentColor
- segmentPaint.alpha = alpha.toAlphaPaint()
- canvas.drawPath(segmentPath, segmentPaint)
- }
- }
使用多段進(jìn)度條前進(jìn)
是不是感覺已經(jīng)差不多快完成了呢?對的!已經(jīng)完成了大部分自定義動畫的工作。我們將為每個段創(chuàng)建一個實(shí)例,而不是操作唯一的Path和Paint對象。
- var segmentCount: Int = 1 // Set wanted value here
- private val segmentPaths: MutableList<Path> = mutableListOf()
- private val segmentPaints: MutableList<Paint> = mutableListOf()
- init {
- (0 until segmentCount).forEach { _ ->
- segmentPaths.add(Path())
- segmentPaints.add(Paint(Paint.ANTI_ALIAS_FLAG))
- }
- }
我們一開始沒有設(shè)置間距,如果需要繪制多段動畫,則要相應(yīng)地劃分View寬度,但是比較省心的是不需要考慮高度。和之前一樣,需要找到每段的四個坐標(biāo)。我們已經(jīng)知道 Y 坐標(biāo),因此找到計算 X 坐標(biāo)的方程很重要。
下面是一個三段式進(jìn)度條。我們通過引入線段寬度(sw)和間距(s)元素來注釋新坐標(biāo)。
從上述圖中可以看到,X坐標(biāo)取決于:
- 每段開始的位置(startX)
- 總段數(shù)(count)
- 段間距量(s)
有了這三個變量,我們就可以從這個進(jìn)度條計算任何坐標(biāo):
每段的寬度:
- val sw = (w - s * (count - 1)) / count
從左坐標(biāo)開始對于每個線段,X 坐標(biāo)位于線段寬度sw加上間距處s,按上述關(guān)系可以得到:
- val topLeftX = (sw + s) * 位置
- val bottomLeftX = (sw + s) * 位置
同理右上角和右下角:
- val topRightX = sw * (position + 1) + s * position
- val bottomRightX = sw * (position + 1) + s * position
開始繪制
- class SegmentedProgressBar @JvmOverloads constructor(
- context: Context,
- attrs: AttributeSet? = null,
- defStyleAttr: Int = 0
- ) : View(context, attrs, defStyleAttr) {
- @get:ColorInt
- var segmentColor: Int = Color.WHITE
- var segmentAlpha: Float = 1f
- var segmentCount: Int = 1
- var spacing: Float = 0f
- private val segmentPaints: MutableList<Paint> = mutableListOf()
- private val segmentPaths: MutableList<Path> = mutableListOf()
- private val segmentCoordinatesComputer: SegmentCoordinatesComputer = SegmentCoordinatesComputer()
- init {
- initSegmentPaths()
- }
- override fun onDraw(canvas: Canvas) {
- val w = width.toFloat()
- val h = height.toFloat()
- (0 until segmentCount).forEach { position ->
- val path = segmentPaths[position]
- val paint = segmentPaints[position]
- val segmentCoordinates = segmentCoordinatesComputer.segmentCoordinates(position, segmentCount, w, spacing)
- drawSegment(canvas, path, paint, segmentCoordinates, segmentColor, segmentAlpha)
- }
- }
- private fun initSegmentPaths() {
- (0 until segmentCount).forEach { _ ->
- segmentPaths.add(Path())
- segmentPaints.add(Paint(Paint.ANTI_ALIAS_FLAG))
- }
- }
- private fun drawSegment(canvas: Canvas, path: Path, paint: Paint, coordinates: SegmentCoordinates, color: Int, alpha: Float) {
- path.run {
- reset()
- moveTo(coordinates.topLeftX, 0f)
- lineTo(coordinates.topRightX, 0f)
- lineTo(coordinates.bottomRightX, height.toFloat())
- lineTo(coordinates.bottomLeftX, height.toFloat())
- close()
- }
- paint.color = color
- paint.alpha = alpha.toAlphaPaint()
- canvas.drawPath(path, paint)
- }
- }
path.reset(): 繪制每個線段時,我們首先在移動到所需坐標(biāo)之前重置路徑。
繪制進(jìn)度
我們已經(jīng)繪制了組件的基礎(chǔ)。然而目前我們不能稱它為進(jìn)度條。因?yàn)檫€沒有顯示進(jìn)度的部分。我們應(yīng)該加入下圖的邏輯:
整體思路和之前繪制底部矩形形狀時差不多:
- 左坐標(biāo)將始終為 0。
- 右坐標(biāo)包括一個max()條件,以防止在進(jìn)度為 0 時添加負(fù)間距。
- val topLeftX = 0f
- val bottomLeftX = 0f
- val topRight = sw * progress + s * max (0, progress - 1)
- val bottomRight = sw * progress + s * max (0, progress - 1)
要繪制進(jìn)度段,我們需要聲明另一個Path和Paint對象,并存儲這個對象的progress值。
- var progress: Int = 0
- private val progressPath: Path = Path()
- private val progressPaint: Paint = Paint( Paint.ANTI_ALIAS_FLAG )
然后,我們調(diào)用drawSegment()去根據(jù)Path,Paint和坐標(biāo)繪制出圖形。
添加動畫效果
我們怎么能忍受一個沒有動畫的進(jìn)度條?
到目前為止,我們已經(jīng)知道了如何來計算我們的線段坐標(biāo)包括起始點(diǎn)。我們將通過在整個動畫持續(xù)時間內(nèi)逐步繪制我們的片段來重復(fù)此模式。
我們可以分為三個階段:
開始:我們得到給定當(dāng)前progress值的段坐標(biāo)。
正在進(jìn)行中:我們通過計算新舊坐標(biāo)之間的線性插值來更新坐標(biāo)。
結(jié)束:我們得到給定新progress值的線段坐標(biāo)。
我們使用 aValueAnimator將狀態(tài)從 0(開始)更新到 1(結(jié)束)。它將處理正在進(jìn)行的階段之間的插值。
- class SegmentedProgressBar @JvmOverloads constructor(
- context: Context,
- attrs: AttributeSet? = null,
- defStyleAttr: Int = 0
- ) : View(context, attrs, defStyleAttr) {
- [...]
- var progressDuration: Long = 300L
- var progressInterpolator: Interpolator = LinearInterpolator()
- private var animatedProgressSegmentCoordinates: SegmentCoordinates? = null
- fun setProgress(progress: Int, animated: Boolean = false) {
- doOnLayout {
- val newProgressCoordinates =
- segmentCoordinatesComputer.progressCoordinates(progress, segmentCount, width.toFloat(), height.toFloat(), spacing, angle)
- if (animated) {
- val oldProgressCoordinates =
- segmentCoordinatesComputer.progressCoordinates(this.progress, segmentCount, width.toFloat(), height.toFloat(), spacing, angle)
- ValueAnimator.ofFloat(0f, 1f)
- .apply {
- duration = progressDuration
- interpolator = progressInterpolator
- addUpdateListener {
- val animationProgress = it.animatedValue as Float
- val topRightXDiff = oldProgressCoordinates.topRightX.lerp(newProgressCoordinates.topRightX, animationProgress)
- val bottomRightXDiff = oldProgressCoordinates.bottomRightX.lerp(newProgressCoordinates.bottomRightX, animationProgress)
- animatedProgressSegmentCoordinates = SegmentCoordinates(0f, topRightXDiff, 0f, bottomRightXDiff)
- invalidate()
- }
- start()
- }
- } else {
- animatedProgressSegmentCoordinates = SegmentCoordinates(0f, newProgressCoordinates.topRightX, 0f, newProgressCoordinates.bottomRightX)
- invalidate()
- }
- this.progress = progress.coerceIn(0, segmentCount)
- }
- }
- override fun onDraw(canvas: Canvas) {
- [...]
- animatedProgressSegmentCoordinates?.let { drawSegment(canvas, progressPath, progressPaint, it, progressColor, progressAlpha) }
- }
- }
為了得到線性插值(lerp),我們使用擴(kuò)展方法將原始值(this)與end某個步驟上的值()進(jìn)行比較amount。
- fun Float.lerp(
- end: Float,
- @FloatRange(from = 0.0, to = 1.0) amount: Float
- ): Float =
- this * (1 - amount.coerceIn (0f, 1f)) + end * amount。強(qiáng)制輸入(0f,1f)
隨著動畫的進(jìn)行,記錄下當(dāng)前坐標(biāo)并計算給定動畫位置的最新坐標(biāo) (amount)。
由于該invalidate()方法,然后發(fā)生漸進(jìn)式繪圖。使用它會強(qiáng)制View調(diào)用onDraw()回調(diào)。
現(xiàn)在有了這個動畫,大家已經(jīng)實(shí)現(xiàn)了一個組件來重現(xiàn)符合 UI 要求的原生 Android 進(jìn)度條。
用斜角裝飾你的組件
即使組件已經(jīng)滿足了我們對分段進(jìn)度條的預(yù)期功能要求,但Eason想對它錦上添花。
為了打破立方體設(shè)計,可以使用斜角來塑造不同的線段。每個段之間保持空間,但我們以特定角度彎曲內(nèi)部段。
是不是覺得無從下手?讓我們放大局部:
我們控制高度和角度,需要計算虛線矩形和三角形之間的距離。
如果大家還記得一些三角形的切線。在上圖中,我們在方程中引入了另一種化合物:線段切線 ( st )。
在 Android 中,該tan()方法需要一個以弧度為單位的角度。所以你必須先轉(zhuǎn)換它:
- val segmentAngle = Math.toRadians(angle.toDouble())
- val segmentTangent = h * tan (segmentAngle).toFloat()
使用這個最新的元素,我們必須重新計算段寬度的值:
- val sw = (w - (s + st) * (count - 1)) / count
我們可以繼續(xù)修改我們的方程。但首先,我們還需要重新考慮如何計算間距。
引入角度打破了我們對間距的感知,使得它不再在一個水平面上。大家自己看吧
我們想要的間距 ( s ) 不再與方程中使用的段間距 ( ss )匹配,所以調(diào)整計算這個間距的方式很重要。不過結(jié)合畢達(dá)哥拉斯定理應(yīng)該可以解決問題:
- val ss = sqrt (s. pow (2) + (s * tan (segmentAngle).toFloat()). pow (2))
- val topLeft = (sw + st + s) * position
- val bottomLeft = (sw + s) * position + st * max (0, position - 1)
- val topRight = (sw + st) * (position + 1) + s *位置 - if (isLast) st else 0f
- val bottomRight = sw * (position + 1) + (st + s) * position
從這些等式中,可以得出兩件點(diǎn):
- 左下角坐標(biāo)有一個max()條件,可以避免在第一段的邊界之外繪制。
- 右上角的最后一段也有同樣的問題,不應(yīng)添加額外的段切線。
為了結(jié)束計算部分,我們還需要更新進(jìn)度坐標(biāo):
- val topLeft = 0f
- val bottomLeft = 0f
- val topRight = (sw + st) * progress + s * max (0, progress - 1) - if (isLast) st else 0f
- val bottomRight = sw * progress + (st + s) *最大(0,進(jìn)度 - 1)
完整代碼:
- class SegmentedProgressBar @JvmOverloads constructor(
- context: Context,
- attrs: AttributeSet? = null,
- defStyleAttr: Int = 0
- ) : View(context, attrs, defStyleAttr) {
- @get:ColorInt
- var segmentColor: Int = Color.WHITE
- set(value) {
- if (field != value) {
- field = value
- invalidate()
- }
- }
- @get:ColorInt
- var progressColor: Int = Color.GREEN
- set(value) {
- if (field != value) {
- field = value
- invalidate()
- }
- }
- var spacing: Float = 0f
- set(value) {
- if (field != value) {
- field = value
- invalidate()
- }
- }
- // TODO : Voluntarily coerce value between those angle to avoid breaking quadrilateral shape
- @FloatRange(from = 0.0, to = 60.0)
- var angle: Float = 0f
- set(value) {
- if (field != value) {
- field = value.coerceIn(0f, 60f)
- invalidate()
- }
- }
- @FloatRange(from = 0.0, to = 1.0)
- var segmentAlpha: Float = 1f
- set(value) {
- if (field != value) {
- field = value.coerceIn(0f, 1f)
- invalidate()
- }
- }
- @FloatRange(from = 0.0, to = 1.0)
- var progressAlpha: Float = 1f
- set(value) {
- if (field != value) {
- field = value.coerceIn(0f, 1f)
- invalidate()
- }
- }
- var segmentCount: Int = 1
- set(value) {
- val newValue = max(1, value)
- if (field != newValue) {
- field = newValue
- initSegmentPaths()
- invalidate()
- }
- }
- var progressDuration: Long = 300L
- var progressInterpolator: Interpolator = LinearInterpolator()
- var progress: Int = 0
- private set
- private var animatedProgressSegmentCoordinates: SegmentCoordinates? = null
- private val progressPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
- private val progressPath: Path = Path()
- private val segmentPaints: MutableList<Paint> = mutableListOf()
- private val segmentPaths: MutableList<Path> = mutableListOf()
- private val segmentCoordinatesComputer: SegmentCoordinatesComputer = SegmentCoordinatesComputer()
- init {
- context.obtainStyledAttributes(attrs, R.styleable.SegmentedProgressBar, defStyleAttr, 0).run {
- segmentCount = getInteger(R.styleable.SegmentedProgressBar_spb_count, segmentCount)
- segmentAlpha = getFloat(R.styleable.SegmentedProgressBar_spb_segmentAlpha, segmentAlpha)
- progressAlpha = getFloat(R.styleable.SegmentedProgressBar_spb_progressAlpha, progressAlpha)
- segmentColor = getColor(R.styleable.SegmentedProgressBar_spb_segmentColor, segmentColor)
- progressColor = getColor(R.styleable.SegmentedProgressBar_spb_progressColor, progressColor)
- spacing = getDimension(R.styleable.SegmentedProgressBar_spb_spacing, spacing)
- angle = getFloat(R.styleable.SegmentedProgressBar_spb_angle, angle)
- progressDuration = getInteger(R.styleable.SegmentedProgressBar_spb_duration, progressDuration)
- recycle()
- }
- initSegmentPaths()
- }
- fun setProgress(progress: Int, animated: Boolean = false) {
- doOnLayout {
- val newProgressCoordinates =
- segmentCoordinatesComputer.progressCoordinates(progress, segmentCount, width.toFloat(), height.toFloat(), spacing, angle)
- if (animated) {
- val oldProgressCoordinates =
- segmentCoordinatesComputer.progressCoordinates(this.progress, segmentCount, width.toFloat(), height.toFloat(), spacing, angle)
- ValueAnimator.ofFloat(0f, 1f)
- .apply {
- duration = progressDuration
- interpolator = progressInterpolator
- addUpdateListener {
- val animationProgress = it.animatedValue as Float
- val topRightXDiff = oldProgressCoordinates.topRightX.lerp(newProgressCoordinates.topRightX, animationProgress)
- val bottomRightXDiff = oldProgressCoordinates.bottomRightX.lerp(newProgressCoordinates.bottomRightX, animationProgress)
- animatedProgressSegmentCoordinates = SegmentCoordinates(0f, topRightXDiff, 0f, bottomRightXDiff)
- invalidate()
- }
- start()
- }
- } else {
- animatedProgressSegmentCoordinates = SegmentCoordinates(0f, newProgressCoordinates.topRightX, 0f, newProgressCoordinates.bottomRightX)
- invalidate()
- }
- this.progress = progress.coerceIn(0, segmentCount)
- }
- }
- private fun initSegmentPaths() {
- segmentPaths.clear()
- segmentPaints.clear()
- (0 until segmentCount).forEach { _ ->
- segmentPaths.add(Path())
- segmentPaints.add(Paint(Paint.ANTI_ALIAS_FLAG))
- }
- }
- private fun drawSegment(canvas: Canvas, path: Path, paint: Paint, coordinates: SegmentCoordinates, color: Int, alpha: Float) {
- path.run {
- reset()
- moveTo(coordinates.topLeftX, 0f)
- lineTo(coordinates.topRightX, 0f)
- lineTo(coordinates.bottomRightX, height.toFloat())
- lineTo(coordinates.bottomLeftX, height.toFloat())
- close()
- }
- paint.color = color
- paint.alpha = alpha.toAlphaPaint()
- canvas.drawPath(path, paint)
- }
- override fun onDraw(canvas: Canvas) {
- val w = width.toFloat()
- val h = height.toFloat()
- (0 until segmentCount).forEach { position ->
- val path = segmentPaths[position]
- val paint = segmentPaints[position]
- val segmentCoordinates = segmentCoordinatesComputer.segmentCoordinates(position, segmentCount, w, h, spacing, angle)
- drawSegment(canvas, path, paint, segmentCoordinates, segmentColor, segmentAlpha)
- }
- animatedProgressSegmentCoordinates?.let { drawSegment(canvas, progressPath, progressPaint, it, progressColor, progressAlpha) }
- }
- }
希望本文對正在創(chuàng)建組件或者造輪子的大家有所啟發(fā)。我們公眾號團(tuán)隊正在努力將最好的知識帶給大家,We’ll be back soon!




































