Search code examples
androidscale

How to fix scale of image


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.


Solution

  • 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