hocinehamdi
9/13/2014 - 10:01 PM

Animated share button

Animated share button

/**
 * An easy way to display an animated share button, 
 * the three dots will start from the center 
 * to their final positions.
 */

public class AnimatedShareButton extends View {
    private Paint paint;

    private float cx1 = -1;
    private float cy1 = -1;
    private float cx2 = -1;
    private float cy2 = -1;
    private float cx3 = -1;
    private float cy3 = -1;

    boolean startAnim = false;

    public AnimatedShareButton(Context context) {
        super(context);
        init();
    }

    public AnimatedShareButton(Context context, AttributeSet attributes) {
        super(context, attributes);

        init();
    }

    private void init() {
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(getResources().getColor(R.color.orange));

        postDelayed(new Runnable() {
            @Override
            public void run() {
                startAnim = true;
                invalidate();
            }
        }, 500);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        boolean invalidate = false;

        if (cx1 == -1) {
            cx1 = getHeight() * 0.5f;
            cy1 = getHeight() * 0.5f;
            cx2 = getHeight() * 0.5f;
            cy2 = getHeight() * 0.5f;
            cx3 = getHeight() * 0.5f;
            cy3 = getHeight() * 0.5f;

            invalidate();
        } else if (startAnim) {
            if (cx1 > getHeight() * 0.30f) {
                cx1 -= 1;
                invalidate = true;
            }

            if (cx2 < getHeight() * 0.70f) {
                cx2 += 1;
                invalidate = true;
            }

            if (cy2 > getHeight() * 0.30f) {
                cy2 -= 1;
                invalidate = true;
            }

            if (cx3 < getHeight() * 0.70f) {
                cx3 += 1;
                invalidate = true;
            }

            if (cy3 < getHeight() * 0.70f) {
                cy3 += 1;
                invalidate = true;
            }
        }

        float radius = getHeight() * 0.15f;

        canvas.drawCircle(cx1, cy1, radius, paint);
        canvas.drawCircle(cx2, cy2, radius, paint);
        canvas.drawCircle(cx3, cy3, radius, paint);

        if (cx2 - cx1 > radius * 2) {
            paint.setStrokeWidth(radius*0.25f);
            canvas.drawLine(cx1, cy1, cx2, cy2, paint);
            canvas.drawLine(cx1, cy1, cx3, cy3, paint);
        }

        if (invalidate)
            invalidate();
    }
}