How to set image to an image button - android

I have taken an image button with the following code:
skin = new Skin(Gdx.files.internal("glassy-ui.json"));
button2 = new ImageButton(skin);
myTexture = new Texture(Gdx.files.internal("PlayButton.png"));
myTextureRegion = new TextureRegion(myTexture);
myTexRegionDrawable = new TextureRegionDrawable(myTextureRegion);
button2.getStyle().imageUp = new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("PlayButton.png"))));
button2.addListener(new InputListener(){
#Override
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
game.dispose();
game.setScreen(new GameScreen(game));
return true;
}
});
stage.addActor(button2);
I want to set image in imagebutton as drawable,Refer this link for further understanding . How can I do that? What I also want to do is that there is any visible reaction to an users input like changing its size etc..
By the way, the image is round.

ImageButtonStyle imgBtnStyle=new ImageButtonStyle();
imgBtnStyle.imageUp=new SpriteDrawable(spriteUp);
imgBtnStyle.imageDown=new SpriteDrawable(spriteDown);
ImageButton imgBtn=new ImageButton(imgBtnStyle);
Add Image button to stage. Do whatever animation(actions) you want to do, on this ImageButton Actor.

You can add the image in imagebutton like,
then try this
Drawable img = getContext().getResources().getDrawable( R.drawable.smiley );
yourimagebutton.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null);

To fill the image in button, set Scale type FitXY.
button2.setScaleType(ImageView.ScaleType.FIT_XY);
or To put the image in center of the button, set Scale type FitCenter.
button2.setScaleType(ImageView.ScaleType.FIT_CENTER);

Related

Limit Image to size of containing view (xamarin.android)

I'm trying to create a chess board using a GridLayout in Xamarin.Android. Each View in the GridLayout will be an image view depicting a piece (if the square contains a piece). Before adding the image resource, the board displays fine. But as soon as an image is added, it pushes the size of the ImageView to be much larger than desired.
Here is the code I am using. The following method is run for each square on the board and creates the ImageView and returns it to be added to the GridLayout:
public View BuildSquare(Square squareModel)
{
SquareView rtn = new SquareView(this.Activity, squareModel); //SquareView extends ImageView
rtn.UpdateBackgroundColor(); //set square color
if (squareModel.Piece != null)
{
rtn.DrawPiece();
}
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
//set weight of each row and column to ensure equal size
param.RowSpec = GridLayout.InvokeSpec(GridLayout.Undefined, 1f);
param.ColumnSpec = GridLayout.InvokeSpec(GridLayout.Undefined, 1f);
rtn.LayoutParameters = param;
return rtn;
}
and the DrawPiece() method is as follows, which sets the image resource:
public void DrawPiece()
{
if (squareModel.Piece == null) return;
string key = squareModel.Piece.GetPieceNotation();
int resource = -1;
//get the image resource corresponding to the piece on the ssquare
if (AndroidConstants.PieceResources.TryGetValue(key, out resource))
{
this.SetImageResource(resource);
}
this.SetScaleType(ScaleType.FitXy);
}
When I comment out the rtn.DrawPiece() line, the board displays correctly as shown below:
However, when the line is included and the image resource is set, it displays as follows:
What you are seeing here is the top left square on the board hugely inflated to accommodate the image. I want the image to be scaled to fit in the square in the first image above. I have tried with different ScaleTypes but it seems to make no difference. Is this something to do with using the GridLayout? Or is there something else going on here that I'm missing?
I think you need to set the height and width to your SquareView.
For example:
public View BuildSquare(Square squareModel)
{
SquareView rtn = new SquareView(this, squareModel); //SquareView extends ImageView
rtn.UpdateBackgroundColor(); //set square color
if (squareModel.Piece ==0)
{
rtn.DrawPiece();
}
//Set the height and width
GridLayout.LayoutParams param = new GridLayout.LayoutParams(new ViewGroup.LayoutParams(50, 50));
//set weight of each row and column to ensure equal size
param.RowSpec = GridLayout.InvokeSpec(GridLayout.Undefined, 1f);
param.ColumnSpec = GridLayout.InvokeSpec(GridLayout.Undefined, 1f);
rtn.LayoutParameters = param;
return rtn;
}
And the result:

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

(ANDROID) ImageView won't position correctly

I have an Android related issue:
I am trying to centre a logo on the screen of my device, but it won't position correctly.
I am using the following function:
public void ImageCentered(int ID){
ImageView iv = (ImageView) findViewById(ID);
int x = 0;
int y = 0;
RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
x = (screenWidth/2)-(iv.getWidth()/2);
y = (screenHeight/2)-(iv.getHeight()/2);
position.setMargins(x, y, 0, 0);
iv.setLayoutParams(position);
}
This could should work,but it won't. The image is set off slightly to the right and bottom like in this image:
https://www.dropbox.com/s/tf7r1u1xqcmb9t9/2014-08-16%2018.36.04.png
Now, the strange thing is, when I use the following code:
public void ImageCentered(int ID){
ImageView iv = (ImageView) findViewById(ID);
int x = 0;
int y = 0;
RelativeLayout.LayoutParams position = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
x = (screenWidth/2)-(iv.getWidth()/2);
y = (screenHeight/2)-(iv.getHeight()/2);
position.setMargins(x, y, 0, 0);
Message(IntToStr(x)+", "+IntToStr(y));
iv.setLayoutParams(position);
}
this is the result:
https://www.dropbox.com/s/mjw80zlzkav6dzs/2014-08-16%2018.41.16.png
Side note: The text in the Message() function does not matter, nor does its position within the ImageCentered() function.
I am not calling the function in my OnCreate(), as the width and height of the image would always return 0, so I looked something up and found this:
#Override
public void onWindowFocusChanged(boolean hasFocus){
ImageCentered(R.id.image);
}
This piece of code is in my MainActivity.java file, whereas the ImageCentered() function is in my UtilLib.java file.
So, I was wondering: What's going on here? Why does the code work when I pop in a Message() but not when I leave it out?
Sure, I can try hardcoding the data, but what about smaller/bigger screens?
I hope an Android guru can help me out here, as I've been struggling with this for quite some time now.
EDIT
Just noticed something interesting when pressing "OK" on my Message:
https://www.dropbox.com/s/a7lu6588hy1opw7/2014-08-16%2018.51.55.png
My guess is that my problem lies there, but after clicking the "OK" button once more, the data is "492, 207" again. scratches head
Assuming rom your code that the ImageView is inside a RelativeLayout, You could also do:
// get imageview layout params or create new ones
RelativeLayout.LayoutParams params = imageView.getLayoutParams();
params.addRule(RelativeLayout.CENTER_HORIZONTAL);
this way the image will be automatically centered without all those manual calculations!.
You can also specify it in the XML with
<ImageView .....
android:layout_centerHorizontal="true"/>
I've ultimately decided to just hardcode the x and y coordinates, and later on use some sort of scaling-conversion to position them properly, unless someone can provide me with a better method of fixing this.
UPDATE
So, after googling after a while (again), I have finally found the answer and created two functions:
public int GetImageHeight(int ID){
ImageView iv = (ImageView)findViewById(ID);
iv.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
iv.layout(0, 0, iv.getMeasuredWidth(), iv.getMeasuredHeight());
return iv.getMeasuredHeight();
}
public int GetImageWidth(int ID){
ImageView iv = (ImageView)findViewById(ID);
iv.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
iv.layout(0, 0, iv.getMeasuredWidth(), iv.getMeasuredHeight());
return iv.getMeasuredWidth();
}
All you have to do is pass the ID of the image you made in your xml file, like so:
GetImageHeight(R.id.logo)

How to set Top padding for image of a dynamic button with image and text

I have looked at various questions on this but, couldn't get them work.
I have a button, with a background, image on top and text at the bottom. The button is dynamic and hence NO XML is available.
Code for the dynamic button:
final Button image = new Button(this);
image.setTag(i);
image.setText(buttonsList[i].toUpperCase());
image.setGravity(Gravity.CENTER);
image.setBackgroundColor(getResources().getColor(R.color.dark_grey));
if (i == Const.MainIndex.FESTIVAL_OUTLOOK_INDEX) {
try {
XmlResourceParser parser = getResources().getXml(
R.color.text_color_green);
ColorStateList colors = ColorStateList.createFromXml(
getResources(), parser);
image.setTextColor(colors);
} catch (Exception e) {
}
//setting this value to -ve decreases the
//gap between the image and text
image.setCompoundDrawablePadding(-100);
image.setCompoundDrawablesWithIntrinsicBounds(
null,
getResources().getDrawable(
R.drawable.sidemenu_image_festout), null, null);
image.setBackgroundResource(R.drawable.button_background_green);
}
Here is how the image looks now..
I want to set padding on TOP of the image. So that the image doesn't look to close to the border of the button. How can I achieve this?
I have tried setting image.setPadding(0,10,0,0) but no effect.
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(left, top, right, bottom);
imageView.setLayoutParams(lp);
use this

How to size imagebutton to exactly the same size as its source image?

I have programatically created a set of ImageButton views (with transparent background) as map pins on a static map (ImageView) defined in my app. At certain locations on the map, there are a few ImageButtons that are quite close to each other. I have noticed that in such situation even I am clicking on button 1, the app will think that button 2 is being clicked on and thus proceed to run the activity associated with button 2. Turning off transparency on these buttons reveals that the buttons are actually much bigger than the associated source images and thus some of these buttons have overlapped.
How do I define the imagebuttons such that they are size to the same size as the source images?
Here is a snapshot of relevant code under onCreate():
ImageButton btnMapLoc = new ImageButton(ResultMapActivity.this);
RelativeLayout.LayoutParams vp = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
vp.setMargins(x,y,0,0); // [left, top, right, bottom] - in pixels
btnMapLoc.setLayoutParams(vp);
//btnMapLoc.setBackgroundColor(Color.TRANSPARENT);
btnMapLoc.requestLayout();
String imgNameNormal = "map_loc_" + mapLocation + "_normal"; //e.g. map_loc_10_normal
int idNormal = getResources().getIdentifier(imgNameNormal,"drawable",getPackageName());
String imgNameClick = "map_loc_" + mapLocation + "_click"; //e.g. map_loc_10_click
int idClick = getResources().getIdentifier(imgNameClick,"drawable",getPackageName());
btnMapLoc.setImageResource(idNormal);
rl.addView(btnMapLoc, vp);
// Change image as the state of the button changed (normal vs. clicked)
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {-android.R.attr.state_pressed},getResources().getDrawable(idNormal)); // Note the "-"
states.addState(new int[] {android.R.attr.state_pressed},getResources().getDrawable(idClick));
btnMapLoc.setImageDrawable(states);
Thanks.
Try this, it works for me.
Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.testbild);
ImageButton btnMapLoc = (ImageButton) findViewById(R.id.imageButton1);
LayoutParams lp = new LayoutParams(image.getWidth(), image.getHeight());
btnMapLoc.setLayoutParams(lp);
btnMapLoc.setImageBitmap(image);
I would simply use an ImageView instead, which is exactly the same size as the image in it by default. Or is there anything you need that an ImageButton can do and an ImageView can't?

Categories

Resources