Thursday 5 December 2013

Set Wallpaper using drawable image

To set wallpaper in android using the image from drawable folder in application source, too fit the full image view in the screen size of the device


WallpaperManager myWallpaperManager = WallpaperManager
                            .getInstance(inflater.getContext());
                    Bitmap bitmap1 = BitmapFactory.decodeStream(getResources().openRawResource(image));
                    Display display = getActivity().getWindowManager().getDefaultDisplay();
                    Point size = new Point();
                    display.getSize(size);
                    int width = size.x;
                    int height = size.y;
                    Bitmap bitmap = Bitmap.createScaledBitmap(bitmap1, width,
                            height, true);
                    try {
                        //set wallpaper picture from resource here

                        if((myWallpaperManager.getDesiredMinimumWidth()>0)&&(myWallpaperManager.getDesiredMinimumHeight()>0))
                        {

                            Bitmap blank = BitmapHelper.createNewBitmap(myWallpaperManager.getDesiredMinimumWidth(), myWallpaperManager.getDesiredMinimumHeight());
                            Bitmap overlay = BitmapHelper.overlayIntoCentre(blank, bitmap);

                            myWallpaperManager.setBitmap(overlay);
                        }
                        else
                        {
                            myWallpaperManager.setBitmap(bitmap);
                        }
                        Toast.makeText(getActivity().getBaseContext(),"Wallpaper successfully set",3000).show();
                        dialog.dismiss();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }


public static class BitmapHelper {

            public static Bitmap overlayIntoCentre(Bitmap bmp1, Bitmap bmp2) {
                Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
                Canvas canvas = new Canvas(bmOverlay);
                canvas.drawBitmap(bmp1, new Matrix(), null);//draw background bitmap

                //overlay the second in the centre of the first
                //(may experience issues if the first bitmap is smaller than the second, but then why would you want to overlay a bigger one over a smaller one?!)
                canvas.drawBitmap(bmp2, (bmp1.getWidth()/2)-(bmp2.getWidth()/2), 0, null);

                return bmOverlay;
            }

            public static Bitmap createNewBitmap(int width, int height)
            {
                //create a blanks bitmap of the desired width/height
                return Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            }
        }









No comments:

Post a Comment

Disqus for Android