Set drawable size programmatically in java

Set drawable size programmatically in java

To set the size of a Drawable programmatically in Java, you can create a scaled version of the drawable with the desired dimensions. You can achieve this using the Bitmap class to resize the drawable and then set the resized drawable to an ImageView or use it as needed. Here's an example of how to do this:

import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.widget.ImageView; public class ResizeDrawable { public static void setDrawableSize(Context context, int drawableResourceId, int width, int height, ImageView imageView) { // Load the original drawable Drawable originalDrawable = context.getResources().getDrawable(drawableResourceId); // Convert the drawable to a Bitmap Bitmap originalBitmap = ((BitmapDrawable) originalDrawable).getBitmap(); // Resize the Bitmap to the desired width and height Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, width, height, false); // Convert the resized Bitmap back to a Drawable Drawable resizedDrawable = new BitmapDrawable(context.getResources(), resizedBitmap); // Set the resized drawable to an ImageView or use it as needed imageView.setImageDrawable(resizedDrawable); } } 

In this example:

  1. Load the original drawable using context.getResources().getDrawable(drawableResourceId). Replace drawableResourceId with the ID of the drawable you want to resize.

  2. Convert the original drawable to a Bitmap using ((BitmapDrawable) originalDrawable).getBitmap().

  3. Resize the Bitmap to the desired width and height using Bitmap.createScaledBitmap(originalBitmap, width, height, false).

  4. Convert the resized Bitmap back to a Drawable using new BitmapDrawable(context.getResources(), resizedBitmap).

  5. Set the resized drawable to an ImageView using imageView.setImageDrawable(resizedDrawable) or use it as needed.

You can call the setDrawableSize method to set the size of a drawable programmatically. For example:

ImageView imageView = findViewById(R.id.imageView); int desiredWidth = 200; // Set your desired width int desiredHeight = 200; // Set your desired height int drawableResourceId = R.drawable.your_drawable; // Replace with your drawable resource ID ResizeDrawable.setDrawableSize(this, drawableResourceId, desiredWidth, desiredHeight, imageView); 

Replace R.drawable.your_drawable with the actual resource ID of the drawable you want to resize, and adjust desiredWidth and desiredHeight to your desired dimensions.


More Tags

laravel-5.6 mahapps.metro libavcodec aws-powershell prometheus-operator capslock angle readonly kubernetes-helm navigator

More Java Questions

More Electrochemistry Calculators

More Everyday Utility Calculators

More Mortgage and Real Estate Calculators

More Entertainment Anecdotes Calculators