views:

116

answers:

3

How do you create an animated dashed or dotted border of an arbitrary shape in Android? In XML (preferred) or programmatically.

See picture below for an example.

alt text

A: 

XML... I guess not possible. But you can use a custom view or a SurfaceView and handle the drawing by yourself. Have fun with that :)

WarrenFaith
Any pointers to implement it with a custom view or SurfaceView?
hgpc
you can draw lines on every canvas and the used Paint object can have different styles. If you change between white line with a black dashed line above and black line with white dashed line above on every frame, you should get the wished effect.
WarrenFaith
A: 

Could you use some form of two 9patch images as a background frame around the image file you want to present, one in each of two layouts. The images would differ in terms of the placement of the dashed elements. Interchange the views rapidly (might need a delay) and you might get the effect you want. Don't really know how effective that would be though in terms of being able to let the user continue using the app and chewing battery...

Adriaan
Two 9 patch images in an animation drawable. That might work, and is doable via XML. Will give it a try.
hgpc
Nope. Doesn't work. 9 patch images do not repeat patterns, they just stretch a part of the image.
hgpc
Sorry, what I was getting at is that you create two images in 9patch format. You will have to create the patterns yourself but in such a way that if you were to rapidly switch between them it would create the illusion that the dashes were moving.
Adriaan
The switch can be done with an animation drawable. However, I don't understand how the 9patch images can be used to create a resolution independent dotted border (animated or not).
hgpc
I don't think 9patchs will be useful in this situation, there is no way to specify them to tile a section like he wants.
smith324
+1  A: 

Have you seen the PathEffects API demo? http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/graphics/PathEffects.html

It produces precisely an animated line and you can just adjust the path to the edge of your view to create a border. For example:

Define a path by your view parameters / arbitrary shape:

Path path = new Path();
path.addRect(view.getLeft(), view.getTop(), view.getRight(), view.getBottom(), Path.Direction.CW);

Then create a dashed PathEffect with:

PathEffect pe = new DashPathEffect(new float[] {10, 5, 5, 5}, phase);

Then set the associate it with a Paint object and draw:

mPaint.setPathEffect(pe);
canvas.drawPath(path, mPaint);

EDIT: The animated effect comes from continuously changing the phase and redrawing. In the API demo it calls invalidate() in the onDraw() method (which triggers onDraw()...)

antonyt
Thanks antonyt! This is exactly what I was looking for. Pity it can't be defined in xml.
hgpc