viernes, 25 de julio de 2014

Android: ImageView wrap resized image.


getWomanPictureView().getViewTreeObserver().addOnGlobalLayoutListener(
    new OnGlobalLayoutListener() {

     @Override
     public void onGlobalLayout() {

      Bitmap image = getFragment().getWomanPictureBitmap(
        getWomanPictureView(), "fotito_normal");

      getWomanPictureView().setImageBitmap(image);

      removeOnGlobalLayoutListener(getWomanPictureView());
     }

     @SuppressWarnings("deprecation")
     @SuppressLint("NewApi")
     private void removeOnGlobalLayoutListener(
       final ImageView image) {

      int currentAPIVersion = android.os.Build.VERSION.SDK_INT;

      if (currentAPIVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
       image.getViewTreeObserver()
         .removeOnGlobalLayoutListener(this);
      } else {
       image.getViewTreeObserver()
         .removeGlobalOnLayoutListener(this);
      }
     }
    });

public Bitmap getWomanPictureBitmap(ImageView womanPictureView,
   String womanPicture) {

  int womanPictureResID = getActivity().getResources().getIdentifier(
    womanPicture, "drawable", getActivity().getPackageName());

  Bitmap image = BitmapFactory.decodeResource(getResources(),
    womanPictureResID);

  int width = womanPictureView.getWidth();

  if (width != 0 && width != image.getWidth()) {

   int height = width * image.getHeight() / image.getWidth();

   Bitmap scaledImage = Bitmap.createScaledBitmap(image, width,
     height, false);

   image.recycle();

   return scaledImage;

  } else {

   return image;
  }
 }

No hay comentarios:

Publicar un comentario