Use independent pixel density for width and height when creating a bitmap

The Bitmap.createBitmap method (int width, int height, Bitmap.Config config) just says to give it a height and width. There is no indication if these are actual pixels or dp pixels.

My questions:

1.) Are these values ​​dp pixels? 2.) If not, is there a way to use dp pixels as parameters for height and width?

Thanks.

+6
source share
3 answers

It uses pixels (regular, not dp pixels). Use the following method to convert your parameters in dp to regular pixels:

public static float dipToPixels(Context context, float dipValue) { DisplayMetrics metrics = context.getResources().getDisplayMetrics(); return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dipValue, metrics); } 

Credit: Convert dip to px in Android

+11
source

You can create a Bitmap with the width and height defined in the XML file.

This is what I did:

  • Create an XML values ​​file and name it whatever you like (drawing_dimensions.xml)
  • In the XML file:

    drawing_dimensions.xml

     <?xml version="1.0" encoding="utf-8"?> <resources> <dimen name="bitmapWidth">160dp</dimen> <dimen name="bitmapHeight">128dp</dimen> </resources> 

    this can be changed to any device you prefer to use

  • Then you need to create a link to this in your activity:

    DrawingActivity.java

     @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //onCreate..... // referencing to the dimension resource XML just created int bitmapWidth = getResources().getDimension(R.dimen.bitmapWidth); int bitmapHeight = getResources().getDimension(R.dimen.bitmapHeight); Bitmap myBitmap = Bitmap.createScaledBitmap( getResources().getDrawable(R.drawable.my_image), bitmapWidth, bitmapHeight, true); 

Hope this helps, happy coding!

+6
source

Values ​​are in pixels (normal, not dp). It is worth mentioning that in all functions that accept pixel sizes, the sizes are usually the correct pixel sizes. This is true for the width and height of the view, positions, available sizes, etc.

If you want to provide dp instead, there are many conversion functions from dp to pixels. This is a very simple formula.

If you want to decode bitmaps and change the density during the process of decoding a bitmap, look at BitmapFactory.decodeXYZ and carefully look at BitmapFactory.Options in the fields related to density. This can be useful if you want the same source bitmap (for example, a bitmap downloaded from the Internet) to have different pixel sizes on different density devices.

+3
source

Source: https://habr.com/ru/post/950936/


All Articles