Skip to content

Instantly share code, notes, and snippets.

@mauriciogior
Last active August 29, 2015 14:13
Show Gist options
  • Save mauriciogior/527570bab1ae55d7aa98 to your computer and use it in GitHub Desktop.
Save mauriciogior/527570bab1ae55d7aa98 to your computer and use it in GitHub Desktop.
ImageView with background fill

Example

Screenshot

There is no support for horizontal fill, just vertical.

public class ImageViewWithFill extends ImageView {

    private final int fillColor = 0xff66ffcc; // fill color
    private float fill = 0f; // filled percentage (0 - 100)

    public ImageViewWithFill(Context context) {
        super(context);
    }

    public ImageViewWithFill(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ImageViewWithFill(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void fillAt(float fillTo) {
        FillAnimation animation = new FillAnimation(fill, fillTo);

        ((ViewGroup) getParent()).invalidate();
        getRootView().invalidate();

        setAnimation(animation);
        animate().start();
    }

    public float getAmountFilled() {
        return fill;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int h = canvas.getHeight();
        int w = canvas.getWidth();

        Paint p = new Paint();
        p.setColor(fillColor);
        p.setFlags(Paint.ANTI_ALIAS_FLAG);
        
        // change here to add support for horizontal fill
        canvas.drawRect(0, h, w, h * ((100 - fill) / 100), p);

        super.onDraw(canvas);
    }

    private class FillAnimation extends Animation {

        private static final float SPEED = 0.08f;

        private float mStart;
        private float mEnd;

        public FillAnimation(float fromY, float toY) {
            mStart = fromY;
            mEnd = toY;

            setInterpolator(new LinearInterpolator());

            float duration = Math.abs(mEnd - mStart) / SPEED;
            setDuration((long) duration);
        }

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);

            float offset = (mEnd - mStart) * interpolatedTime + mStart;

            fill = offset;

            postInvalidate();
        }

    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment