Android загрузить drawable программно и изменить его размер
Как загрузить drawable из InputStream (assets, file system) и динамически изменять его размер на основе разрешения экрана hdpi, mdpi или ldpi?
исходное изображение находится в hdpi, мне нужно только изменить размер для mdpi и ldpi.
кто-нибудь знает, как Android делает динамическое изменение размеров чертежей в /res?
4 ответов
это приятно и легко (другие ответы не работали для меня), найдено здесь:
  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);
доступна документация для Android здесь.
нашел это:
  /**
   * 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;
  }
используйте так:
loadImageFromFilesystem(context, filename, DisplayMetrics.DENSITY_MEDIUM);
Если вы хотите отобразить изображение, но, к сожалению, это изображение большого размера, например, вы хотите отобразить изображение в формате 30 на 30, затем проверьте его размер, если он больше, чем требуется размер, а затем разделить его на сумму (30*30 здесь в этом случае), и то, что вы получили, снова взять и использовать для разделения области изображения снова.
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)
после загрузки изображения и установки его в imageview вы можете использовать layoutparamsto размер изображения для match_parent
такой
android.view.ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
layoutParams.width =MATCH_PARENT;
layoutParams.height =MATCH_PARENT;
imageView.setLayoutParams(layoutParams);
