自定义view的drawRoundRect模拟进度条

主要方法发介绍

                 1:drawRoundRect参数介绍

                 drawRoundRect(l,t,r,b,rx,ry,paint)里面的参数可以有两种:

                   1:前四个参数(l,t,r,,b)分别是矩形左边距离x轴的距离,上边距离y轴的距离,右边距离x轴的距离,以及下边距离y轴的距离,

                         rx,ry分别是画弧度时的高宽,paint就是画笔

                  2:ValueAnimator的应用,括号里面的两个参数是动画因子需要变化的范围,

valueAnimator1 = ValueAnimator.ofFloat(0f,width.toFloat()).apply {
duration = 2000 //设置动画的时间
addUpdateListener {//为动画添加数据更新事件
rect_width = animatedValue as Float//将实时更新的数据给动画因子
//当这个动画做完时就执行画圆弧动画
if (rect_width == width.toFloat()){
Start_redious()
}
invalidate()//重新绘制ondraw方法
}
start()
}
整体代码
自定义的view类中:
class myView:View {
//画矩形的画笔
private val paint_rect = Paint().apply {
style = Paint.Style.FILL
color = Color.BLUE
}
//画线的画笔
private val paint_line = Paint().apply {
style = Paint.Style.FILL
color = Color.WHITE
}
//矩形的宽度
private var rect_width =0f
//椭圆的rx,ry
private var redious = 0f
//向中间靠拢所移动的距离
private var moveX = 0f


//第一次动画的
lateinit var valueAnimator1:ValueAnimator
//画圆弧的动画
lateinit var valueAnimator2: ValueAnimator

constructor(context: Context):super(context){}
constructor(context: Context,attributeSet: AttributeSet?):super(context,attributeSet){}

override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
//画有圆角的矩形
canvas?.drawRoundRect(moveX,0f,rect_width-moveX,height.toFloat(),
redious,redious,paint_rect)

}
//矩形宽度变化的动画
fun Start_Rect_width(){
valueAnimator1 = ValueAnimator.ofFloat(0f,width.toFloat()).apply {
duration = 2000
addUpdateListener {
rect_width = animatedValue as Float
//当这个动画做完时就执行画圆弧动画
if (rect_width == width.toFloat()){
Start_redious()
}
invalidate()
}
start()
}
}
//椭圆圆弧redious的变化动画
fun Start_redious(){
ValueAnimator.ofFloat(0f,height/2f).apply {
duration = 1000
addUpdateListener {
redious = animatedValue as Float
if (redious == height/2f){
MoveTocenter()
}
invalidate()
}
start()
}
}
//向两边靠拢动画
fun MoveTocenter(){
ValueAnimator.ofFloat(0f,(width-2*redious)/2f).apply {
duration = 2000
addUpdateListener {
moveX = animatedValue as Float
if (moveX == (width-2*redious)/2f){
}
invalidate()
}
start()
}
}


}
xml文件中应用
<com.example.myapplication.myView
android:id="@+id/myview"
android:layout_width="0dp"
android:layout_height="100dp"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="100dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:background="@color/colorAccent/>
MainActivity中调用,我的方法中用了调用了视图的宽高,所以在onWindowFocusChanged方法中调用的方法,如果在oncreate方法中
调用动画将不会启动,其原因是,oncreate方法是在视图还没有出来之前调用,这是后调用视图的宽高,它会给你一个0,
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
myview.Start_Rect_width()
}
GitHub连接:https://github.com/luofangli/DrawRoundRect


原文地址:https://www.cnblogs.com/luofangli/p/13836228.html