2012-01-12 9 views
8

¿Cómo puedo cargar dibujable desde InputStream (activos, sistema de archivos) y cambiar el tamaño dinámicamente en función de la resolución de pantalla hdpi, mdpi o ldpi?Carga de Android dibujable programáticamente y cambiar su tamaño

La imagen original está en hdpi, solo necesito cambiar el tamaño para mdpi y ldpi.

¿Alguien sabe cómo Android hace el cambio de tamaño dinámico de los dibujables en/res?

+0

Por curiosidad, alguna razón para no pre-dimensionamiento de él (por 'mdpi' y' ldpi') y vinculándolo a él en el directorio 'res' –

+0

Las imágenes descargadas de la red. Puedo hacer el preprocesamiento en el servidor, pero la descarga será más lenta. – peceps

Respuesta

4

lo encontró:

/** 
    * Loads image from file system. 
    * 
    * @param context the application context 
    * @param filename the filename of the image 
    * @param originalDensity the density of the image, it will be automatically 
    * resized to the device density 
    * @return image drawable or null if the image is not found or IO error occurs 
    */ 
    public static Drawable loadImageFromFilesystem(Context context, String filename, int originalDensity) { 
    Drawable drawable = null; 
    InputStream is = null; 

    // set options to resize the image 
    Options opts = new BitmapFactory.Options(); 
    opts.inDensity = originalDensity; 

    try { 
     is = context.openFileInput(filename); 
     drawable = Drawable.createFromResourceStream(context.getResources(), null, is, filename, opts);   
    } catch (Throwable e) { 
     // handle 
    } finally { 
     if (is != null) { 
     try { 
      is.close(); 
     } catch (Throwable e1) { 
      // ingore 
     } 
     } 
    } 
    return drawable; 
    } 

uso como esto:

loadImageFromFilesystem(context, filename, DisplayMetrics.DENSITY_MEDIUM); 
+1

Desafortunadamente, este código no funciona en HTC Desire HD y HTC Evo. Vea la solución aquí: http://stackoverflow.com/questions/7747089/exception-in-drawable-createfromresourcestream-htc-only/9195531#9195531 – peceps

1

Si desea mostrar una imagen, pero por desgracia esta imagen es de gran tamaño, ejemplo permite, desea mostrar una imagen en formato 30 por 30, luego verifique su tamaño si es mayor que su tamaño requerido, luego divídalo por su cantidad (30 * 30 aquí en este caso), y lo que obtuvo es nuevamente tomar y usar para dividir nuevamente el área de la imagen .

drawable = this.getResources().getDrawable(R.drawable.pirImg); 
int width = drawable.getIntrinsicWidth(); 
int height = drawable.getIntrinsicHeight(); 
if (width > 30)//means if the size of an image is greater than 30*30 
{ 
    width = drawable.getIntrinsicWidth()/30; 
    height = drawable.getIntrinsicWidth()/30; 
} 

drawable.setBounds(
    0, 0, 
    drawable.getIntrinsicWidth()/width, 
    drawable.getIntrinsicHeight()/height); 

//and now add the modified image in your overlay 
overlayitem[i].setMarker(drawable) 
8

Ésta es agradable y fácil (las otras respuestas no estaban trabajando para mí), que se encuentra here:

ImageView iv = (ImageView) findViewById(R.id.imageView); 
    Bitmap bMap = BitmapFactory.decodeResource(getResources(), R.drawable.picture); 
    Bitmap bMapScaled = Bitmap.createScaledBitmap(bMap, newWidth, newHeight, true); 
    iv.setImageBitmap(bMapScaled); 

documentación de Android está disponible here.

0

después de cargar la imagen y la ajuste en imageview puede utilizar el tamaño layoutparamsto su imagen a match_parent

como esto

android.view.ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams(); 
layoutParams.width =MATCH_PARENT; 
layoutParams.height =MATCH_PARENT; 
imageView.setLayoutParams(layoutParams); 
Cuestiones relacionadas