MOHRE
MOHRE

Reputation: 1156

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.

Upvotes: 2

Views: 301

Answers (2)

Xu Zhang
Xu Zhang

Reputation: 64

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

Upvotes: 1

Milad Faridnia
Milad Faridnia

Reputation: 9477

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"

Upvotes: 0

Related Questions