如何合并两个位图

时间:2013-07-30 07:08:56

标签: java android bitmap android-canvas

我试图在第二个右边粘贴一个位图。这是我的代码:

public static Bitmap getGluedBitmap(File left, File right, int reqWidth, int reqHeight, LruCache<String, Bitmap> mCache)
    {
        Bitmap lefty = decodeSampledBitmapFromFile(left, reqWidth / 2, reqHeight, 2, mCache);
        Bitmap righty = decodeSampledBitmapFromFile(right, reqWidth / 2, reqHeight, 2, mCache);
        Bitmap output = Bitmap.createBitmap(reqWidth, reqHeight, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        canvas.drawBitmap(lefty, null, new Rect(0, 0, canvas.getWidth() / 2, canvas.getHeight()), null);
        canvas.drawBitmap(righty, null, new Rect(canvas.getWidth() / 2 + 1, 0, canvas.getWidth(), canvas.getHeight()), null);

        return output;
    }

以下是来自Google示例的decodeSampledBitmapFromFile方法,针对我的需求进行了优化:

public static Bitmap decodeSampledBitmapFromFile(File file, int reqWidth, int reqHeight, int state, LruCache<String, Bitmap> mCache) {
        String imageKey = String.valueOf(file.getAbsolutePath());
        imageKey += state;
        Bitmap bitmap = getBitmapFromMemCache(imageKey, mCache);
        if (bitmap == null) {
            // First decode with inJustDecodeBounds=true to check dimensions
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(file.getAbsolutePath(), options);

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

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

            boolean done = false;
            while(!done)
            {
                try {
                    bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
                    done = true;
                } catch (OutOfMemoryError e) {
                    // Ignore.  Try again.
                }
            }
            return addBitmapToMemoryCache(imageKey, bitmap, mCache);
        }
        else
        {
            return bitmap;
        }
    }

此方法按缓存中的键搜索图片,state用于缓存picters上的不同版本,即小版本,大型顶点等。 此外,你可以看到一些带有解码文件的弯曲指甲,但这一步是暂时的,我稍后会解决这个问题。所有你需要知道这个方法正确地工作了146%。

问题是:我用第一种方法创建的位图是不正确的,而且它没有显示。我的意思是这个位图的宽度和高度由于某种原因等于-1。 但是,Bitmap lefty和righty的宽度也等于-1,但是我尝试显示那些位图并且效果很好。

告诉我我是否合并了位图错误。

1 个答案:

答案 0 :(得分:0)

嗯,代码绝对正确。出于某种原因,我的设备无法显示生成的位图。我试图将此代码构建到其他设备,它完美地工作。谢谢你的关注。

相关问题