你真的理解Bitmap么?

你真的理解Bitmap么?

一直以来,Android适配要将图片放在mdpi、hdpi、xhdpi,如果放乱了就会导致各种性能问题,为什么?为什么我讲图片放在mdpi,然后运行到hdpi设备上图片会大很多?源码怎么处理呢?俗话说,要知其然也要知其所以然

res文件的加载

我们先来看一段伪代码

    Bitmap bm = BitmapFactory.decodeResource(res,R.mipmap.icon);
    imageView.setImageBitmap(bm);
  • 假设:icon是放在mipmap-mdpi目录下,然后我运行的目标设备是hdpi分辨率,接下来我们来追踪下流程

BitmapFactory.decodeResource

public static Bitmap decodeResource(Resources res, int id, Options opts) {
     Bitmap bm = null;
     InputStream is = null; 
     
     try {
         final TypedValue value = new TypedValue();
         is = res.openRawResource(id, value);
         bm = decodeResourceStream(res, value, is, null, opts);
     } catch (Exception e) {
        ...
     } finally {
        ...
     }
     ...
     return bm;
}
  • BitmapFactory.decodeResource有两个重载方法,实际上最终调用的是上面这个函数
  • 这个函数中,首先初始化了一个TypeValue实力,然后通过res,进一步通过Native层的AssetManager读到icon流,对应的实现AssetInputStream
  • 流程代码如下:

Resources.openRawResource

 public InputStream openRawResource(@RawRes int id, TypedValue value)
            throws NotFoundException {
    getValue(id, value, true);

    try {
        return mAssets.openNonAsset(value.assetCookie, value.string.toString(),
                AssetManager.ACCESS_STREAMING);
    } catch (Exception e) {
      ...
    }
}

AssetManager.openNonAsset

 public final InputStream openNonAsset(int cookie, String fileName, int accessMode)
        throws IOException {
    synchronized (this) {
        ...
        long asset = openNonAssetNative(cookie, fileName, accessMode);
        if (asset != 0) {
            AssetInputStream res = new AssetInputStream(asset);
            incRefsLocked(res.hashCode());
            return res;
        }
    }
    ...
}
  • 这里不在细说AssetManager的工作机制,如果你感兴趣请看这里

BitmapFactory.decodeResourceStream

public static Bitmap decodeResourceStream(Resources res, TypedValue value,
            InputStream is, Rect pad, Options opts) {
    if (opts == null) {
        opts = new Options();
    }

    if (opts.inDensity == 0 && value != null) {
        final int density = value.density;
        if (density == TypedValue.DENSITY_DEFAULT) {
            opts.inDensity = DisplayMetrics.DENSITY_DEFAULT;
        } else if (density != TypedValue.DENSITY_NONE) {
            opts.inDensity = density;
        }
    }
    
    if (opts.inTargetDensity == 0 && res != null) {
        opts.inTargetDensity = res.getDisplayMetrics().densityDpi;
    }
    
    return decodeStream(is, pad, opts);
}
  • 参数中,is的实际就是读icon文件的流,value就是mdpi文件对应的信息,所以执行完这个方法后,opts存储的inDensity指向的是mdpi,inTargetDensity指向的是目标设备的也就是hdpi的,接着往下看代码

BitmapFactory.decodeStream

public static Bitmap decodeStream(InputStream is, Rect outPadding, Options opts) {
        ...
        Bitmap bm = null;
        ...
        try {
            if (is instanceof AssetManager.AssetInputStream) {
                final long asset = 
                    ((AssetManager.AssetInputStream) is).getNativeAsset();
                bm = nativeDecodeAsset(asset, outPadding, opts);
            } else {
                ...
            }
            ...
            setDensityFromOptions(bm, opts);
        } finally {
            ...
        }
        return bm;
  • is是前面AssetManager.openNonAsset返回的,类型是AssetInputStream,所以会在native层去解析asset,
  • native层的代码调用逻辑为BitmaFactory.cpp,其全路径为android / platform / frameworks / base / core / jni / android / graphics / BitmapFactory.cpp
static jobject nativeDecodeAsset(JNIEnv* env, jobject clazz, jint native_asset,
        jobject padding, jobject options) {
    return nativeDecodeAssetScaled(env, clazz, native_asset, padding, options, false, 1.0f);
}

static jobject nativeDecodeAssetScaled(JNIEnv* env, jobject clazz, jint native_asset,
        jobject padding, jobject options, jboolean applyScale, jfloat scale) {
    SkStream* stream;
    Asset* asset = reinterpret_cast<Asset*>(native_asset);
    bool forcePurgeable = optionsPurgeable(env, options);
    if (forcePurgeable) {
        ....
        stream = copyAssetToStream(asset);
        ...
    } else {
        ...
        stream = new AssetStreamAdaptor(asset);
    }
    SkAutoUnref aur(stream);
    return doDecode(env, stream, padding, options, true, forcePurgeable, applyScale, scale);
}
  • 可以看到最终调用到了doDecode方法
static jobject doDecode(JNIEnv* env, SkStream* stream, jobject padding,
        jobject options, bool allowPurgeable, bool forcePurgeable = false,
        bool applyScale = false, float scale = 1.0f) {
    int sampleSize = 1;
    ...
    jobject javaBitmap = NULL;
    if (options != NULL) {
        sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID);
        ...
        javaBitmap = env->GetObjectField(options, gOptions_bitmapFieldID);
    }
    ...
    if (willScale) {
        ...
        const float sx = scaledWidth / float(decoded->width());
        const float sy = scaledHeight / float(decoded->height());
        bitmap->setConfig(decoded->getConfig(), scaledWidth, scaledHeight);
        bitmap->allocPixels(&javaAllocator, NULL);
        bitmap->eraseColor(0);
        SkPaint paint;
        paint.setFilterBitmap(true);
        SkCanvas canvas(*bitmap);
        canvas.scale(sx, sy);
        canvas.drawBitmap(*decoded, 0.0f, 0.0f, &paint);
    }
    ...
    if (javaBitmap != NULL) {
        // If a java bitmap was passed in for reuse, pass it back
        return javaBitmap;
    }
    // now create the java bitmap
    return GraphicsJNI::createBitmap(env, bitmap, javaAllocator.getStorageObj(),
            isMutable, ninePatchChunk);
}
  • 略去中间我不管兴趣的代码(ps:如果你对Bitmap解析过程中各项参数感兴趣,可以看下这个类)
  • 我发现在native层分别时候,并没有去做缩放,那么我一开始提出的缩放点在哪里呢?先保留这个疑问继续往下看

BitmapFactory.setDensityFromOptions

private static void setDensityFromOptions(Bitmap outputBitmap, Options opts) {
        ...
        final int density = opts.inDensity;
        if (density != 0) {
            outputBitmap.setDensity(density);
            final int targetDensity = opts.inTargetDensity;
            if (targetDensity == 0 || density == targetDensity || density == opts.inScreenDensity) {
                return;
            }

            byte[] np = outputBitmap.getNinePatchChunk();
            final boolean isNinePatch = np != null && NinePatch.isNinePatchChunk(np);
            if (opts.inScaled || isNinePatch) {
                outputBitmap.setDensity(targetDensity);
            }
        } else if (opts.inBitmap != null) {
            ...
        }
    }
  • 在BitmapFactory.setDensityFromOptions中,把前面对应解析到的opts.inDensity传给了解析完的bitmap,那么是不是说在使用这个bitmap 时候再去进行缩放呢?
  • 查看Options针对inDensity、inTargetDensity的解释,证明我的猜想是正确的
    /**
      * The pixel density to use for the bitmap.  This will always result
      * in the returned bitmap having a density set for it (see
      * {@link Bitmap#setDensity(int) Bitmap.setDensity(int)}).  In addition,
      * if {@link #inScaled} is set (which it is by default} and this
      * density does not match {@link #inTargetDensity}, then the bitmap
      * will be scaled to the target density before being returned.
      * 
      */
     public int inDensity;
     
    /**
    * The pixel density of the destination this bitmap will be drawn to.
    * This is used in conjunction with {@link #inDensity} and
    * {@link #inScaled} to determine if and how to scale the bitmap before
    * returning it.
    */
    public int inTargetDensity;
  • 上面不进行翻译,我觉得会曲解意思,意思就是说在绘制时候,如果inDensity、inTargetDensity不一致那么就会按照inTargetDensity的值进行缩放
  • 回到一开始的伪代码,接下老我们看ImageView是如何处理的

ImageView.onDraw

  • 熟悉Android开发的一定知道,调用setImageBitmap会调用invalidate,之后的流程不再细说,最后我们来看onDraw都做了什么
protected void onDraw(Canvas canvas) {
    ...
    mDrawable.draw(canvas);
    ...
}
  • 略去不关心的代码,实际上onDraw就只调用了一行代码
  • mDrawable是什么?他的draw方法都做了什么?

ImageView.setImageBitmap

public void setImageBitmap(Bitmap bm) {
    ...
    mRecycleableBitmapDrawable = new ImageViewBitmapDrawable(
                    mContext.getResources(), bm);
    ...
}
  • 实际上在setImageBitmap时候,会创建一个ImageViewBitmapDrawable,他的父类是BitmapDrawable,后续代码流程会将这个ImageViewBitmapDrawable赋值给mDrawable
  • 我们来看BitmapDrawable.draw都干嘛了

BitmapDrawable.draw

public void draw(Canvas canvas) {
    ...
    canvas.drawBitmap(bitmap, null, mDstRect, paint);
    ...
}
  • 这里会调用到canvas.drawBitmap,接着追下去

canvas.drawBitmap

public void drawBitmap(@NonNull Bitmap bitmap, @Nullable Rect src, @NonNull Rect dst,
            @Nullable Paint paint) {
    ...
     native_drawBitmap(mNativeCanvasWrapper, bitmap, left, top, right, bottom,
            dst.left, dst.top, dst.right, dst.bottom, nativePaint, mScreenDensity,
            bitmap.mDensity);
}
  • 最终调用的是native_drawBitmap,并且注意一个参数bitmap.mDensity
  • 接着往下追踪,Canvas.cpp的位置是android / platform / frameworks / core / jni / android / graphics / Canvas.cpp
{"native_drawBitmap","(IIFFIIII)V",
    (void*) SkCanvasGlue::drawBitmap__BitmapFFPaint},
{"native_drawBitmap","(IILandroid/graphics/Rect;Landroid/graphics/RectF;III)V",
    (void*) SkCanvasGlue::drawBitmapRF},
{"native_drawBitmap","(IILandroid/graphics/Rect;Landroid/graphics/Rect;III)V",
    (void*) SkCanvasGlue::drawBitmapRR},
{"native_drawBitmap", "(I[IIIFFIIZI)V",
  • 对应的映射有4处,drawBitmap__BitmapFFPaint查看这个实现如下:
static void drawBitmap__BitmapFFPaint(JNIEnv* env, jobject jcanvas,
                                          SkCanvas* canvas, SkBitmap* bitmap,
                                          jfloat left, jfloat top,
                                          SkPaint* paint, jint canvasDensity,
                                          jint screenDensity, jint bitmapDensity) {
        ...
        if (canvasDensity == bitmapDensity || canvasDensity == 0
                || bitmapDensity == 0) {
            ...
        } else {
            canvas->save();
            SkScalar scale = SkFloatToScalar(canvasDensity / (float)bitmapDensity);
            canvas->translate(left_, top_);
            canvas->scale(scale, scale);
            ...
            filteredPaint.setFilterBitmap(true);
            canvas->drawBitmap(*bitmap, 0, 0, &filteredPaint);
            canvas->restore();
        }
    }
  • 这里,如果说canvasDensity与bitmapDensity不一致就会进行缩放,
  • 所以我们可以得出结论,mdpi下的icon在hdpi中对应的大小是whargb*TargetDensity/inDensity
  • 验证了我们开篇回答的问题,over到此可以愉快的写bug去了
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容