2015-03-24 100 views
3

我有一个自定义的视图,我想绘制一条路径,就像一个边框。 但边界应该逐渐吸引,就像一条长大的蛇。 目标是将其用作玩家在游戏中进行移动的计时器。在Android中逐渐绘制的路径

我使用了Path类和方法lineTo和addArc来绘制边框。

timerPath = new Path(); 
timerPath.moveTo(getTranslationX() + width/2, getTranslationY() + 3); 
timerPath.lineTo(getTranslationX() + width - 10, getTranslationY() + 3); 
timerPath.addArc(new RectF(getTranslationX() + width - 20, getTranslationY() + 3, 
getTranslationX() + width - 3, getTranslationY() + 20), -90f, 90f); 
... 
... 
timerPath.lineTo(getTranslationX() + width/2, getTranslationY() + 3); 

timerPaint = new Paint(); 
timerPaint.setColor(Color.GREEN); 
timerPaint.setStyle(Paint.Style.STROKE); 
timerPaint.setStrokeWidth(6); 

我使用drawPath()方法中的onDraw:

canvas.drawPath(timerPath, timerPaint); 

它看起来很好。

现在,我想知道是否有一种方法可以使用百分比(10%,11%,12%等)绘制路径的一部分。 然后我就可以为图画制作动画了。

如果这是不可能的,是否有另一种动画边界绘图的方式? (用作定时器)

感谢您的帮助。

回答

6

您可以使用PathMeasure类来完成此操作。从您的路径创建一个PathMeasure对象,测量长度,然后用getSegment()返回,你可以画到画布部分路径:

float percentage = 50.0f; // initialize to your desired percentage 

    PathMeasure measure = new PathMeasure(timerPath, false); 
    float length = measure.getLength(); 
    Path partialPath = new Path(); 
    measure.getSegment(0.0f, (length * percentage)/100.0f, partialPath, true); 
    partialPath.rLineTo(0.0f, 0.0f); // workaround to display on hardware accelerated canvas as described in docs 
    canvas.drawPath(partialPath, timerPaint); 
+0

正是我一直在寻找。非常感谢!! – 2015-03-25 12:04:18