Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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.

like image 338
Dick Lucas Avatar asked Aug 02 '13 22:08

Dick Lucas


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

like image 138
Ryan S Avatar answered Oct 06 '22 01:10

Ryan S


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!

like image 34
MattMatt Avatar answered Oct 06 '22 01:10

MattMatt


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.

like image 25
talkol Avatar answered Oct 05 '22 23:10

talkol