Wanted to use sliders on one of the interfaces i was making and the existing release of sliders that i found used several unnecessary things and the code for interfaces that used sliders was all stuck into 1 method, so i decided to write my own much cleaner version.
Create a new class called WidgetSlider
Code:
/**
* @Author Suic
* Created on 9/9/2020
*/
public class WidgetSlider {
private float minValue, maxValue, value;
private int sliderWidth;
private SimpleImage background, handle;
public WidgetSlider(int minValue, int maxValue, int defaultValue, SimpleImage background, SimpleImage handle) {
this.minValue = minValue;
this.maxValue = maxValue;
this.value = defaultValue;
this.background = background;
this.handle = handle;
this.sliderWidth = background.width;
}
public void render(int x, int y) {
background.drawSprite(x, y);
int handleX = (int) MathUtils.map(value, minValue, maxValue, 0, sliderWidth - (handle.width / 2f));
handle.drawSprite(x + handleX, y - 1);
}
public void handleSlider(int x) {
value = MathUtils.map(x, 0, sliderWidth - 1, minValue, maxValue); // mapping to sliderWidth - 1 because x goes from 0 to width - 1
}
public float getValue() {
return value;
}
}
map method:
Code:
public static float map(float value, float istart, float istop, float ostart, float ostop) {
return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
}
in Widget/RSInterface:
Code:
public WidgetSlider widgetSlider;
public static void addSlider(int id, int minValue, int maxValue, int defaultValue, int backgroundSprite, int handleSprite) {
Widget widget = addInterface(id);
SimpleImage background = Client.spriteCache.get(backgroundSprite);
SimpleImage handle = Client.spriteCache.get(handleSprite);
widget.widgetSlider = new WidgetSlider(minValue, maxValue, defaultValue, background, handle);
widget.width = background.width;
widget.height = background.height;
widget.type = TYPE_SLIDER;
}
in buildInterfaceMenu inside where it iterates thru each component
Code:
if (child.type == Widget.TYPE_SLIDER && mousePressed) {
if (mouseX >= childX && mouseY >= childY
&& mouseX < childX + child.width && mouseY < childY + child.height) {
int xPos = mouseX - childX;
child.widgetSlider.handleSlider(xPos);
}
}
in drawInterface inside where it iterates thru each component
Code:
} else if (child.type == Widget.TYPE_SLIDER) {
WidgetSlider widgetSlider = child.widgetSlider;
widgetSlider.render(child_x_in_bounds, child_y_in_bounds);
Usage:
Code:
addSlider(id, 10, 75, 10, 615, 606);
Example of it used on a interface(i know that the slider sprites don't fit the interface, only used it for testing):