Search code examples
javalibgdxprogress-barnine-patch

Using 'small' values in progressBar with 9 patch looks bad


I'm using libGDX ProgressBar. I create it with the next code:

style = new ProgressBar.ProgressBarStyle();
style.background = new SpriteDrawable(backgroundImage);
NinePatch fillImage = new NinePatch(new TextureRegion(img2, 1, 1, img2.getWidth(), img2.getHeight()), 25, 26, 30, 30);
style.knobBefore = new NinePatchDrawable(fillImage);
style.knobBefore.setMinWidth(0);
style.knobBefore.setRightWidth(0);
style.knobBefore.setLeftWidth(0);

progress = new ProgressBar(0, 30, 0.1f, false, style);

When I set a value to a big number, for example 15 this is how it looks:[1]

but when I set a small value 1/30 (smaller the the basic 9 patch image) it looks bad:

Any ideas how to handle this problem?


Solution

  • You are setting your NinePatch width to be less than the minimum. The left and right do not change, so the minimum width your NinePatch can be is 25 + 26 = 51px. Any less than this you will get erroneous results. I believe the reason it looks like that is because your sides are actually pushing through each other, creating a negative width for the centre, which is still completely acceptable to draw with. (You can see in your image that the right is at the very far left, the left is most likely at the very far right but behind the reversed middle) The simplest solution would just be to limit the progress bar width to the proper minimum with something like this (if progress value is between 0 and 1);

    //convert min width to a ratio
    float minProgress = style.knobBefore.getMinWidth() / progressBarLength;
    
    float progress = Math.max(progress, minProgress);
    

    getMinWidth() would probably tell you it is 51/52px. You also shouldn't force setMinWidth(), setLeftWidht(), setRightWidth().