How to convert a Drawable to a Bitmap?

前端 未结 20 2822
攒了一身酷
攒了一身酷 2020-11-21 22:46

I would like to set a certain Drawable as the device\'s wallpaper, but all wallpaper functions accept Bitmaps only. I cannot use WallpaperMan

20条回答
  •  清歌不尽
    2020-11-21 23:27

    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;
    }
    

提交回复
热议问题