9

The Bitmap.createBitmap(int width, int height, Bitmap.Config config) method simply says to give it a height and a 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 any way to use dp pixels as parameters for the height and width?

Thank you.

Dick Lucas
  • 12,289
  • 14
  • 49
  • 76

3 Answers3

17

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

Community
  • 1
  • 1
Ryan S
  • 4,549
  • 2
  • 21
  • 33
7

You can create a Bitmap with Width and Height defined in an XML file.

This is what I did:

  • Make an XML Values file and name it whatever you like (drawing_dimensions.xml)
  • Within 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 whichever unit you prefer to use

  • Then you only need to create a reference 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);
    

I hope this helps, happy coding!

MattMatt
  • 905
  • 6
  • 19
3

The values are in pixels (regular, not dp). It's worth a mention that in all functions which accept pixel sizes, the sizes are usually regular pixel sizes. This is true for view widths and heights, positions, drawable sizes, etc.

If you wish to provide dp instead, there are plenty of conversion functions from dp to pixels out there. It's a very straight forward formula.

If you wish to decode bitmaps and change density during the bitmap decode process, take a look at BitmapFactory.decodeXYZ and look closely at BitmapFactory.Options at the Density related fields. This could be useful if you want the same source bitmap (a bitmap downloaded from the web for example) to have a different pixel size on different density devices.

talkol
  • 12,564
  • 11
  • 54
  • 64