I would like to set a certain Drawable
as the device\'s wallpaper, but all wallpaper functions accept Bitmap
s only. I cannot use WallpaperMan
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon);
This will not work every time for example if your drawable is layer list drawable then it gives a null response, so as an alternative you need to draw your drawable into canvas then save as bitmap, please refer below a cup of code.
public void drawableToBitMap(Context context, int drawable, int widthPixels, int heightPixels) {
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/", "drawable.png");
FileOutputStream fOut = new FileOutputStream(file);
Drawable drw = ResourcesCompat.getDrawable(context.getResources(), drawable, null);
if (drw != null) {
convertToBitmap(drw, widthPixels, heightPixels).compress(Bitmap.CompressFormat.PNG, 100, fOut);
}
fOut.flush();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap convertToBitmap(Drawable drawable, int widthPixels, int heightPixels) {
Bitmap bitmap = Bitmap.createBitmap(widthPixels, heightPixels, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, widthPixels, heightPixels);
drawable.draw(canvas);
return bitmap;
}
above code save you're drawable as drawable.png in the download directory
Use this code.it will help you for achieving your goal.
Bitmap bmp=BitmapFactory.decodeResource(getResources(), R.drawable.profileimage);
if (bmp!=null) {
Bitmap bitmap_round=getRoundedShape(bmp);
if (bitmap_round!=null) {
profileimage.setImageBitmap(bitmap_round);
}
}
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
int targetWidth = 100;
int targetHeight = 100;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth),
((float) targetHeight)) / 2),
Path.Direction.CCW);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth, targetHeight), new Paint(Paint.FILTER_BITMAP_FLAG));
return targetBitmap;
}