anu_r
anu_r

Reputation: 1622

Why isn't my Image setting to a Square in my ImageView in Android?

I am trying to set an Image retrieved from my sdcard in a Square shape in an ImageView of 48 by 48dp. I have done the following coding but the Image still sets to Rectangle.Can anyone tell me step by step what to do?

  Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
  Bitmap myBitmap = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Bitmap.Config.ARGB_8888);
  Paint paint = new Paint();
  Canvas cc = new Canvas(myBitmap);
  cc.drawRect(48,48,48,48, paint);
  frndsimag.setImageBitmap(bmp);

Upvotes: 0

Views: 298

Answers (2)

Damian Petla
Damian Petla

Reputation: 9103

I see 2 issues with this code. First of all, you are passing to ImageView original bitmap bmp instead myBitmap. Secondly, New bitmap has same size as original. If you didn't set android:scaleType for your ImageView it will use the same amount of space.

To achieve your goal I would do the following. Assuming you are defining ImageView in XML layout, set android:width and android:height to 48dp and android:scaleType=fitXY to fill entire space or centerInside if you wish to keep original ratio.

Then your code could be shrink to this:

Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
frndsimag.setImageBitmap(bmp);

In case your images are large it would be wise to use optimization techniques from this page http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

Upvotes: 1

ssantos
ssantos

Reputation: 16526

Just guessing, but the ImageView frndsimag could just have rectangular shape, and the image displayed would be stretching to fill the space.

Hard to say without seeing the layout xml, but you could try changing frndsimag scaleType, for instance.-

frndsimag.setScaleType(ScaleType.CENTER);

Upvotes: 1

Related Questions