你真的理解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(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去了

你可能感兴趣的:(你真的理解Bitmap么?)