【问题标题】:Clean way to implement gradual fading of brightness in Android?在Android中实现亮度逐渐衰减的干净方法?
【发布时间】:2011-11-02 18:21:36
【问题描述】:

目前我有代码来淡化亮度调整,看起来像这样:

new Thread() {
    public void run() {
        for (int i = initial; i < target; i++) {
            final int bright = i;
            handle.post(new Runnable() {
                public void run() {
                    float currentBright = bright / 100f;
                    window.getAttributes().screenBrightness = currentBright;
                    window.setAttributes(window.getAttributes());
                });
            }
            try {
                sleep(step);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}.start();

我不确定这是否被认为是好的方法(我考虑过使用 ASyncTask,但在这种情况下我看不到好处)。有没有更好的方法来实现背光褪色?

编辑:我现在使用 TimerTask 如下:

new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
        final float currentBright = counter[0] / 100f;
        handle.post(new Runnable() {    
            public void run() {
                window.getAttributes().screenBrightness = currentBright;
                window.setAttributes(window.getAttributes());
                if (++counter[0] <= target) {
                    cancel();
                }
            }
        });
    }
}, 0, step);

我使用数组作为计数器的原因是因为它需要final才能在Runnable中访问,但我需要修改该值。这使用更少的 CPU,但仍然比我喜欢的多。

EDIT2:Aaa 和第三次尝试。感谢 CommonsWare 的建议! (希望我应用正确!)

    handle.post(new Runnable() {
        public void run() {
            if (counter[0] < target) {
                final float currentBright = counter[0] / 100f;
                window.getAttributes().screenBrightness = currentBright;            
                window.setAttributes(window.getAttributes());
                counter[0]++;
                handle.postDelayed(this, step);
            }
        }
   });

谢谢!

【问题讨论】:

  • 你想让设备进入睡眠状态?
  • 不,我只是想逐渐改变背光亮度。
  • 据我所知,没有具体的 Android Animation Resource 可以满足您的需求:-/ 抱歉。
  • 嗯,我试试 ObjectAnimator。感谢您的链接。
  • 你实现它的方式有什么问题?我觉得不错……

标签: android brightness fading


【解决方案1】:

如何在每次迭代中将亮度降低到一半。

然后循环将在 O(log n) 而不是当前解决方案中的 O(n) 中完成。

【讨论】:

  • 我喜欢你的想法!问题是亮度衰减最初会非常跳跃,所以看起来有点滞后。
  • 我试了一下,如果步长足够小,效果还不错。干杯!
  • @Glitch 我很高兴它为你工作 && 我是我在这里的第一个赏金
【解决方案2】:

在 Honeycomb 中,您可以使用 Property Animation 来做这些事情。这个post on the Android Developers blog talks about it all in some detail

【讨论】:

  • 我已经尝试过了,但我无法实际测试它,因为我没有 Honeycomb 设备。也许如果我们可以访问源代码,我可以为其他 Android 平台实现它。
猜你喜欢
  • 2019-05-31
  • 2012-01-28
  • 2010-10-16
  • 1970-01-01
  • 2010-12-01
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多