大部分代碼網(wǎng)上找的简识,參考地址再找太麻煩了,懶得再找了感猛。
設(shè)置位置
//x,y為控件中心點(diǎn)坐標(biāo)
fun move(x:Int,y:Int,view:View){
val left = x - view.width/2
val top = y - view.height/2
val right = left + view.width
val bottom = top + view.height
//如果控件做過(guò)translation動(dòng)畫七扰,需要復(fù)位(2d)
view.translationX = 0f
view.translationY = 0f
view.layout(left,top,right,bottom)
}
彈簧動(dòng)畫1
// 通過(guò)自定義Interpolator可以實(shí)現(xiàn)一些有趣的效果
class SpringInterpolator(private val factor: Float) : Interpolator {
override fun getInterpolation(input: Float): Float {
//factor = 0.4
// pow(2, -10 * x) * sin((x - factor / 4) * (2 * PI) / factor) + 1
return (Math.pow(
2.0,
(-10 * input).toDouble()
) * Math.sin((input - factor / 4) * (2 * Math.PI) / factor) + 1).toFloat()
}
}
fun moveAni(x:Int,y:Int,view:View){
val left = x - view.width/2 - view.translationX
val top = y - view.height/2 - view.translationY
val mx = left - view.left
val my = top - view.top
var aniset = AnimatorSet()
var objAniY = ObjectAnimator.ofFloat(view,"translationY",view.translationY,view.translationY +my)
var objAniX = ObjectAnimator.ofFloat(view,"translationX",view.translationX,view.translationX +mx)
aniset.play(objAniX).with(objAniY)
aniset.duration = 300
aniset.interpolator = SpringInterpolator(1.3f)
aniset.start()
}
彈簧動(dòng)畫2
//彈簧動(dòng)畫庫(kù)
implementation 'com.android.support:support-dynamic-animation:28.0.0'
//彈簧2 可以再封裝一下,懶得弄了
fun moveAni2(x:Int,y:Int,view:View){
val left = x - view.width/2
val top = y - view.height/2
//這里可以用 SpringAnimation(view,SpringAnimation.TRANSLATION_Y,view.translationY)
// TRANSLATION_X陪白、 TRANSLATION_Y 等
//這里的示例沒有用TRANSLATION屬性做動(dòng)畫颈走,某種程度上這樣更靈活,用這樣的方法可以實(shí)現(xiàn)復(fù)雜的效果
var spaniY = SpringAnimation(view,object : FloatPropertyCompat<View>("top"){
override fun setValue(p0: View, p1: Float) {
p0.layout(p0.left,p1.toInt(),p0.right,p1.toInt()+p0.height)
}
override fun getValue(p0: View): Float {
return p0.top.toFloat()
}
})
spaniY.spring = SpringForce(top.toFloat())
//復(fù)合動(dòng)畫這部分如果設(shè)置的不一樣會(huì)有意想不到的混亂效果
spaniY.minimumVisibleChange = DynamicAnimation.MIN_VISIBLE_CHANGE_PIXELS
spaniY.spring.dampingRatio = SpringForce.DAMPING_RATIO_LOW_BOUNCY
spaniY.spring.stiffness = SpringForce.STIFFNESS_MEDIUM
spaniY.start()
var spanX = SpringAnimation(view,object : FloatPropertyCompat<View>("left"){
override fun setValue(p0: View, p1: Float) {
p0.layout(p1.toInt(),p0.top,p1.toInt()+p0.width,p0.bottom)
}
override fun getValue(p0: View): Float {
return p0.left.toFloat()
}
})
spanX.spring = SpringForce(left.toFloat())
//與第一個(gè)的設(shè)置相同
spanX.minimumVisibleChange = DynamicAnimation.MIN_VISIBLE_CHANGE_PIXELS
spanX.spring.dampingRatio = SpringForce.DAMPING_RATIO_LOW_BOUNCY
spanX.spring.stiffness = SpringForce.STIFFNESS_MEDIUM
spanX.start()
}