Android ImageView.setMatrix()和.invalidate() - 重新绘制需要花费太多时间

Fil*_*ski 15 java android invalidation imageview scaletype

任务:我想调整大小并在屏幕上移动图像.无论图像有多大,我都想顺利地做到这一点.API级别8应该支持该代码.

问题:我试过ImageViewscaleType="matrix".打电话ImageView.setMatrix()然后ImageView.invalidate()用小图片很好用,但对大图片很可怕.无论多大ImageView.

我可以以某种方式加快重新绘制,ImageView以便不会重新计算整个图像吗?也许有一种方法可以使用不同的组件完成任务?


编辑:有关我想要实现的更多信息.

  • pw,ph - 图片的宽度和高度(以像素为单位)
  • dw,dh - 设备显示的宽度和高度(以像素为单位)
  • fw,fh - 可见帧的宽度和高度(以像素为单位)
  • x,y - 框架左上角的位置(以像素为单位) 可视化问题.

我想在屏幕上显示图像的一部分.属性x,y,fwfh不断变化.我正在寻找代码的一部分(想法),或者为这8个指定变量快速生成并显示图像部分的组件.


编辑2:关于pwph的信息

我假设pwph可以保持从1到无穷大的值.如果这种方法造成很多麻烦,我们可以假设图片不比用设备的相机拍摄的图片大.

Fil*_*ski 2

在您(社区)的帮助下,我找到了解决方案。我确信还有其他更好的方法可以做到这一点,但我的解决方案并不是很复杂,并且应该适用于任何图像,任何 Android 自 API 级别 8 以来的任何图像。

解决方案是使用两个ImageView对象而不是一个。

第一个ImageView将像以前一样工作,但加载的图像将按比例缩小,以便其宽度将小于 的宽度ImageView,并且其高度将小于 的高度ImageView

第二个ImageView在开始时将为空白。每次xyfwfh属性发生更改时AsyncTask,都会执行以仅加载图像的可见部分。当属性快速变化时,AsyncTask将无法及时完成。它必须被取消并开始新的。完成后,结果Bitmap将加载到第二个上ImageView,以便用户可见。当属性再次更改时,加载Bitmap将被删除,因此不会覆盖移动Bitmap加载到第一个ImageView注意: BitmapRegionDecoder我将使用它来加载子图像,自 Android API 级别 10 起可用,因此 API 8 和 API 9 用户将只能看到缩小的图像。我决定没关系。


需要代码:

  • 设置第一个(底部)ImageView scaleType="matrix"(最好在 XML 中)
  • 设置第二个(顶部)ImageView scaleType="fitXY"(最好在 XML 中)
  • Android 文档中的函数(此处) - 感谢用户Vishavjeet Singh

注意:计算 时请注意||运算符而不是。我们希望加载的图像小于 ,以便我们确定有足够的 RAM 来加载它。(我假设尺寸不大于设备显示屏的尺寸。我还假设设备有足够的内存来加载至少设备显示屏尺寸的 2 倍。请告诉我我是否在这里犯了错误。) 2:我正在使用 加载图像。要以不同的方式加载文件,您必须更改块中的代码。&&inSampleSizeImageViewImageViewBitmaps
InputStreamtry{...} catch(...){...}

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

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

        final int halfHeight = height / 2;
        final int 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;
        }
    }

    return inSampleSize;
}

public Bitmap decodeSampledBitmapFromResource(Uri fileUri,
                                              int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    try {
        InputStream is = this.getContentResolver().openInputStream(fileUri);
        BitmapFactory.decodeStream(is, null, options);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    try {
        InputStream is = this.getContentResolver().openInputStream(fileUri);
        return BitmapFactory.decodeStream(is, null, options);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)
  • 返回图像的子图像的函数。

注意:将从源图像中剪切出来的矩形的大小是相对于图像的。ImageView指定它的值是从 0 到 1,因为和 加载的s的大小Bitmap与原始图像的大小不同。

public Bitmap getCroppedBitmap (Uri fileUri, int outWidth, int outHeight,
                                    double rl, double rt, double rr, double rb) {
        // rl, rt, rr, rb are relative (values from 0 to 1) to the size of the image.
        // That is because image moving will be smaller than the original.
        if (Build.VERSION.SDK_INT >= 10) {
            // Ensure that device supports at least API level 10
            // so we can use BitmapRegionDecoder
            BitmapRegionDecoder brd;
            try {
                // Again loading from URI. Change the code so it suits yours.
                InputStream is = this.getContentResolver().openInputStream(fileUri);
                brd = BitmapRegionDecoder.newInstance(is, true);

                BitmapFactory.Options options = new BitmapFactory.Options();
                options.outWidth = (int)((rr - rl) * brd.getWidth());
                options.outHeight = (int)((rb - rt) * brd.getHeight());
                options.inSampleSize = calculateInSampleSize(options,
                        outWidth, outHeight);

                return brd.decodeRegion(new Rect(
                        (int) (rl * brd.getWidth()),
                        (int) (rt * brd.getHeight()),
                        (int) (rr * brd.getWidth()),
                        (int) (rb * brd.getHeight())
                ), options);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        else
            return null;
    }
Run Code Online (Sandbox Code Playgroud)
  • AsyncTask加载子图像Bitmap

注意:注意声明此类类型的变量。稍后会用到。

private LoadHiResImageTask loadHiResImageTask = new LoadHiResImageTask();

private class LoadHiResImageTask extends AsyncTask<Double, Void, Bitmap> {
        /** The system calls this to perform work in a worker thread and
         * delivers it the parameters given to AsyncTask.execute() */
        protected Bitmap doInBackground(Double... numbers) {
            return getCroppedBitmap(
                    // You will have to change first parameter here!
                    Uri.parse(imagesToCrop[0]),
                    numbers[0].intValue(), numbers[1].intValue(),
                    numbers[2], numbers[3], numbers[4], numbers[5]);
        }

        /** The system calls this to perform work in the UI thread and delivers
         * the result from doInBackground() */
        protected void onPostExecute(Bitmap result) {
            ImageView hiresImage = (ImageView) findViewById(R.id.hiresImage);
            hiresImage.setImageBitmap(result);
            hiresImage.postInvalidate();
        }
    }
Run Code Online (Sandbox Code Playgroud)
  • 使所有功能协同工作的功能。

每次xyfwfh属性更改时都会调用此函数。
注意: 我的代码中的hiresImageid是第二个(顶部)ImageView

private void updateImageView () {
        //  ... your code to update ImageView matrix ...
        // 
        // imageToCrop.setImageMatrix(m);
        // imageToCrop.postInvalidateDelayed(10);

        if (Build.VERSION.SDK_INT >= 10) {
            ImageView hiresImage = (ImageView) findViewById(R.id.hiresImage);
            hiresImage.setImageDrawable(null);
            hiresImage.invalidate();
            if (loadHiResImageTask.getStatus() != AsyncTask.Status.FINISHED) {
                loadHiResImageTask.cancel(true);
            }
            loadHiResImageTask = null;
            loadHiResImageTask = new LoadHiResImageTask();
            loadHiResImageTask.execute(
                    (double) hiresImage.getWidth(),
                    (double) hiresImage.getHeight(),
                    // x, y, fw, fh are properties from the question
                    (double) x / d.getIntrinsicWidth(),
                    (double) y / d.getIntrinsicHeight(),
                    (double) x / d.getIntrinsicWidth()
                            + fw / d.getIntrinsicWidth(),
                    (double) y / d.getIntrinsicHeight()
                            + fh / d.getIntrinsicHeight());
        }
    }
Run Code Online (Sandbox Code Playgroud)