主要方法發介紹
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
