简体   繁体   English

图像缩放Android

[英]Image Scaling Android

I'm showing images from gallery to Imageview. 我正在显示从图库到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. 情况1:工作。

Original Image 原始图片

Output of above code. 以上代码的输出。

Case 2: not working 情况2:无法运作

Original Image. 原始图像。

Output of above code. 以上代码的输出。

in case 2 why image is not getting scaled properly, to fill the imageview? 在情况2中,为什么无法正确缩放图像以填充imageview? Please let me know where I'm going wrong. 请让我知道我要去哪里了。

Android already provides a method to create scaled bitmap. Android已经提供了一种创建缩放位图的方法。 check this out LINK 查看此链接

Are you wanting it to stretch? 您要伸展吗? Use fitxy. 使用fitxy。

Use the scaleType attribute on your ImageView in your layout xml file. 在布局xml文件中的ImageView上使用scaleType属性。

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). 然后,您可以使用setImageUri(Uri uri)ImageView上设置图像(我假设您有要显示的图像的Uri)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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