Android-自定义三角形评分控件

简介: Android-自定义三角形评分控件

效果图

image.png

序言

移动应用开发中,显示数据的方式多种多样,直观的图形展示常常能带给用户更好的体验。本文将介绍如何使用Flutter创建一个自定义三角形纬度评分控件,该控件可以通过动画展示评分的变化,让应用界面更加生动。

实现思路及步骤

  1. 定义控件属性:首先需要定义控件的基本属性,如宽度、高度、最大评分以及每个顶点的评分值。
  2. 自定义绘制:使用自定义View绘制三角形和评分三角形,并在顶点处绘制空心圆点。
  3. 实现动画效果:使用属性动画ValueAnimator来控制评分动画,使每个顶点的评分从0逐渐增加到对应的评分值。

代码实现

定义自定义属性和布局文件

在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>
创建自定义View类

首先,创建一个自定义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())

        // 绘制内部动态三角形
        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)

        // 绘制动态点上的空心圆
        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="质量保证"
            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="更改数据" />

</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()
        }
    }
}

通过以上步骤和代码,我们可以创建一个带动画效果的三角形纬度评分控件,使评分展示更加生动和直观。

详情可见:github.com/yixiaolunhui/AndroidXY

相关文章
|
4月前
|
Android开发 UED 计算机视觉
Android自定义view之线条等待动画(灵感来源:金铲铲之战)
本文介绍了一款受游戏“金铲铲之战”启发的Android自定义View——线条等待动画的实现过程。通过将布局分为10份,利用`onSizeChanged`测量最小长度,并借助画笔绘制动态线条,实现渐变伸缩效果。动画逻辑通过四个变量控制线条的增长与回退,最终形成流畅的等待动画。代码中详细展示了画笔初始化、线条绘制及动画更新的核心步骤,并提供完整源码供参考。此动画适用于加载场景,提升用户体验。
421 5
Android自定义view之线条等待动画(灵感来源:金铲铲之战)
|
4月前
|
Android开发
Android自定义view之利用PathEffect实现动态效果
本文介绍如何在Android自定义View中利用`PathEffect`实现动态效果。通过改变偏移量,结合`PathEffect`的子类(如`CornerPathEffect`、`DashPathEffect`、`PathDashPathEffect`等)实现路径绘制的动态变化。文章详细解析了各子类的功能与参数,并通过案例代码展示了如何使用`ComposePathEffect`组合效果,以及通过修改偏移量实现动画。最终效果为一个菱形图案沿路径运动,源码附于文末供参考。
|
4月前
|
Android开发 开发者
Android自定义view之利用drawArc方法实现动态效果
本文介绍了如何通过Android自定义View实现动态效果,重点使用`drawArc`方法完成圆弧动画。首先通过`onSizeChanged`进行测量,初始化画笔属性,设置圆弧相关参数。核心思路是不断改变圆弧扫过角度`sweepAngle`,并调用`invalidate()`刷新View以实现动态旋转效果。最后附上完整代码与效果图,帮助开发者快速理解并实践这一动画实现方式。
133 0
|
4月前
|
Android开发 数据安全/隐私保护 开发者
Android自定义view之模仿登录界面文本输入框(华为云APP)
本文介绍了一款自定义输入框的实现,包含静态效果、hint值浮动动画及功能扩展。通过组合多个控件完成界面布局,使用TranslateAnimation与AlphaAnimation实现hint文字上下浮动效果,支持密码加密解密显示、去除键盘回车空格输入、光标定位等功能。代码基于Android平台,提供完整源码与attrs配置,方便复用与定制。希望对开发者有所帮助。
|
4月前
|
XML Java Android开发
Android自定义view之网易云推荐歌单界面
本文详细介绍了如何通过自定义View实现网易云音乐推荐歌单界面的效果。首先,作者自定义了一个圆角图片控件`MellowImageView`,用于绘制圆角矩形图片。接着,通过将布局放入`HorizontalScrollView`中,实现了左右滑动功能,并使用`ViewFlipper`添加图片切换动画效果。文章提供了完整的代码示例,包括XML布局、动画文件和Java代码,最终展示了实现效果。此教程适合想了解自定义View和动画效果的开发者。
213 65
Android自定义view之网易云推荐歌单界面
|
4月前
|
XML 前端开发 Android开发
一篇文章带你走近Android自定义view
这是一篇关于Android自定义View的全面教程,涵盖从基础到进阶的知识点。文章首先讲解了自定义View的必要性及简单实现(如通过三个构造函数解决焦点问题),接着深入探讨Canvas绘图、自定义属性设置、动画实现等内容。还提供了具体案例,如跑马灯、折线图、太极图等。此外,文章详细解析了View绘制流程(measure、layout、draw)和事件分发机制。最后延伸至SurfaceView、GLSurfaceView、SVG动画等高级主题,并附带GitHub案例供实践。适合希望深入理解Android自定义View的开发者学习参考。
521 84
|
4月前
|
前端开发 Android开发 UED
讲讲Android为自定义view提供的SurfaceView
本文详细介绍了Android中自定义View时使用SurfaceView的必要性和实现方式。首先分析了在复杂绘制逻辑和高频界面更新场景下,传统View可能引发卡顿的问题,进而引出SurfaceView作为解决方案。文章通过Android官方Demo展示了SurfaceView的基本用法,包括实现`SurfaceHolder.Callback2`接口、与Activity生命周期绑定、子线程中使用`lockCanvas()`和`unlockCanvasAndPost()`方法完成绘图操作。
103 3
|
4月前
|
Android开发 开发者
Android自定义view之围棋动画(化繁为简)
本文介绍了Android自定义View的动画实现,通过两个案例拓展动态效果。第一个案例基于`drawArc`方法实现单次动画,借助布尔值控制动画流程。第二个案例以围棋动画为例,从简单的小球直线运动到双向变速运动,最终实现循环动画效果。代码结构清晰,逻辑简明,展示了如何化繁为简实现复杂动画,帮助读者拓展动态效果设计思路。文末提供完整源码,适合初学者和进阶开发者学习参考。
Android自定义view之围棋动画(化繁为简)
|
4月前
|
Java Android开发 开发者
Android自定义view之围棋动画
本文详细介绍了在Android中自定义View实现围棋动画的过程。从测量宽高、绘制棋盘背景,到创建固定棋子及动态棋子,最后通过属性动画实现棋子的移动效果。文章还讲解了如何通过自定义属性调整棋子和棋盘的颜色及动画时长,并优化视觉效果,如添加渐变色让白子更明显。最终效果既可作为围棋动画展示,也可用作加载等待动画。代码完整,适合进阶开发者学习参考。
|
4月前
|
传感器 Android开发 开发者
Android自定义view之3D正方体
本文介绍了如何通过手势滑动操作实现3D正方体的旋转效果,基于Android自定义View中的GLSurfaceView。相较于使用传感器控制,本文改用事件分发机制(onTouchEvent)处理用户手势输入,调整3D正方体的角度。代码中详细展示了TouchSurfaceView的实现,包括触控逻辑、OpenGL ES绘制3D正方体的核心过程,以及生命周期管理。适合对Android 3D图形开发感兴趣的开发者学习参考。

热门文章

最新文章