2012-09-13 41 views
12

Necesito cambiar el tamaño de un ImageView para que se ajuste a la pantalla y mantenga la misma relación de aspecto. Las siguientes condiciones se cumplen:Redimensionar la imagen para ajustarla a la relación de aspecto

  • Las imágenes son una anchura fija (tamaño de la anchura de la pantalla)
  • Las imágenes se descargan de Internet, es decir, tamaño sólo se pueden determinar más tarde
  • relación
  • Aspecto para cada imagen se variar; algunos son altos, otros son cuadrados, algunos son plana
  • altura
  • de ImageView tiene que cambiar, ya sea grande o más pequeña sobre la base de la relación de aspecto de la
  • altura exceso se recorta, no puede tener una gran cantidad de espacio vacío como es por defecto.

Por ejemplo, una pequeña imagen de 50x50 en una pantalla de 400 px de ancho escalaría la imagen hasta 400x400 px. Una imagen de 800x200 se escalaría a 400x100.

He observado la mayoría de los otros hilos, y muchas soluciones propuestas, como simplemente cambiar adjustViewBounds y scaleType, solo reducirán una imagen y no la ampliarán.

Respuesta

9
ImageView mImageView; // This is the ImageView to change 

// Use this in onWindowFocusChanged so that the ImageView is fully loaded, or the dimensions will end up 0. 
public void onWindowFocusChanged(boolean hasFocus) 
{ 
    super.onWindowFocusChanged(hasFocus); 

    // Abstracting out the process where you get the image from the internet 
    Bitmap loadedImage = getImageFromInternet (url); 

    // Gets the width you want it to be 
    intendedWidth = mImageView.getWidth(); 

    // Gets the downloaded image dimensions 
    int originalWidth = loadedImage.getWidth(); 
    int originalHeight = loadedImage.getHeight(); 

    // Calculates the new dimensions 
    float scale = (float) intendedWidth/originalWidth; 
    int newHeight = (int) Math.round(originalHeight * scale); 

    // Resizes mImageView. Change "FrameLayout" to whatever layout mImageView is located in. 
    mImageView.setLayoutParams(new FrameLayout.LayoutParams(
      FrameLayout.LayoutParams.WRAP_CONTENT, 
      FrameLayout.LayoutParams.WRAP_CONTENT)); 
    mImageView.getLayoutParams().width = intendedWidth; 
    mImageView.getLayoutParams().height = newHeight; 
} 
24

lo creé con la ayuda de esta respuesta de Bob Lee en este post: Android: How to stretch an image to the screen width while maintaining aspect ratio?

package com.yourpackage.widgets; 

import android.content.Context; 
import android.util.AttributeSet; 
import android.widget.ImageView; 

public class AspectRatioImageView extends ImageView { 

    public AspectRatioImageView(Context context) { 
     super(context); 
    } 

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

    public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
    } 

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
     int width = MeasureSpec.getSize(widthMeasureSpec); 
     int height = width * getDrawable().getIntrinsicHeight()/getDrawable().getIntrinsicWidth(); 
     setMeasuredDimension(width, height); 
    } 
} 

Ahora utilizarlo en el XML:

<com.yourpackage.widgets.AspectRatioImageView android:layout_centerHorizontal="true" 
    android:src="@drawable/yourdrawable" android:id="@+id/image" 
    android:layout_alignParentTop="true" android:layout_height="wrap_content" 
    android:layout_width="match_parent" android:adjustViewBounds="true" /> 

Que se diviertan!

+4

+1, agradable y simple, sólo se me protegerlo contra 'getIntrinsicWidth' siendo 0 (se bloqueará al tratar de dividir por él) –

+0

ajustarViewViews también se debe hacer en AspectRatioImageView http://developer.android.com/reference/android/widget/ImageView.html#setAdjustViewBounds%28boolean%29 – Nepster

1

prefiero la respuesta de Agarwal, con algunas modificaciones, ya que es resuable:

package com.yourpackage.widgets; 

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

public class AspectRatioImageView extends ImageView { 

    public AspectRatioImageView(Context context) 
    {  
     super(context); 
     this.setScaleType(ScaleType.FIT_XY); 
    } 

    public AspectRatioImageView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     this.setScaleType(ScaleType.FIT_XY); 
    } 

    public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     this.setScaleType(ScaleType.FIT_XY); 
    } 

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

     if (d != null && d.getIntrinsicWidth() > 0) 
     { 
      int width = MeasureSpec.getSize(widthMeasureSpec); 
      if (width <= 0) 
       width = getLayoutParams().width; 

      int height = width * d.getIntrinsicHeight()/d.getIntrinsicWidth(); 
      setMeasuredDimension(width, height); 
     } 
     else 
      super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
    } 
} 

Ahora utilizarlo en el XML:

<com.yourpackage.widgets.AspectRatioImageView 
android:src="@drawable/yourdrawable" 
android:layout_height="wrap_content" 
android:layout_width="match_parent"/> 
Cuestiones relacionadas