今天是個奇怪的日子诊县,有三位同學(xué)找我缎浇,都是關(guān)于界面卡頓的問題,問我能不能幫忙解決下熔号。由于性能優(yōu)化涉及的知識點比較多稽鞭,我一時半會也無法徹底回答。恰好之前在做需求時也遇到了一個卡頓的問題引镊,因此今晚寫下這篇卡頓優(yōu)化的文章朦蕴,希望對大家有所幫助。先來看看卡頓的現(xiàn)象:
1. 查找卡頓原因
從上面的現(xiàn)象來看弟头,應(yīng)該是主線程執(zhí)行了耗時操作引起了卡頓吩抓,因為正常滑動是沒問題的赴恨,只有在刷新數(shù)據(jù)的時候才會出現(xiàn)卡頓疹娶。至于什么情況下會引起卡頓,之前在自定義 View 部分已有詳細講過伦连,這里就不在啰嗦雨饺。我們猜想可能是耗時引起的卡頓,但也不能 100% 確定惑淳,況且我們也并不知道是哪個方法引起的额港,因此我們只能借助一些常用工具來分析分析,我們打開 Android Device Monitor 歧焦。
2. RxJava 線程切換
我們找到了是高斯模糊處理耗時導(dǎo)致了界面卡頓移斩,那現(xiàn)在我們把高斯模糊算法處理放入子線程中去,處理完后再次切換到主線程倚舀,這里采用 RxJava 來實現(xiàn)叹哭。
Observable.just(resource.getBitmap())
.map(bitmap -> {
// 高斯模糊
Bitmap blurBitmap = ImageUtil.doBlur(resource.getBitmap(), 100, false);
blurBitmapCache.put(path, blurBitmap);
return blurBitmap;
}).subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(blurBitmap -> {
if (blurBitmap != null) {
recommendBgIv.setImageBitmap(blurBitmap);
}
});
關(guān)于響應(yīng)式編程思想和 RxJava 的實現(xiàn)原理大家可以參考以下幾篇文章:
2. 高斯模糊算法分析
把耗時操作放到子線程中去處理忍宋,的確解決了界面卡頓問題痕貌。但這其實是治標不治本,我們發(fā)現(xiàn)圖片加載處理異常緩慢糠排,內(nèi)存久高不下有時可能會導(dǎo)致內(nèi)存溢出舵稠。接下來我們來分析一下高斯模糊的算法實現(xiàn):
看上面這幾張圖,我們通過怎樣的操作才能把第一張圖處理成下面這兩張圖?其實就是模糊化哺徊,怎么才能做到模糊化室琢?我們來看下高斯模糊算法的處理過程。再上兩張圖:
所謂"模糊"落追,可以理解成每一個像素都取周邊像素的平均值盈滴。上圖中,2是中間點轿钠,周邊點都是1巢钓。"中間點"取"周圍點"的平均值,就會變成1疗垛。在數(shù)值上症汹,這是一種"平滑化"。在圖形上贷腕,就相當于產(chǎn)生"模糊"效果背镇,"中間點"失去細節(jié)。
為了得到不同的模糊效果泽裳,高斯模糊引入了權(quán)重的概念瞒斩。上面分別是原圖、模糊半徑3像素涮总、模糊半徑10像素的效果济瓢。模糊半徑越大,圖像就越模糊妹卿。從數(shù)值角度看旺矾,就是數(shù)值越平滑。接下來的問題就是夺克,既然每個點都要取周邊像素的平均值箕宙,那么應(yīng)該如何分配權(quán)重呢?如果使用簡單平均铺纽,顯然不是很合理柬帕,因為圖像都是連續(xù)的,越靠近的點關(guān)系越密切狡门,越遠離的點關(guān)系越疏遠陷寝。因此,加權(quán)平均更合理其馏,距離越近的點權(quán)重越大凤跑,距離越遠的點權(quán)重越小。對于這種處理思想叛复,很顯然正太分布函數(shù)剛好滿足我們的需求仔引。但圖片是二維的扔仓,因此我們需要根據(jù)一維的正太分布函數(shù),推導(dǎo)出二維的正太分布函數(shù):
if (radius < 1) {//模糊半徑小于1
return (null);
}
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// 通過 getPixels 獲得圖片的像素數(shù)組
int[] pix = new int[w * h];
bitmap.getPixels(pix, 0, w, 0, 0, w, h);
int wm = w - 1;
int hm = h - 1;
int wh = w * h;
int div = radius + radius + 1;
int r[] = new int[wh];
int g[] = new int[wh];
int b[] = new int[wh];
int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
int vmin[] = new int[Math.max(w, h)];
int divsum = (div + 1) >> 1;
divsum *= divsum;
int dv[] = new int[256 * divsum];
for (i = 0; i < 256 * divsum; i++) {
dv[i] = (i / divsum);
}
yw = yi = 0;
int[][] stack = new int[div][3];
int stackpointer;
int stackstart;
int[] sir;
int rbs;
int r1 = radius + 1;
int routsum, goutsum, boutsum;
int rinsum, ginsum, binsum;
// 循環(huán)行
for (y = 0; y < h; y++) {
rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
// 半徑處理
for (i = -radius; i <= radius; i++) {
p = pix[yi + Math.min(wm, Math.max(i, 0))];
sir = stack[i + radius];
// 拿到 rgb
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rbs = r1 - Math.abs(i);
rsum += sir[0] * rbs;
gsum += sir[1] * rbs;
bsum += sir[2] * rbs;
if (i > 0) {
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
} else {
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
}
}
stackpointer = radius;
// 循環(huán)每一列
for (x = 0; x < w; x++) {
r[yi] = dv[rsum];
g[yi] = dv[gsum];
b[yi] = dv[bsum];
rsum -= routsum;
gsum -= goutsum;
bsum -= boutsum;
stackstart = stackpointer - radius + div;
sir = stack[stackstart % div];
routsum -= sir[0];
goutsum -= sir[1];
boutsum -= sir[2];
if (y == 0) {
vmin[x] = Math.min(x + radius + 1, wm);
}
p = pix[yw + vmin[x]];
sir[0] = (p & 0xff0000) >> 16;
sir[1] = (p & 0x00ff00) >> 8;
sir[2] = (p & 0x0000ff);
rinsum += sir[0];
ginsum += sir[1];
binsum += sir[2];
rsum += rinsum;
gsum += ginsum;
bsum += binsum;
stackpointer = (stackpointer + 1) % div;
sir = stack[(stackpointer) % div];
routsum += sir[0];
goutsum += sir[1];
boutsum += sir[2];
rinsum -= sir[0];
ginsum -= sir[1];
binsum -= sir[2];
yi++;
}
yw += w;
}
for (x = 0; x < w; x++) {
// 與上面代碼類似 ......
對于部分哥們來說咖耘,上面的函數(shù)和代碼可能看不太懂翘簇。我們來講通俗一點,一方面如果我們的圖片越大儿倒,像素點也就會越多版保,高斯模糊算法的復(fù)雜度就會越大。如果半徑 radius 越大圖片會越模糊夫否,權(quán)重計算的復(fù)雜度也會越大找筝。因此我們可以從這兩個方面入手,要么壓縮圖片的寬高慷吊,要么縮小 radius 半徑袖裕。但如果 radius 半徑設(shè)置過小,模糊效果肯定不太好溉瓶,因此我們還是在寬高上面想想辦法急鳄,接下來我們?nèi)タ纯?Glide 的源碼:
private Bitmap decodeFromWrappedStreams(InputStream is,
BitmapFactory.Options options, DownsampleStrategy downsampleStrategy,
DecodeFormat decodeFormat, boolean isHardwareConfigAllowed, int requestedWidth,
int requestedHeight, boolean fixBitmapToRequestedDimensions,
DecodeCallbacks callbacks) throws IOException {
long startTime = LogTime.getLogTime();
int[] sourceDimensions = getDimensions(is, options, callbacks, bitmapPool);
int sourceWidth = sourceDimensions[0];
int sourceHeight = sourceDimensions[1];
String sourceMimeType = options.outMimeType;
// If we failed to obtain the image dimensions, we may end up with an incorrectly sized Bitmap,
// so we want to use a mutable Bitmap type. One way this can happen is if the image header is so
// large (10mb+) that our attempt to use inJustDecodeBounds fails and we're forced to decode the
// full size image.
if (sourceWidth == -1 || sourceHeight == -1) {
isHardwareConfigAllowed = false;
}
int orientation = ImageHeaderParserUtils.getOrientation(parsers, is, byteArrayPool);
int degreesToRotate = TransformationUtils.getExifOrientationDegrees(orientation);
boolean isExifOrientationRequired = TransformationUtils.isExifOrientationRequired(orientation);
// 關(guān)鍵在于這兩行代碼,如果沒有設(shè)置或者獲取不到圖片的寬高堰酿,就會加載原圖
int targetWidth = requestedWidth == Target.SIZE_ORIGINAL ? sourceWidth : requestedWidth;
int targetHeight = requestedHeight == Target.SIZE_ORIGINAL ? sourceHeight : requestedHeight;
ImageType imageType = ImageHeaderParserUtils.getType(parsers, is, byteArrayPool);
// 計算壓縮比例
calculateScaling(
imageType,
is,
callbacks,
bitmapPool,
downsampleStrategy,
degreesToRotate,
sourceWidth,
sourceHeight,
targetWidth,
targetHeight,
options);
calculateConfig(
is,
decodeFormat,
isHardwareConfigAllowed,
isExifOrientationRequired,
options,
targetWidth,
targetHeight);
boolean isKitKatOrGreater = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// Prior to KitKat, the inBitmap size must exactly match the size of the bitmap we're decoding.
if ((options.inSampleSize == 1 || isKitKatOrGreater) && shouldUsePool(imageType)) {
int expectedWidth;
int expectedHeight;
if (sourceWidth >= 0 && sourceHeight >= 0
&& fixBitmapToRequestedDimensions && isKitKatOrGreater) {
expectedWidth = targetWidth;
expectedHeight = targetHeight;
} else {
float densityMultiplier = isScaling(options)
? (float) options.inTargetDensity / options.inDensity : 1f;
int sampleSize = options.inSampleSize;
int downsampledWidth = (int) Math.ceil(sourceWidth / (float) sampleSize);
int downsampledHeight = (int) Math.ceil(sourceHeight / (float) sampleSize);
expectedWidth = Math.round(downsampledWidth * densityMultiplier);
expectedHeight = Math.round(downsampledHeight * densityMultiplier);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Calculated target [" + expectedWidth + "x" + expectedHeight + "] for source"
+ " [" + sourceWidth + "x" + sourceHeight + "]"
+ ", sampleSize: " + sampleSize
+ ", targetDensity: " + options.inTargetDensity
+ ", density: " + options.inDensity
+ ", density multiplier: " + densityMultiplier);
}
}
// If this isn't an image, or BitmapFactory was unable to parse the size, width and height
// will be -1 here.
if (expectedWidth > 0 && expectedHeight > 0) {
setInBitmap(options, bitmapPool, expectedWidth, expectedHeight);
}
}
// 通過流 is 和 options 解析 Bitmap
Bitmap downsampled = decodeStream(is, options, callbacks, bitmapPool);
callbacks.onDecodeComplete(bitmapPool, downsampled);
if (Log.isLoggable(TAG, Log.VERBOSE)) {
logDecode(sourceWidth, sourceHeight, sourceMimeType, options, downsampled,
requestedWidth, requestedHeight, startTime);
}
Bitmap rotated = null;
if (downsampled != null) {
// If we scaled, the Bitmap density will be our inTargetDensity. Here we correct it back to
// the expected density dpi.
downsampled.setDensity(displayMetrics.densityDpi);
rotated = TransformationUtils.rotateImageExif(bitmapPool, downsampled, orientation);
if (!downsampled.equals(rotated)) {
bitmapPool.put(downsampled);
}
}
return rotated;
}
4. LruCache 緩存
最后我們還可以再做一些優(yōu)化疾宏,數(shù)據(jù)沒有改變時不去刷新數(shù)據(jù),還有就是采用 LruCache 緩存触创,相同的高斯模糊圖像直接從緩存獲取坎藐。需要提醒大家的是,我們在使用之前最好了解其源碼實現(xiàn)哼绑,之前有見到同事這樣寫過:
/**
* 高斯模糊緩存的大小 4M
*/
private static final int BLUR_CACHE_SIZE = 4 * 1024 * 1024;
/**
* 高斯模糊緩存岩馍,防止刷新時抖動
*/
private LruCache<String, Bitmap> blurBitmapCache = new LruCache<String, Bitmap>(BLUR_CACHE_SIZE);
// 偽代碼 ......
// 有緩存直接設(shè)置
Bitmap blurBitmap = blurBitmapCache.get(item.userResp.headPortraitUrl);
if (blurBitmap != null) {
recommendBgIv.setImageBitmap(blurBitmap);
return;
}
// 從后臺獲取,進行高斯模糊后,再緩存 ...
這樣寫有兩個問題,第一個問題是我們發(fā)現(xiàn)整個應(yīng)用 OOM 了都還可以緩存數(shù)據(jù)抖韩,第二個問題是 LruCache 可以實現(xiàn)比較精細的控制蛀恩,而默認緩存池設(shè)置太大了會導(dǎo)致浪費內(nèi)存,設(shè)置小了又會導(dǎo)致圖片經(jīng)常被回收茂浮。第一個問題我們只要了解其內(nèi)部實現(xiàn)就迎刃而解了双谆,關(guān)鍵問題在于緩存大小該怎么設(shè)置?如果我們想不到好的解決方案席揽,那么也可以去參考參考 Glide 的源碼實現(xiàn)顽馋。
public Builder(Context context) {
this.context = context;
activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
screenDimensions = new DisplayMetricsScreenDimensions(context.getResources().getDisplayMetrics());
// On Android O+ Bitmaps are allocated natively, ART is much more efficient at managing
// garbage and we rely heavily on HARDWARE Bitmaps, making Bitmap re-use much less important.
// We prefer to preserve RAM on these devices and take the small performance hit of not
// re-using Bitmaps and textures when loading very small images or generating thumbnails.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && isLowMemoryDevice(activityManager)) {
bitmapPoolScreens = 0;
}
}
// Package private to avoid PMD warning.
MemorySizeCalculator(MemorySizeCalculator.Builder builder) {
this.context = builder.context;
arrayPoolSize =
isLowMemoryDevice(builder.activityManager)
? builder.arrayPoolSizeBytes / LOW_MEMORY_BYTE_ARRAY_POOL_DIVISOR
: builder.arrayPoolSizeBytes;
int maxSize =
getMaxSize(
builder.activityManager, builder.maxSizeMultiplier, builder.lowMemoryMaxSizeMultiplier);
int widthPixels = builder.screenDimensions.getWidthPixels();
int heightPixels = builder.screenDimensions.getHeightPixels();
int screenSize = widthPixels * heightPixels * BYTES_PER_ARGB_8888_PIXEL;
int targetBitmapPoolSize = Math.round(screenSize * builder.bitmapPoolScreens);
int targetMemoryCacheSize = Math.round(screenSize * builder.memoryCacheScreens);
int availableSize = maxSize - arrayPoolSize;
if (targetMemoryCacheSize + targetBitmapPoolSize <= availableSize) {
memoryCacheSize = targetMemoryCacheSize;
bitmapPoolSize = targetBitmapPoolSize;
} else {
float part = availableSize / (builder.bitmapPoolScreens + builder.memoryCacheScreens);
memoryCacheSize = Math.round(part * builder.memoryCacheScreens);
bitmapPoolSize = Math.round(part * builder.bitmapPoolScreens);
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(
TAG,
"Calculation complete"
+ ", Calculated memory cache size: "
+ toMb(memoryCacheSize)
+ ", pool size: "
+ toMb(bitmapPoolSize)
+ ", byte array size: "
+ toMb(arrayPoolSize)
+ ", memory class limited? "
+ (targetMemoryCacheSize + targetBitmapPoolSize > maxSize)
+ ", max size: "
+ toMb(maxSize)
+ ", memoryClass: "
+ builder.activityManager.getMemoryClass()
+ ", isLowMemoryDevice: "
+ isLowMemoryDevice(builder.activityManager));
}
}
可以看到 Glide 是根據(jù)每個 App 的內(nèi)存情況,以及不同手機設(shè)備的版本和分辨率幌羞,計算出一個比較合理的初始值寸谜。關(guān)于 Glide 源碼分析大家可以看看這篇:第三方開源庫 Glide - 源碼分析(補)
5. 最后總結(jié)
工具的使用其實并不難,相信我們在網(wǎng)上找?guī)灼恼聦嵺`實踐新翎,就能很熟練找到其原因程帕。難度還在于我們需要了解 Android 的底層源碼住练,第三方開源庫的原理實現(xiàn)地啰。個人還是建議大家平時多去看看 Android Framework 層的源碼愁拭,多去學(xué)學(xué)第三方開源庫的內(nèi)部實現(xiàn),多了解數(shù)據(jù)結(jié)構(gòu)和算法亏吝。真正的做到治標又治本
在最后呢岭埠,還是要多方面提醒一下大家,本地的內(nèi)存卡頓還是比較容易處理的蔚鸥,因為我們手上有機型能復(fù)現(xiàn)惜论。比較難的是線上用戶手中的卡頓搜集,我們也不妨多花點時間做一些思考止喷。后面我也會出一系列文章用來幫助大家收集線上卡頓問題馆类。但大部分內(nèi)容都是基于 NDK ,因此性能優(yōu)化弹谁,很多時候往往也需要跟底層機制打交道乾巧。
視頻地址:https://pan.baidu.com/s/1jtuLBcV6l6sMKLiTDFMJDw
視頻密碼:svzw