Skip to content

Commit

Permalink
优化
Browse files Browse the repository at this point in the history
  • Loading branch information
821938089 committed May 14, 2024
1 parent 5eaf2f0 commit 72ad27e
Showing 1 changed file with 9 additions and 28 deletions.
37 changes: 9 additions & 28 deletions app/src/main/java/io/legado/app/ui/widget/BatteryView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@ import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.os.Build
import android.text.StaticLayout
import android.text.style.LineHeightSpan
import android.util.AttributeSet
import androidx.annotation.ColorInt
import androidx.appcompat.widget.AppCompatTextView
Expand All @@ -29,13 +27,6 @@ class BatteryView @JvmOverloads constructor(
private val outFrame = Rect()
private val polar = Rect()
private val canvasRecorder = CanvasRecorderFactory.create()
private val batterySpan = LineHeightSpan { _, _, _, _, _, fm ->
fm.top = -22
fm.ascent = -28
fm.descent = 7
fm.bottom = 1
fm.leading = 0
}
var isBattery = false
set(value) {
field = value
Expand All @@ -48,6 +39,9 @@ class BatteryView @JvmOverloads constructor(

init {
setPadding(4.dpToPx(), 3.dpToPx(), 6.dpToPx(), 3.dpToPx())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
isFallbackLineSpacing = false
}
batteryPaint.strokeWidth = 1f.dpToPx()
batteryPaint.isAntiAlias = true
batteryPaint.color = paint.color
Expand All @@ -69,9 +63,9 @@ class BatteryView @JvmOverloads constructor(
fun setBattery(battery: Int, text: String? = null) {
this.battery = battery
if (text.isNullOrEmpty()) {
setText(getBatteryText(battery.toString()))
setText(battery.toString())
} else {
setText(getBatteryText("$text $battery"))
setText("$text $battery")
}
}

Expand All @@ -84,17 +78,16 @@ class BatteryView @JvmOverloads constructor(
if (AppConfig.optimizeRender) {
canvasRecorder.recordIfNeededThenDraw(canvas, width, height) {
super.onDraw(this)
if (!isBattery) return@recordIfNeededThenDraw
drawBattery(this)
}
} else {
super.onDraw(canvas)
if (!isBattery) return
drawBattery(canvas)
}
}

private fun drawBattery(canvas: Canvas) {
if (!isBattery) return
layout.getLineBounds(0, outFrame)
val batteryStart = layout
.getPrimaryHorizontal(text.length - battery.toString().length)
Expand All @@ -120,22 +113,10 @@ class BatteryView @JvmOverloads constructor(
canvas.drawRect(polar, batteryPaint)
}

private fun getBatteryText(text: CharSequence?): SpannableStringBuilder? {
if (text == null) {
return null
}

return SpannableStringBuilder(text).apply {
setSpan(batterySpan, 0, text.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
}


@Suppress("UNNECESSARY_SAFE_CALL")
override fun invalidate() {
super.invalidate()
kotlin.runCatching {
canvasRecorder.invalidate()
}
canvasRecorder?.invalidate()
}

}

0 comments on commit 72ad27e

Please sign in to comment.