根据显示尺寸自动调整图像大小

时间:2015-01-14 13:16:02

标签: android

在我的应用程序中,我有Activity来显示用户个人资料。用户可以通过从设备相机图片或Facebook图片等中选择它来设置其个人资料图片。但是这些图片可能非常大,所以如果它们太大,我需要以某种方式自动缩放pcitures。

修改

由于回答了我的问题,我尝试了一些东西。我创建了一些Helper方法:

public static int getDisplayWidth(Activity activity) {
    DisplayMetrics displaymetrics = new DisplayMetrics();

    activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

    return displaymetrics.widthPixels;
}

public static int getDisplayHeight(Activity activity) {
    DisplayMetrics displaymetrics = new DisplayMetrics();

    activity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);

    return displaymetrics.widthPixels;
}

public static int getDrawableWith(Context context, int id) {
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), id);

    return bitmap.getWidth();
}

public static int getDrawableHeight(Context context, int id) {
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), id);

    return bitmap.getHeight();
}

public static int getHeightOfImage(int originalWidth, int originalHeight, int targetWidth) {
    double ratio = ((double)originalWidth / (double)originalHeight);

    return (int)(targetWidth / ratio);
}

我现在尝试创建一个调整大小的drawable并将其设置为我的imageview:

RelativeLayout.LayoutParams layoutParamsView = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);

this.setLayoutParams(layoutParamsView);

int originalWidth = Helper.getDrawableWith(this.getContext(), R.drawable.background_wave);
int originalHeight = Helper.getDrawableHeight(this.getContext(), R.drawable.background_wave);

int targetWidth = Helper.getDisplayWidth((Activity)this.getContext());
int targetHeight = Helper.getHeightOfImage(originalWidth, originalHeight, targetWidth);

RelativeLayout.LayoutParams layoutParamsImageview = new RelativeLayout.LayoutParams(targetWidth, targetHeight);
layoutParamsImageview.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutParamsImageview.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

Drawable drawable = Helper.getScaledDrawable(this.getContext(), R.drawable.background_wave, targetWidth, targetHeight);

this.imageViewBackgroundWave = new ImageView(this.getContext());
this.imageViewBackgroundWave.setLayoutParams(layoutParamsImageview);
this.imageViewBackgroundWave.setImageDrawable(drawable);

this.addView(this.imageViewBackgroundWave);

这可以很好地根据显示尺寸调整图像大小。

1 个答案:

答案 0 :(得分:1)

最简单的方法是将Bitmap转换为Drawable以进行缩放。

How to convert a Bitmap to Drawable in android?

虽然记住记忆(这是你的第一个"解决方案") - 大图像,即使"缩放"作为一个drawable将消耗大量的内存。