4

I have been struggling with what I think is something simple. I am setting an image on an image button using a class. I want the image to fit the constraints of the screen, but without stretching. That is, if it's too wide to fit the screen, I want the height to be scaled to accommodate so that it doesn't get stretched. And if the height is too tall, I want the image height to be reduced, thereby shrinking the width too.

I have seen this question asked a couple times and I have tried every bit of the advice, but it makes absolutely no difference for me. I think this may have something to do with usnig an ImageButton instead of an ImageView?

Here are some relevant chunks of code (badly broken) ...

In my class:

          ImageView img = (ImageButton) dialog.findViewById(R.id.fullsizeimage);
          img.setScaleType(ImageView.ScaleType.CENTER_INSIDE);  //Changing ScaleType here has no effect
          img.setImageBitmap(useThisBitmap);

And here is the xml layout contents ...

 <?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<ImageButton
    android:id="@+id/fullsizeimage"
    android:background="@null"
    android:layout_width="wrap_content" 
    android:layout_height="fill_parent"
    android:adjustViewBounds="true"
    />

 </RelativeLayout>

Some of that junk in the XML file is probably wrong. But I have changed it so many times, and it has ZERO effect.

Any and all advise is greatly appreciated.

RayHaque
  • 171
  • 1
  • 4
  • 9

1 Answers1

3

I think that ImageButton will always stretch the background image in order to fill its whole background. An ImageView can be easily made clickable on its own, have you tried that?

A more complicated option is to use a custom view which can draw your image on canvas any way you like and can have onTouch listener.

Lumis
  • 21,517
  • 8
  • 63
  • 67
  • That would make sense. I see that ScaleType does not apply to an ImageButton (or so thinks the SDK). So I changed it to an ImageView. That looks a little better anyway. But ... setting the ScaleType has no effect. Nor does it have any effect when I enter it into the XML file (i.e. android:scaleType="centerCrop"). This is driving me nuts. :-) – RayHaque Mar 13 '11 at 18:12
  • Turns out I am a fool! Earlier in my code I was doing this: `Bitmap useThisBitmap = Bitmap.createScaledBitmap(bitmap, parent.getWidth(), parent.getHeight(), true);` and then below that: `Bitmap bitmap = BitmapFactory.decodeStream(bis);`. The first piece of code was an experiment that didn't work, but if you look at my code above you will see that I was still referencing it. I just changed this one line and now my ScaleType is working ... `img.setImageBitmap(bitmap); // not useThisBitmap!` Thanks for the help Lumis. – RayHaque Mar 13 '11 at 22:45