如何缩放设备宽度的图像宽度?

时间:2017-05-16 07:17:27

标签: android image image-processing

我在图库中获取图片,但有些图片宽度不适合设备宽度,因此如何将图片宽度设置为ImageView中的设备宽度,但原始图片高度的高度相同。

下面是我在此设置的图片代码

Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
    String path = getPathFromURI(selectedImageUri);
    Log.i("", "Image Path : " + path);
     // Set the image in ImageView
      try {
       bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
           } catch (IOException e) {
               e.printStackTrace();
           }
           imgEdit.setImageURI(selectedImageUri);
        }

5 个答案:

答案 0 :(得分:1)

你必须扩展ImageView,这将是match_parent宽度和比例高度:

package com.yourpackage.ui;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class DynamicImageView extends ImageView {

public DynamicImageView(final Context context, final AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
    final Drawable d = this.getDrawable();

    if (d != null) {
        final int width = MeasureSpec.getSize(widthMeasureSpec);
        final int height = (int) Math.ceil(width * (float) d.getIntrinsicHeight() / d.getIntrinsicWidth());
        this.setMeasuredDimension(width, height);
    } else {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}
}

然后在您的XML布局中:

<com.yourpackage.ui.DynamicImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop"/>

答案 1 :(得分:0)

使用此功能,请根据需要更改宽高比

 Display display = ((NavigationHome) context).getWindowManager().getDefaultDisplay();
    int width = display.getWidth(); // deprecated
    int height = display.getHeight();
    int sliderHeight = (int) ((width) / 2.4);
        if (height != 0)
            imageView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,sliderHeight));

答案 2 :(得分:0)

试试这个

imageView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT));

或者如果你想填充宽度

imageView.setLayoutParams(new LayoutParams((LayoutParams.FILL_PARENT,LayoutParams.MATCH_PARENT));

答案 3 :(得分:0)

用它更改图像视图。

 <ImageView
        android:id="@+id/background"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:scaleType="fitXY"

        />

答案 4 :(得分:-1)

尝试将高度设置为match_parent

类似

<ImageView
     android:layout_width="match_parent"
     android:layout_height="50dp"/>