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.
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
You can create a Bitmap
with Width and Height defined in an XML file.
This is what I did:
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With