如何有效设置画布中的位图?

时间:2018-10-10 17:57:42

标签: java android live-wallpaper

我正在使用Android的WallpaperService来在我的应用程序中实现自动换壁纸功能。因此,经过大量研究和反复试验后,我找到了一个可以满足我需要的解决方案。但是,我的实现的主要问题是,它消耗大量电池电量。特别是当用户选择最小时间段时(例如5分钟)。我的应用在“最高电池消耗者”列表中排名前三。那么,我的代码中是否有其他方法或改进措施可以大大减少电池消耗?

我只发布了一部分代码,这些代码会更改Canvas的位图:

//Loading Bitmap from Storage, path is File variable
bitmap = BitmapFactory.decodeFile(path.getPath() + "/" + fileNames[index]);
canvas = holder.lockCanvas();
canvas.save();
int width = bitmap.getWidth();
int height = bitmap.getHeight();
WindowManager windowManager =
        (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);
if (windowManager != null) {
    //This part will get height and width of actual device screen(Resolution) if soft buttons are present
    final Display display = windowManager.getDefaultDisplay();
    Point outPoint = new Point();
    if (Build.VERSION.SDK_INT >= 19) {
        // include navigation bar
        display.getRealSize(outPoint);
    } else {
        // exclude navigation bar
        display.getSize(outPoint);
    }
    maxHeight = outPoint.y;
    maxWidth = outPoint.x;
} else {
    maxWidth = Resources.getSystem().getDisplayMetrics().widthPixels;
    maxHeight = Resources.getSystem().getDisplayMetrics().heightPixels;
}
if (width > height) {
    //Crops Image to match the ratio of device resolution
    // landscape
    bitmap = Bitmap.createBitmap(
            bitmap,
            bitmap.getWidth() / 2 - bitmap.getHeight() / 2,
            0,
            bitmap.getHeight(),
            bitmap.getHeight()
    );
    float widthratio = (float) bitmap.getHeight() / maxHeight;
    width = (int) (bitmap.getWidth() / widthratio);
    height = maxHeight;
} else if (height > width) {
    // portrait
    float ratio;
    float heightratio = (float) width / maxWidth;
    height = (int) (height / heightratio);
    width = maxWidth;
    if (height < maxHeight) {
        ratio = (float) height / maxHeight;
        height = maxHeight;
        width = (int) (width / ratio);
    }
} else {
    // square
    height = maxHeight;
    width = maxWidth;
}
canvas.scale(1, 1);
//Scale the bitmap to match the resolution of device screen
bitmap = Bitmap.createScaledBitmap(bitmap, (int) (width), (int) (height), false);
//Drawing Image in Canvas
canvas.drawBitmap(bitmap, 0, 0, null);
bitmap.recycle();
bitmap = null;
canvas.restore();
holder.unlockCanvasAndPost(canvas);
handler.removeCallbacks(drawImage);
//Delaying handler as per user's preferenced time period
handler.postDelayed(drawImage, preferences.getInt("TIMETOCHANGEBACHGROUND", 3600) * 1000);
canvas.setBitmap(null);

0 个答案:

没有答案