從0到1自定義分段式進度條
Eason最近遇到一個需求,需要去展示分段式的進度條,為了給這個進度條想要的外觀和感覺,在構建用戶界面 (UI) 時,大家通常會依賴 SDK 提供的可用工具并嘗試通過調整SDK來適配當前這個UI需求;但悲傷的是,大多數(shù)情況下它基本不符合我們的預期。所以Eason決定自己繪制它。
創(chuàng)建自定義視圖
在 Android 中要繪制自定義動圖,大家需要使用Paint并根據(jù)Path對象引導繪制到畫布上。
我們可以直接在畫布Canvas中操作上面的所有對象View。更具體地說,所有圖形的繪制都發(fā)生在onDraw()回調中。
- 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
- }
回到進度條,讓我們從開始對整個進度條的實現(xiàn)進行分解。
整體思路是:先繪制有一組顯示不同角度的四邊形,它們彼此間隔開并且具有沒有空間的填充狀態(tài)。最后,我們有一個波浪動畫與其填充進度同步。
在嘗試滿足上述所有這些要求之前,我們可以從一個更簡單的版本開始。不過不用擔心。我們會從基礎的開始并逐步深入淺出的!
繪制單段進度條
第一步是繪制其最基本的版本:單段進度條。
暫時拋開角度、間距和動畫等復雜元素。這個自定義動畫整體來說只需要繪制一個矩形。我們從分配 aPath和一個Paint對象開始。
- private val segmentPath: Path = Path()
- private val segmentPaint: Paint = Paint( Paint.ANTI_ALIAS_FLAG )
盡量不在onDraw()方法內部分配對象。這兩個Path和Paint對象必須在其范圍之內創(chuàng)建。在View很多時候調用這個onDraw回調時將導致你內存逐漸減少。編譯器中的 lint 消息也會警告大家不要這樣做。
要實現(xiàn)繪圖部分,我們可能要選擇Path的drawRect()方法。因為我們將在接下來的步驟中繪制更復雜的形狀,所以更傾向于逐點繪制。
- moveTo():將畫筆放置到特定坐標。
- lineTo(): 在兩個坐標之間畫一條線。
- 這兩種方法都接受Float值作為參數(shù)。
從左上角開始,然后將光標移動到其他坐標。
下圖表示將繪制的矩形,給定一定的寬度 ( w ) 和高度 ( h )。
在Android中,繪制時,Y軸是倒置的。在這里,我們從上到下計算。
繪制這樣的形狀意味著將光標定位在左上角,然后在右上角畫一條線。
- path.moveTo(0f, 0f)
- path.lineTo(w, 0f)
在右下角和左下角重復這個過程。
- path.lineTo(w, h)
- path.lineTo(0f, h)
最后,關閉路徑完成形狀的繪制。
- path.close()
計算階段已經完成。是時候用paint給它涂上顏色了!
針對Paint對象的處理,大家可以使用顏色、Alpha 通道和其他選項。Paint.Style枚舉決定形狀是否將被填充(默認)、空心有邊框或兩者兼而有之。在示例中,將繪制一個帶有半透明灰色的填充矩形:
- paint.color = color
- paint.alpha = alpha.toAlphaPaint()
對于 alpha 屬性,Paint需要Integer從 0 到 255。由于更習慣于Float從 0 到 1操作 a ,我創(chuàng)建了這個簡單的轉換器
- fun Float.toAlphaPaint(): Int = (this * 255).toInt()
上面已準備好呈現(xià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)
- }
- }
使用多段進度條前進
是不是感覺已經差不多快完成了呢?對的!已經完成了大部分自定義動畫的工作。我們將為每個段創(chuàng)建一個實例,而不是操作唯一的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))
- }
- }
我們一開始沒有設置間距,如果需要繪制多段動畫,則要相應地劃分View寬度,但是比較省心的是不需要考慮高度。和之前一樣,需要找到每段的四個坐標。我們已經知道 Y 坐標,因此找到計算 X 坐標的方程很重要。
下面是一個三段式進度條。我們通過引入線段寬度(sw)和間距(s)元素來注釋新坐標。
從上述圖中可以看到,X坐標取決于:
- 每段開始的位置(startX)
- 總段數(shù)(count)
- 段間距量(s)
有了這三個變量,我們就可以從這個進度條計算任何坐標:
每段的寬度:
- val sw = (w - s * (count - 1)) / count
從左坐標開始對于每個線段,X 坐標位于線段寬度sw加上間距處s,按上述關系可以得到:
- 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(): 繪制每個線段時,我們首先在移動到所需坐標之前重置路徑。
繪制進度
我們已經繪制了組件的基礎。然而目前我們不能稱它為進度條。因為還沒有顯示進度的部分。我們應該加入下圖的邏輯:
整體思路和之前繪制底部矩形形狀時差不多:
- 左坐標將始終為 0。
- 右坐標包括一個max()條件,以防止在進度為 0 時添加負間距。
- val topLeftX = 0f
- val bottomLeftX = 0f
- val topRight = sw * progress + s * max (0, progress - 1)
- val bottomRight = sw * progress + s * max (0, progress - 1)
要繪制進度段,我們需要聲明另一個Path和Paint對象,并存儲這個對象的progress值。
- var progress: Int = 0
- private val progressPath: Path = Path()
- private val progressPaint: Paint = Paint( Paint.ANTI_ALIAS_FLAG )
然后,我們調用drawSegment()去根據(jù)Path,Paint和坐標繪制出圖形。
添加動畫效果
我們怎么能忍受一個沒有動畫的進度條?
到目前為止,我們已經知道了如何來計算我們的線段坐標包括起始點。我們將通過在整個動畫持續(xù)時間內逐步繪制我們的片段來重復此模式。
我們可以分為三個階段:
開始:我們得到給定當前progress值的段坐標。
正在進行中:我們通過計算新舊坐標之間的線性插值來更新坐標。
結束:我們得到給定新progress值的線段坐標。
我們使用 aValueAnimator將狀態(tài)從 0(開始)更新到 1(結束)。它將處理正在進行的階段之間的插值。
- 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),我們使用擴展方法將原始值(this)與end某個步驟上的值()進行比較amount。
- fun Float.lerp(
- end: Float,
- @FloatRange(from = 0.0, to = 1.0) amount: Float
- ): Float =
- this * (1 - amount.coerceIn (0f, 1f)) + end * amount。強制輸入(0f,1f)
隨著動畫的進行,記錄下當前坐標并計算給定動畫位置的最新坐標 (amount)。
由于該invalidate()方法,然后發(fā)生漸進式繪圖。使用它會強制View調用onDraw()回調。
現(xiàn)在有了這個動畫,大家已經實現(xiàn)了一個組件來重現(xiàn)符合 UI 要求的原生 Android 進度條。
用斜角裝飾你的組件
即使組件已經滿足了我們對分段進度條的預期功能要求,但Eason想對它錦上添花。
為了打破立方體設計,可以使用斜角來塑造不同的線段。每個段之間保持空間,但我們以特定角度彎曲內部段。
是不是覺得無從下手?讓我們放大局部:
我們控制高度和角度,需要計算虛線矩形和三角形之間的距離。
如果大家還記得一些三角形的切線。在上圖中,我們在方程中引入了另一種化合物:線段切線 ( st )。
在 Android 中,該tan()方法需要一個以弧度為單位的角度。所以你必須先轉換它:
- val segmentAngle = Math.toRadians(angle.toDouble())
- val segmentTangent = h * tan (segmentAngle).toFloat()
使用這個最新的元素,我們必須重新計算段寬度的值:
- val sw = (w - (s + st) * (count - 1)) / count
我們可以繼續(xù)修改我們的方程。但首先,我們還需要重新考慮如何計算間距。
引入角度打破了我們對間距的感知,使得它不再在一個水平面上。大家自己看吧
我們想要的間距 ( s ) 不再與方程中使用的段間距 ( ss )匹配,所以調整計算這個間距的方式很重要。不過結合畢達哥拉斯定理應該可以解決問題:
- 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
從這些等式中,可以得出兩件點:
- 左下角坐標有一個max()條件,可以避免在第一段的邊界之外繪制。
- 右上角的最后一段也有同樣的問題,不應添加額外的段切線。
為了結束計算部分,我們還需要更新進度坐標:
- 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,進度 - 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ā)。我們公眾號團隊正在努力將最好的知識帶給大家,We’ll be back soon!