我正在使用Paint
和Canvas
在onDraw上绘制自定义形状。在onDraw类中,我有一个矩形clipPath
。
我希望能够对clipPath
中MainActivity
的位置进行动画处理(从左到右动画)。这将隐藏从左到右绘制的图形(BlackGraph)。
class BlackGraph(context: Context) : View(context) {
var clipAmount:Float = 0.0f
override fun onDraw(canvas: Canvas) {
val paint = Paint()
paint.style = Paint.Style.FILL
paint.color = Color.parseColor("#000000")
val path = Path()
val clipPath = Path()
clipPath.addRect(clipAmount, 0f, width.toFloat(), height.toFloat(), Path.Direction.CW)
canvas.clipPath(clipPath)
path.moveTo(0f, height-30.toFloat())
path.lineTo(width.toFloat(), 0f)
path.lineTo(width.toFloat(), height.toFloat())
path.lineTo(0f, height.toFloat())
path.lineTo(0f, 0f)
canvas.drawPath(path, paint)
}
}
在 onCreate 中:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val layout1 = findViewById<android.support.constraint.ConstraintLayout>(R.id.layout1)
val blackGraph = BlackGraph(this)
layout1.addView(blackGraph)
val valueAnimator = ValueAnimator.ofFloat(0f, 450f)
valueAnimator.addUpdateListener {
val value = it.animatedValue as Float
println("Value -> $value")
blackGraph.clipAmount = value
}
valueAnimator.duration = 2000
valueAnimator.start()
}
我试图简单地动画clipAmount的位置以实现所需的动画。
问题出在onCreate
中,clipAmount值从不动画。但是,打印语句可以正常工作。 Logcat充满了从0.0到450.0的float值
如何为clipPath
的运动设置动画?
答案 0 :(得分:1)
好的,您在这里遇到了一些问题。首先,您不应该在onDraw()中初始化Paint,Path,应该首先对其进行初始化,然后再进行修改,这样您将获得更好的性能。更新clipAmount
的值时,需要调用postInvalidateOnAnimation()
以使BlackGraph
视图再次绘制,这将触发方法onDraw()
。最后一件事是clipPath
需要调用reset()
来清除,然后才能使用方法addRect()
添加新路径。
class BlackGraph(context: Context) : View(context) {
var clipAmount:Float = 0.0f
val paint = Paint().apply {
style = Paint.Style.FILL
color = Color.parseColor("#000000")
}
val path = Path()
val clipPath = Path()
override fun onDraw(canvas: Canvas) {
clipPath.apply {
reset()
addRect(clipAmount, 0f, width.toFloat(), height.toFloat(), Path.Direction.CW)
}
canvas.clipPath(clipPath)
path.moveTo(0f, height-30.toFloat())
path.lineTo(width.toFloat(), 0f)
path.lineTo(width.toFloat(), height.toFloat())
path.lineTo(0f, height.toFloat())
path.lineTo(0f, 0f)
canvas.drawPath(path, paint)
}
fun animateClipAmount() {
val valueAnimator = ValueAnimator.ofFloat(0f, 450f)
valueAnimator.addUpdateListener {
val value = it.animatedValue as Float
clipAmount = value
println("Value -> $clipAmount")
postInvalidateOnAnimation()
}
valueAnimator.duration = 2000
valueAnimator.start()
}
}
在onCreate中:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val layout1 = findViewById<android.support.constraint.ConstraintLayout>(R.id.layout1)
val blackGraph = BlackGraph(this)
layout1 .addView(blackGraph)
blackGraph.animateClipAmount()
}
}