简体   繁体   中英

Image Scaling Android

I'm showing images from gallery to Imageview.

I'm using below code

 Bitmap background = Bitmap.createBitmap((int) width, (int) height, Bitmap.Config.ARGB_8888);
                float originalWidth = bMap.getWidth(), originalHeight = bMap.getHeight();
                Canvas canvas = new Canvas(background);
                float scale = width/originalWidth;
                float xTranslation = 0.0f, yTranslation = (height - originalHeight * scale)/2.0f;
                Matrix transformation = new Matrix();
                transformation.postTranslate(xTranslation, yTranslation);
                transformation.preScale(scale, scale);
                Paint paint = new Paint();
                paint.setFilterBitmap(true);
                canvas.drawBitmap(bMap, transformation, paint);
                imageView1.setImageBitmap(background);

Case 1: working.

Original Image

Output of above code.

Case 2: not working

Original Image.

Output of above code.

in case 2 why image is not getting scaled properly, to fill the imageview? Please let me know where I'm going wrong.

Android already provides a method to create scaled bitmap. check this out LINK

Are you wanting it to stretch? Use fitxy.

Use the scaleType attribute on your ImageView in your layout xml file.

Example:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="centerCrop" />

Then you can set your image on the ImageView using setImageUri(Uri uri) (I assume you have the Uri of the image to show).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM