【问题标题】:Why is my Android app so slow?为什么我的 Android 应用程序这么慢?
【发布时间】:2013-07-26 05:45:19
【问题描述】:

我在一个 int 数组(int[] 像素)中有一个图像(大小为 1024x1024),我正在使用以下循环反转一个通道...

int i = 0;
for (int y = 0; y < H; y++) {
    for (int x = 0; x < W; x++) {
       int color = pixels[i];
       pixels[i] = Color.argb(Color.alpha(color), 255 - Color.red(color), Color.green(color), Color.blue(color));
       i++;
    }
}

在我的新 Galaxy S4 手机上,这需要超过 1 秒。即使在较旧的 iPhone 上,类似的循环也会在眨眼间运行。我在这里做错了吗?

如果我用“Color.BLUE”替换“Color.argb(Color.alpha(color), 255 - Color.red(color), Color.green(color), Color.blue(color))”,它变得更快。

找到了解决方法。

如果我使用自己的位运算符而不是颜色函数,它会变得更快...

  int i = 0;
  for (int y = 0; y < H; y++) {
     for (int x = 0; x < W; x++) {
         int color = pixels[i];
         int red = ((color & 0x00ff0000) >> 16);
         pixels[i] = (color & 0xff00ffff) | ((255 - red) << 16);
         //pixels[i] = Color.argb(Color.alpha(color), 255 - Color.red(color), Color.green(color), Color.blue(color));
         i++;
      }
  }

【问题讨论】:

    标签: java android eclipse image-processing


    【解决方案1】:

    我觉得如果把这段代码换成这个,会比较快

                int w = bitmap.getWidth();
            int h = bitmap.getHeight();
            int pixels[] = new int[w * h];
            bitmap.getPixels(pixels, 0, w, 0, 0, w, h);
            int n = w * h;
            for (int i = 0; i < n; i++) {
                int color = pixels[i];
                pixels[i] = Color.argb(Color.alpha(color), 255 - Color.red(color), Color.green(color), Color.blue(color));
            }
            bitmap.setPixels(pixels, 0, w, 0, 0, w, h);
    

    【讨论】:

    • 我可以进行优化,但这里的瓶颈是颜色处理操作。因此,总体运行时间基本保持不变。
    【解决方案2】:

    您可能需要考虑使用 ColorMatrix 类来完成此操作:http://developer.android.com/reference/android/graphics/ColorMatrix.html

    以您的方式操作单个像素时,很可能会涉及相当大的开销。 ColorMatrix 类是你的朋友。

    【讨论】:

    • Color 函数确实看起来很慢,如果我用自己的位运算符替换它们,它会变得更快。
    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 2016-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    相关资源
    最近更新 更多