kotlin第六课加载动画
2021-04-18 本文已影响0人
恰我年少时
image.png
loading中的代码:
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.os.Build
import android.util.AttributeSet
import android.view.View
import androidx.annotation.RequiresApi
import java.text.AttributedCharacterIterator
import java.util.jar.Attributes
class LoadingView(context:Context,attrs:AttributeSet? = null)
: View(context,attrs)
{
val bgPaint:Paint = Paint().also {
it.color = Color.YELLOW
it.strokeWidth = 20f
it.style = Paint.Style.STROKE
}//创建画笔
val fgPaint:Paint = Paint().also {
it.color = Color.RED
it.strokeWidth = 20f
it.style = Paint.Style.STROKE
it.strokeCap = Paint.Cap.ROUND
}
//onDraw会被多次调用
//动画因子
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
var sweepAngle = 0f
set(value){
field = value
invalidate()
}
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
override fun onDraw(canvas: Canvas) {//运行起来后系统自动调用
//super.onDraw(canvas)//如何绘制一个圆:画板(canvas)、画笔(有粗细颜色)Paint
val cx = width.toFloat()/2
val cy = height.toFloat()/2
val radius = Math.min(width.toFloat(),height.toFloat())/2-bgPaint.strokeWidth
canvas?.drawCircle(cx, cy, radius.toFloat(),bgPaint)
//进度
canvas?.drawArc(fgPaint.strokeWidth,fgPaint.strokeWidth,width.toFloat()-fgPaint.strokeWidth,height.toFloat()-fgPaint.strokeWidth, -90f, sweepAngle,false,fgPaint)
}
}
MainActivity中的代码:
import android.animation.ValueAnimator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
//on开头一般是一些事件,由系统调用
class MainActivity : AppCompatActivity() {//主界面
lateinit var loadingView: LoadingView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)//把我们的内容视图R.layout.activity_main解析、复制给主视图
loadingView = findViewById(R.id.progressView) //在xml文件中找到id为progressView的控件
}
override fun onTouchEvent(event: MotionEvent?): Boolean {//返回true会把事件消费掉,false会传给下一层
if (event?.action == MotionEvent.ACTION_DOWN){//触发动画
ValueAnimator.ofFloat(0f,360f).apply {
//已经创建对象
this.duration = 3000 // this可省略
addUpdateListener {
//获取当前产生的值
val value = it.animatedValue as Float
//改变LoadingView变化因子的值
loadingView.sweepAngle = value
Log.v("ppp","$value")
}
start()
repeatCount = 50000000
}//动画管理器
}
//dowm\move\up三个动作
return true
}
}
/**
1、百分比显示在中间
2、两个按钮:开始下载、暂停下载和继续
*/