scene2d button scaling with libgdx - android

I don't know if it is just me, but drawables confuse me. Are they intended to keep the size they are given, or is there a way to scale the image within them? I understand they can use ninepatch to fill certain areas by stretching an image, but I want to scale the image that it stretches. I am using a TextButton
for my menu buttons, but they are way too big, and I would love to know how to scale them. I am retrieving the skin from an atlas, which has ninepatch images in it.
Here is the settings screen:
Here are the images in the pack I am using:
Here is the initialization of the TextureAtlas, and Skin:
buttonAtlas = new TextureAtlas(Gdx.files.internal("buttons/buttons.pack"));
buttonSkin = new Skin(buttonAtlas);
Here is the initialization of that menu button.
TextButtonStyle textButtonStyle = new TextButtonStyle();
textButtonStyle.up = Assets.buttonSkin.getDrawable("bluebutton");
textButtonStyle.down = Assets.buttonSkin.getDrawable("redbutton");
textButtonStyle.font = font;
buttonMenu = new TextButton("Menu", textButtonStyle);
buttonMenu.pad(20.0f);
buttonMenu.addListener(new ClickListener() {
#Override
public void clicked(InputEvent event, float x, float y) {
game.fade.startFadeOut();
super.clicked(event, x, y);
}
});
And perhaps I could change how I put it in the table, or how I put the table in the stage?
table.add(buttonMenu).width(Gdx.graphics.getWidth()/4);
stage.addActor(table);
As a last resort I suppose I could attempt creating my own text button actor that I could scale, thank you for your time.

First of all if you know that your images are too big: The best would be to scale the images themselves to a smaller size and then use the TexturePacker too generate a new TextureAtlas that contain the smaller images.
Anyhow you can scale the image button with the TableLayout if you really want to, see example:
table.add(buttonMenu).width(100).height(100);

The above answer didnt work for me, but i have a solution.
You can make a secondary camera and attach it to your stage.
To scale the table just scale the viewport size of the secondary camera
An example would be:
//Heres where you set the scale of your buttons and your table
Camera secondaryCamera = new Camera(Gdx.graphics.getWidth() * scale,
Gdx.graphics.getHeight() * scale);
Stage stage = new Stage();
Table table = new Table();
ImageButton button = new ImageButton(drawableUp, drawableDown, drawableChecked);
table.setFillParent(true);
stage.getViewport().setCamera(secondaryCamera);
table.add(ImageButton);
stage.addActor(table);
This works great when your using it for touch controls. You can use a table for the entire UI and scale it to your liking independent of your other game items;

table.add(buttonMenu).width(100).height(100); should work, and you just need to adjust the width and height parameters to your liking, or you can use the setBounds method. Here is an example:
TextButton myButton = new TextButton("Press Me", style);
myButton.setBounds(xCoordinate, yCoordinate, width, height);

You can set size of Drawable in ButtonStyle to resize your Button:
float scale = 0.5f;
float currentHeight = textButtonStyle.up.getMinHeight();
textButtonStyle.up.setMinHeight(currentHeight * scale);
For more information, see official document for layout:
UI widgets do not set their own size and position. Instead, the parent widget sets the size and position of each child. Widgets provide a minimum, preferred, and maximum size that the parent can use as hints. Some parent widgets, such as Table and Container, can be given constraints on how to size and position the children. To give a widget a specific size in a layout, the widget's minimum, preferred, and maximum size are left alone and size constraints are set in the parent.
And you can find the implementation of Button.getPrefHeight() in the source code:
public float getPrefHeight () {
float height = super.getPrefHeight();
if (style.up != null) height = Math.max(height, style.up.getMinHeight());
if (style.down != null) height = Math.max(height, style.down.getMinHeight());
if (style.checked != null) height = Math.max(height, style.checked.getMinHeight());
return height;
}

Related

adding constraints to a spinner in my code

I have a code in my app which when you click the FAB, a spinner appears. when I test this on my phone which is quite small in screen size, the spinner shows up right. but when I try it on a bigger phone screen size, the spinner seems to shrink and is hidden partially.
Is it possible to add constraints to my code here so that the size of the spinner will change depending on the size of the screen and it won't be partially cut off/hidden?
code:
SearchableSpinner spinner = (SearchableSpinner) makeSpinner();
mLinearLayout.addView(spinner); //Add another spinner
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)spinner.getLayoutParams();
layoutParams.setMargins( 5, 130, 10, 0);
layoutParams.height = 80;//pixels
layoutParams.width = 240;//pixels
spinner.setLayoutParams(layoutParams);
To make your spinner have a consistent size/looks on different screen sizes you have to use DP(density independent pixels) instead of simple pixels.
What I would recommend you to do is to set your layout.height/width to specific DP by converting DP to pixels using this:
public static float convertDpToPixel(float dp, Context context){
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float px = dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
return px;
}
Good luck :)

Android Drawable Overflowing From Button Borders

I am using the following code to scale an image to 150dpx150dp and place in inside a 150dpx150dp button but the image overflows the button in all dimensions:
float densityScale = getResources().getDisplayMetrics().density;
float scaledImageWidth = 150 * densityScale;
float scaledImageHeight = 150 * densityScale;
Drawable image = getResources().getDrawable(R.drawable.user_photo);
Bitmap bitmap = ((BitmapDrawable)image).getBitmap();
Drawable scaledImage = new BitmapDrawable(Bitmap.createScaledBitmap(bitmap, (int)scaledImageWidth, (int)scaledImageHeight, true));
scaledImage.setBounds(0, 0, (int)scaledImageWidth, (int)scaledImageHeight);
((Button)findViewById(R.id.button)).setCompoundDrawables(null, scaledImage, null, null);
((Button)findViewById(R.id.button)).setPadding(0,0,0,0);
Button and image are of the same size. Why does this overflow happen and how can it be fixed?
(I know I can use an ImageButton for this but I want to use button drawable because there are cases where I will need to add text etc.)
You need to have a smaller drawable. Button already has a background with a certain padding

Custom View with animation,color and border containing inner textview

Referring to below image, I want that view with yellow background and right border to slide in from right with some text. So this requirements include:
creating a custom view (which will need canvas I guess)
giving it width, height, position, color, border, border-color, etc.
animation to slide from right
textview within this custom view to display text
I referred this tutorial to understand how to include view with a canvas in layout. But instead of hard coded point positions, I tried following:
public MyView(Context context) {
super(context);
WindowManager wm = (WindowManager) DashBoardActivity.mContext
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
width = size.x;
height = size.y;
width -= 10;
height -= 50;
myPath = new Pt[6];
myPath[0] = new Pt(width, height);
myPath[1] = new Pt(width - 400, height);
myPath[2] = new Pt(width - 500, height - 100);
myPath[3] = new Pt(width - 400, height - 200);
myPath[4] = new Pt(width, height - 200);
myPath[5] = new Pt(width, height);
}
But view is not getting positioned as per the expectation. I tried with different hard-coded positions, but either it's getting displayed at wrong position or not getting displayed at all.
Also, to show the text, I added textview in the layout itself but it is getting displayed at top left of the screen instead of the position shown in below image.
How I can achieve this ? Any suggestions appreciated.
You dont need any custom view for this, you can set shape or 9patch image as background to the textview and animate that textview using object animator.
Border in shape xml

Setting font-size of a single word to fill the entire screen

Part of my app displays a single 5-character word in a TextView which should fill the entire screen. The questions listed below address this same issue:
How to adjust text font size to fit textview
Have TextView scale its font size to fill parent?
Text size and different android screen sizes
Auto-fit TextView for Android
However, since my case requires only one 5-character word to fill the entire screen, is there a simpler way to do this? If not, would it be practical to simply provide drawable resources (assuming that the 5-character word will always be the same)?
Thanks!
I'm going to give you some code which shows the exact opposite of what you requested. The code below shrinks a line of text until it fits within the desired area. But there is the basic idea: Get the paint of the textView and then measure it. Adjust the size and remeasure it e.g. textView.getPaint().measureText("Your text")
public static float calculateTextSizeToFit(TextView textView, String desiredText, int limitSpSize, float desiredTxtPxSize) {
Paint measurePaint = new Paint(textView.getPaint());
measurePaint.setTextSize(desiredTxtPxSize);
float pWidth = measurePaint.measureText(desiredText);
float labelWidth = textView.getWidth();
int maxLines = textView.getMaxLines();
while (labelWidth > 0 && pWidth/maxLines > labelWidth-20) {
float textSize = measurePaint.getTextSize();
measurePaint.setTextSize(textSize-1);
pWidth = measurePaint.measureText(desiredText);
if (textSize < TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, limitSpSize,
textView.getContext().getResources().getDisplayMetrics())) break;
}
return measurePaint.getTextSize();
}

Pagination in Android TextView

I have some text in a file [~100 KB] that needs to be displayed to the user in a TextView. I want to split the text into pages.
This is the idea I have in mind to implement pagination:
Determine screen width and screen height, say 320 x 480.
Calculate 75% of height, [360 px] to accommodate buttons etc.
Determine font size
Calculate number of characters [N] that can be displayed.
Read from file and display only N number of characters.
This seems like it would work, but it seems crude and error-prone. Does anyone have better ideas?
You should create your own extension of TextView and hook up into the onMeasure function which should give you the width and height (prob want to give the textview layout_weight=1)
Then you can use a paint to get the size that text will take up, not I've not tested this and you'll probably need to do something to account for splitting of newlines. But it is a good start...
Paint paint = new Paint();
Rect bounds = new Rect();
int text_height = 0;
int text_width = 0;
paint.setTypeface(Typeface.DEFAULT);
paint.setTextSize(12);// have this the same as your text size
String text = "Some random text";
paint.getTextBounds(text, 0, text.length(), bounds);
text_check_h = bounds.height(); // Will give you height textview will occupy
text_check_w = bounds.width(); // Will give you width textview will occupy

Categories

Resources