Android-自定義三角形評分控件

效果圖

屏幕錄制2024-05-18 20.21.33.gif

序言

在移動應(yīng)用開發(fā)中杠人,顯示數(shù)據(jù)的方式多種多樣些侍,直觀的圖形展示常常能帶給用戶更好的體驗苛预。本文將介紹如何使用Flutter創(chuàng)建一個自定義三角形緯度評分控件孵稽,該控件可以通過動畫展示評分的變化许起,讓應(yīng)用界面更加生動。

實現(xiàn)思路及步驟

  1. 定義控件屬性:首先需要定義控件的基本屬性菩鲜,如寬度园细、高度、最大評分以及每個頂點的評分值接校。
  2. 自定義繪制:使用自定義View繪制三角形和評分三角形猛频,并在頂點處繪制空心圓點。
  3. 實現(xiàn)動畫效果:使用屬性動畫ValueAnimator來控制評分動畫蛛勉,使每個頂點的評分從0逐漸增加到對應(yīng)的評分值鹿寻。

代碼實現(xiàn)

定義自定義屬性和布局文件

在res/values/attrs.xml中定義自定義屬性:

   <declare-styleable name="TriangleRatingAnimView">
        <attr name="maxRating" format="integer" />
        <attr name="upRating" format="integer" />
        <attr name="leftRating" format="integer" />
        <attr name="rightRating" format="integer" />
        <attr name="strokeColor" format="color" />
        <attr name="strokeWidth" format="dimension" />
        <attr name="ratingStrokeColor" format="color" />
        <attr name="ratingStrokeWidth" format="dimension" />
    </declare-styleable>

創(chuàng)建自定義View類

首先,創(chuàng)建一個自定義View類TriangleRatingAnimView诽凌,用于繪制三角形和動畫效果毡熏。

package com.yxlh.androidxy.demo.ui.rating

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import androidx.core.content.withStyledAttributes
import androidx.core.graphics.ColorUtils
import androidx.interpolator.view.animation.LinearOutSlowInInterpolator
import com.yxlh.androidxy.R


fun Context.dpToPx(dp: Float): Float {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics)
}

/**
 * 三角形評分控件
 * https://github.com/yixiaolunhui/AndroidXY
 */
class TriangleRatingAnimView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0,
) : View(context, attrs, defStyleAttr) {

    var maxRating: Int = 5
        set(value) {
            field = value
            invalidate()
        }
    var upRating: Int = 0
        set(value) {
            field = value
            animateRating()
        }
    var leftRating: Int = 0
        set(value) {
            field = value
            animateRating()
        }
    var rightRating: Int = 0
        set(value) {
            field = value
            animateRating()
        }
    private var strokeColor: Int = Color.GRAY
    private var strokeWidth: Float = context.dpToPx(1.5f)
    private var ratingStrokeColor: Int = Color.RED
    private var ratingStrokeWidth: Float = context.dpToPx(2.5f)
    private var animatedUpRating = 0
    private var animatedLeftRating = 0
    private var animatedRightRating = 0

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        color = strokeColor
        strokeWidth = this@TriangleRatingAnimView.strokeWidth
    }

    private val outerPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        color = ratingStrokeColor
        strokeWidth = this@TriangleRatingAnimView.ratingStrokeWidth
    }

    private val fillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.FILL
        color = ColorUtils.setAlphaComponent(ratingStrokeColor, (0.3 * 255).toInt())
    }
    private val circlePaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        color = ratingStrokeColor
        strokeWidth = context.dpToPx(1.5f)
    }
    private val circleFillPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.FILL
        color = Color.WHITE
    }

    init {
        context.withStyledAttributes(attrs, R.styleable.TriangleRatingAnimView) {
            maxRating = getInt(R.styleable.TriangleRatingAnimView_maxRating, 5)
            upRating = getInt(R.styleable.TriangleRatingAnimView_upRating, 0)
            leftRating = getInt(R.styleable.TriangleRatingAnimView_leftRating, 0)
            rightRating = getInt(R.styleable.TriangleRatingAnimView_rightRating, 0)
            strokeColor = getColor(R.styleable.TriangleRatingAnimView_strokeColor, Color.GRAY)
            strokeWidth = context.dpToPx(getDimension(R.styleable.TriangleRatingAnimView_strokeWidth, 2f))
            ratingStrokeColor = getColor(R.styleable.TriangleRatingAnimView_ratingStrokeColor, Color.RED)
            ratingStrokeWidth = context.dpToPx(getDimension(R.styleable.TriangleRatingAnimView_ratingStrokeWidth, 4f))
        }
    }

    private fun animateRating() {
        val animator = ValueAnimator.ofFloat(0f, 1f).apply {
            duration = 300
            interpolator = LinearOutSlowInInterpolator()
            addUpdateListener { animation ->
                val animatedValue = animation.animatedValue as Float
                animatedUpRating = (upRating * animatedValue).toInt()
                animatedLeftRating = (leftRating * animatedValue).toInt()
                animatedRightRating = (rightRating * animatedValue).toInt()
                invalidate()
            }
        }
        animator.start()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val width = measuredWidth.toFloat()
        val height = measuredHeight.toFloat()
        val circleRadius = context.dpToPx(5f)
        val padding = circleRadius + context.dpToPx(2f)

        val p1 = width / 2 to padding
        val p2 = padding to height - padding
        val p3 = width - padding to height - padding

        // 繪制外部三角形
        val path = Path().apply {
            moveTo(p1.first, p1.second)
            lineTo(p2.first, p2.second)
            lineTo(p3.first, p3.second)
            close()
        }
        canvas.drawPath(path, paint)

        val centroidX = (p1.first + p2.first + p3.first) / 3
        val centroidY = (p1.second + p2.second + p3.second) / 3

        // 繪制頂點到重心的連線
        canvas.drawLine(p1.first, p1.second, centroidX, centroidY, paint)
        canvas.drawLine(p2.first, p2.second, centroidX, centroidY, paint)
        canvas.drawLine(p3.first, p3.second, centroidX, centroidY, paint)

        val dynamicP1 =
            centroidX + (p1.first - centroidX) * (animatedUpRating / maxRating.toFloat()) to centroidY + (p1.second - centroidY) * (animatedUpRating / maxRating.toFloat())
        val dynamicP2 =
            centroidX + (p2.first - centroidX) * (animatedLeftRating / maxRating.toFloat()) to centroidY + (p2.second - centroidY) * (animatedLeftRating / maxRating.toFloat())
        val dynamicP3 =
            centroidX + (p3.first - centroidX) * (animatedRightRating / maxRating.toFloat()) to centroidY + (p3.second - centroidY) * (animatedRightRating / maxRating.toFloat())

        // 繪制內(nèi)部動態(tài)三角形
        val ratingPath = Path().apply {
            moveTo(dynamicP1.first, dynamicP1.second)
            lineTo(dynamicP2.first, dynamicP2.second)
            lineTo(dynamicP3.first, dynamicP3.second)
            close()
        }
        canvas.drawPath(ratingPath, outerPaint)
        canvas.drawPath(ratingPath, fillPaint)

        // 繪制動態(tài)點上的空心圓
        canvas.drawCircle(dynamicP1.first, dynamicP1.second, circleRadius, circlePaint)
        canvas.drawCircle(dynamicP1.first, dynamicP1.second, circleRadius - context.dpToPx(1.5f), circleFillPaint)
        canvas.drawCircle(dynamicP2.first, dynamicP2.second, circleRadius, circlePaint)
        canvas.drawCircle(dynamicP2.first, dynamicP2.second, circleRadius - context.dpToPx(1.5f), circleFillPaint)
        canvas.drawCircle(dynamicP3.first, dynamicP3.second, circleRadius, circlePaint)
        canvas.drawCircle(dynamicP3.first, dynamicP3.second, circleRadius - context.dpToPx(1.5f), circleFillPaint)
    }
}

定義Activity界面xml文件

在res/layout/activity_rating.xml中使用自定義View:

<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center_horizontal"
    android:gravity="center"
    android:orientation="vertical">


    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center">

        <TextView
            android:id="@+id/upText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="時間管理"
            android:textColor="@color/black"
            android:textSize="13sp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <com.yxlh.androidxy.demo.ui.rating.TriangleRatingAnimView
            android:id="@+id/triangleRatingAnimView"
            android:layout_width="300dp"
            android:layout_height="200dp"
            android:layout_centerInParent="true"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/upText"
            app:leftRating="3"
            app:maxRating="10"
            app:ratingStrokeColor="@android:color/holo_red_dark"
            app:ratingStrokeWidth="4dp"
            app:rightRating="8"
            app:strokeColor="@android:color/darker_gray"
            app:strokeWidth="3dp"
            app:upRating="5" />

        <TextView
            android:id="@+id/leftText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="成本控制"
            android:textColor="@color/black"
            android:textSize="13sp"
            app:layout_constraintTop_toBottomOf="@+id/triangleRatingAnimView"
            app:layout_constraintLeft_toLeftOf="@+id/triangleRatingAnimView"
            />

        <TextView
            android:id="@+id/rightText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="質(zhì)量保證"
            android:textColor="@color/black"
            android:textSize="13sp"
            app:layout_constraintTop_toBottomOf="@+id/triangleRatingAnimView"
            app:layout_constraintRight_toRightOf="@+id/triangleRatingAnimView"
            />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <Button
        android:id="@+id/randomizeButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/triangleRatingAnimView"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:text="更改數(shù)據(jù)" />

</androidx.appcompat.widget.LinearLayoutCompat>

定義RatingActivity

package com.yxlh.androidxy.demo.ui.rating

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.yxlh.androidxy.databinding.ActivityRatingBinding
import kotlin.random.Random

class RatingActivity : AppCompatActivity() {

    private var binding: ActivityRatingBinding? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityRatingBinding.inflate(layoutInflater)
        setContentView(binding?.root)
        binding?.randomizeButton?.setOnClickListener {
            randomizeRatings()
        }
    }

    private fun randomizeRatings() {
        val random = Random(System.currentTimeMillis())
        val maxRating = 5 + random.nextInt(6)
        val upRating = 1 + random.nextInt(maxRating)
        val leftRating = 1 + random.nextInt(maxRating)
        val rightRating = 1 + random.nextInt(maxRating)
        binding?.triangleRatingAnimView?.apply {
            this.maxRating = maxRating
            this.upRating = upRating
            this.leftRating = leftRating
            this.rightRating = rightRating
            invalidate()
        }
    }
}

通過以上步驟和代碼,我們可以創(chuàng)建一個帶動畫效果的三角形緯度評分控件侣诵,使評分展示更加生動和直觀痢法。

詳情可見:github.com/yixiaolunhui/AndroidXY

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市杜顺,隨后出現(xiàn)的幾起案子财搁,更是在濱河造成了極大的恐慌,老刑警劉巖躬络,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件尖奔,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機提茁,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門仗嗦,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人甘凭,你說我怎么就攤上這事稀拐。” “怎么了丹弱?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵德撬,是天一觀的道長。 經(jīng)常有香客問我躲胳,道長蜓洪,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任坯苹,我火速辦了婚禮隆檀,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘粹湃。我一直安慰自己恐仑,他們只是感情好,可當我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布为鳄。 她就那樣靜靜地躺著裳仆,像睡著了一般。 火紅的嫁衣襯著肌膚如雪孤钦。 梳的紋絲不亂的頭發(fā)上歧斟,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天,我揣著相機與錄音偏形,去河邊找鬼静袖。 笑死,一個胖子當著我的面吹牛俊扭,可吹牛的內(nèi)容都是我干的队橙。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼统扳,長吁一口氣:“原來是場噩夢啊……” “哼喘帚!你這毒婦竟也來了畅姊?” 一聲冷哼從身側(cè)響起咒钟,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎若未,沒想到半個月后朱嘴,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年萍嬉,在試婚紗的時候發(fā)現(xiàn)自己被綠了乌昔。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡壤追,死狀恐怖磕道,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情行冰,我是刑警寧澤溺蕉,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站悼做,受9級特大地震影響疯特,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜肛走,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一漓雅、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧朽色,春花似錦邻吞、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至腾誉,卻和暖如春徘层,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背利职。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工趣效, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人猪贪。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓跷敬,卻偏偏與公主長得像,于是被迫代替她去往敵國和親热押。 傳聞我的和親對象是個殘疾皇子西傀,可洞房花燭夜當晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容