2

I want to have a ImageView of fixed x / y ratio on all of the screens. for example famous 16/9 ratio. And I also want that The ImageView be as large as possible. how could I do it in android? Thanks a lot.

MOHRE
  • 1,096
  • 4
  • 15
  • 28

2 Answers2

1

The above answer will alter the aspect ratio.

You cannot achieve your goal by only modifying the xml layout file. You have to do this in Java code.

The basic steps are:

  1. read your image file into a Bitmap, and obtain the initial width and height and aspect ratio of the Bitmap.
  2. calculate the scaling factors for x and y dimension respectively, and use the smaller one of the two factors to scale your image

    factorX= ScreenWitdhInPixel/ImgWidth
    factorY= ScreenHeightInPixel/ImgHeight
    factor= (factorX<factorY?factorX:factorY)

  3. scale your image up using the factor value calculated in step 2

    Matrix matrix = new Matrix(); matrix.postScale(factor, factor); Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);

Please refer to this post for a full example: ImageView fit without stretching the image

Community
  • 1
  • 1
Xu Zhang
  • 64
  • 5
0

You must set android:scaleType="fitXY" to your imageView.

And if you want your ImageView be as large as its parent, you can write this lines of codes:

android:layout_width="match_parent"
android:layout_height="match_parent"
Milad Faridnia
  • 9,113
  • 13
  • 65
  • 78