简体   繁体   中英

Animated Dashed Border in Android

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.

替代文字

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()...)

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 :)

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM