ioan ghip
ioan ghip

Reputation: 1222

ImageView shrinks when image is replaced with another image of same size

I have an imageView in a RelativeLayout and at design time I load from resources a 144x144 png image and everything looks good:

enter image description here

Now, in code, I take a picture with the camera and crop it to 144x144 and load it into the image view:

imageViewMyPicture.setImageBitmap(bitmap);

but now the imageView shrinks:

enter image description here

Both picture have 100% same size, 144x144 and if I load the second picture into the imageView at design time, the size is loaded normally.

What am I doing wrong?

Upvotes: 0

Views: 196

Answers (2)

Submersed
Submersed

Reputation: 8870

You need to account for density when creating your scaled bitmap. Since your ImageView has the correct dimensions before setting the new bitmap, in your case you could just use the dimensions of your ImageView when scaling the new Bitmap... For example:

I'll assume you're using Uris to retrieve the stored image from the file system after it's been taken. If you're using Files, just use Uri.fromFile(file) to get the Uri. I normally use an AsyncTask to accomplish this since you should do Bitmap processing off of the main thread...here's some sudo code (not in an AsyncTask for simplicity, but easily refactored):

//Somewhere in your Activity

public void scaleAndSetBitmap(ImageView imageView, Uri uri){
            InputStream stream = null;
            Bitmap bitmap = null;

            try { 
             stream = getContentResolver().openInputStream(uri);
             bitmap = BitmapFactory.decodeStream(stream, null, options);

              if (image_view != null && bitmap != null) {
                bitmap = Bitmap.createScaledBitmap(bitmap, image_view.getWidth(), image_view.getHeight(), true);
                image_view.setImageBitmap(bitmap);
              } 
            } catch(Exception e){
                e.printStackTrace();
                return;
            } finally {
                try{
                    stream.close();
                } catch(IOException i){
                    return;
                }
            }
}

Upvotes: 1

Martin
Martin

Reputation: 4816

Make sure that when you load images you take into account the density of the device you're running on. You make think you have 144x144, but that could be the raw image file, but when put on a device that is high density it will be rendered at closer to 200x200. Then, when you cut a camera image out as 144x144 you have the raw size, but not the adjusted-for-density size. The easist way to make sure you get that is to read images using resources:

For example, loading a bitmap with this signature means the app will read the image with the right density and give it the size you need for that device.

   selectImg = BitmapFactory.decodeResource(getResources(), R.drawable.drop_device);

Upvotes: 1

Related Questions