位图花费太多时间设置为墙纸

时间:2018-12-05 12:41:26

标签: java android bitmap

当我要将图像设置为墙纸时,有时会导致5秒以上甚至更长的时间,导致应用崩溃。

我进行了很多搜索,找到了使用 setStream 代替 setBitmap 的方法,但是实际上没有用,因为没有任何人提到完整的代码。 所以请帮助我快速设置墙纸。

我的代码:

 private void setAsWallpaper(Bitmap bitmap) {
    mNotifyManager.cancel(id);
    WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
    try {
        wallpaperManager.setBitmap(bitmap);
        success();
    } catch (IOException e) {
        e.printStackTrace();
        failure();
    }
}

2 个答案:

答案 0 :(得分:0)

根据屏幕尺寸调整位图大小 它将减少设置时间

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int screenHeight = displayMetrics.heightPixels;
int screenWidth = displayMetrics.widthPixels;
    bitmap = Bitmap.createScaledBitmap(bitmap,screenWidth, screenHeight, true);

现在您可以为墙纸设置该位图

答案 1 :(得分:0)

您可以使用以下功能来调整位图的大小-

fun decodeSampledBitmapFromFilePath(filepath: String, reqWidth: Int, reqHeight: Int): Bitmap? {

        // First decode with inJustDecodeBounds=true to check dimensions
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeFile(filepath, options)

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight)
        if(options.outHeight == 0 && options.outWidth == 0){
            return null
        }
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false
        return BitmapFactory.decodeFile(filepath, options)
    }

    /**
     * Method to calculate a sample size value that is a power of two based on a target width and height.
     * @param options
     * @param reqWidth
     * @param reqHeight
     * @return sampleSize
     */
    fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
        // Raw height and width of image
        val height = options.outHeight
        val width = options.outWidth
        var inSampleSize = 1

        if (height > reqHeight || width > reqWidth) {

            /* val halfHeight = height / 2
             val halfWidth = width / 2

             // Calculate the largest inSampleSize value that is a power of 2 and keeps both
             // height and width larger than the requested height and width.
             while (halfHeight / inSampleSize >= reqHeight && halfWidth / inSampleSize >= reqWidth) {
                 inSampleSize *= 2
             }*/
            if (width > height) {
                inSampleSize = Math.round(width.toFloat() / reqWidth.toFloat())
            } else {
                inSampleSize = Math.round(height.toFloat() / reqHeight.toFloat())
            }
        }

        return inSampleSize
    }