Android createBitmap使用哪种资源大小?

Android createBitmap使用哪种资源大小?,android,bitmap,Android,Bitmap,我从图片的垂直部分创建位图。但我只想显示20%的图片,并在资源文件夹中有多种大小。当我使用静态像素时,结果是错误的 Bitmap SOURCE_BITMAP = BitmapFactory.decodeResource(getResources(), R.drawable.bg_main); int START_Y = 15; int HEIGHT_PX = 500; // Crop bitmap Bitmap newBitmap = Bitmap.createBitmap(SOURCE_BI

我从图片的垂直部分创建位图。但我只想显示20%的图片,并在资源文件夹中有多种大小。当我使用静态像素时,结果是错误的

Bitmap SOURCE_BITMAP = BitmapFactory.decodeResource(getResources(), R.drawable.bg_main);
int START_Y = 15;
int HEIGHT_PX = 500;

// Crop bitmap
Bitmap newBitmap = Bitmap.createBitmap(SOURCE_BITMAP, 0, START_Y, SOURCE_BITMAP.getWidth(), HEIGHT_PX, null, false);

// Assign new bitmap to ImageView
ImageView image = (ImageView)findViewById(R.id.iv_bg);
image.setImageBitmap(newBitmap);
我的想法是用
(int)(SOURCE\u BITMAP.getHeight()*0.2f)分配
HEIGHT\u PX
但是没有更好的方法来创建位图而不声明像素(=相对于大小)

  • 您可以使用已加载的位图来确定20%是多少,因为位图的大小已包含密度信息(在xhdpi屏幕上,同一图像的像素数是mdpi屏幕上的两倍)
  • 或者,您可以使用显示密度将绝对像素值转换为考虑屏幕逻辑密度的值。绝对像素值将与160dpi屏幕上的mdpi位图相关
  • 要从像素15开始获得20%的位图,请执行以下操作:

    // retrieve screen density
    Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics( metrics );
    float density = metrics.density;
    
    // read Bitmap from resources
    Bitmap source = BitmapFactory.decodeResource(getResources(), R.drawable.bg_main);
    int y = Math.round(15f * density);
    int height = Math.round(source.getHeight() * 0.2f);
    
    // Crop bitmap
    Bitmap newBitmap = Bitmap.createBitmap(source, 0, y, source.getWidth(), height);