動(dòng)態(tài)毛玻璃實(shí)現(xiàn)
?。?!源碼鏈接在最后?。?!
問題
在不斷變化的背景中,實(shí)現(xiàn)毛玻璃
思路
(1)監(jiān)聽布局繪制,動(dòng)態(tài)捕獲布局的畫像
(2)實(shí)時(shí)對(duì)布局的圖片進(jìn)行高斯模糊,繪制
實(shí)現(xiàn)
(1)監(jiān)聽實(shí)現(xiàn),只需要在監(jiān)聽的布局中,設(shè)置好監(jiān)聽回調(diào)即可。
監(jiān)聽為ViewTreeObserver.OnPreDrawListener。設(shè)置好以后,布局繪制信息發(fā)生改變的時(shí)候,都會(huì)回調(diào)。
這里選擇獲取頁面的decoreview作為監(jiān)聽的布局
protected View getActivityDecorView() {
Context ctx = getContext();
for (int i = 0; i < 4 && !(ctx instanceof Activity) && ctx instanceof ContextWrapper; i++) {
ctx = ((ContextWrapper) ctx).getBaseContext();
}
if (ctx instanceof Activity) {
return ((Activity) ctx).getWindow().getDecorView();
} else {
return null;
}
}
decoreview監(jiān)聽如下:
private final ViewTreeObserver.OnPreDrawListener preDrawListener = new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
··········
return true;
}
};
然后,就是核心的繪制了。這里基于decoreview,通過設(shè)置一層canvas進(jìn)行獨(dú)立的繪制,核心方法如下:
private final ViewTreeObserver.OnPreDrawListener preDrawListener = new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
if (!canBlur()) {
return true;
}
if (!blurInterval()) {
return true;
}
final int[] locations = new int[2];
Bitmap oldBmp = mBlurredBitmap;
View decor = mDecorView;
if (decor != null && isShown() && prepare() && checkScreenLocation(decor)) {
boolean redrawBitmap = mBlurredBitmap != oldBmp;
oldBmp = null;
decor.getLocationOnScreen(locations);
int x = -locations[0];
int y = -locations[1];
getLocationOnScreen(locations);
x += locations[0];
y += locations[1];
// just erase transparent
mBitmapToBlur.eraseColor(mOverlayColor & 0xffffff);
int rc = mBlurringCanvas.save();
mIsRendering = true;
RENDERING_COUNT++;
try {
mBlurringCanvas.scale(1.f * mBitmapToBlur.getWidth() / getWidth(), 1.f * mBitmapToBlur.getHeight() / getHeight());
mBlurringCanvas.translate(-x, -y);
if (decor.getBackground() != null) {
decor.getBackground().draw(mBlurringCanvas);
}
decor.draw(mBlurringCanvas);
} catch (StopException e) {
} finally {
mIsRendering = false;
RENDERING_COUNT--;
mBlurringCanvas.restoreToCount(rc);
}
if (canBlur()) {
blur(mBitmapToBlur, mBlurredBitmap);
}
if ((redrawBitmap || mDifferentRoot) && canBlur()) {
Log.d(TAG, "onPreDraw identify: " + mIdentify);
postInvalidate();
}
}
return true;
}
};
可以看出,這里直接通過屏幕高度方法 getLocationOnScreen();進(jìn)行坐標(biāo)獲取,在進(jìn)行坐標(biāo)計(jì)算,bitmap截取,繪制,實(shí)現(xiàn)了動(dòng)態(tài)毛玻璃的效果。但是,這種相關(guān)僅僅使用于非視頻層級(jí),視頻播放層級(jí)(surfaceview),目前還是沒有毛玻璃效果的,暫未想到解決方案。
話說回來:
實(shí)現(xiàn)毛玻璃的方法,是使用安卓原生的api:RenderScript進(jìn)行實(shí)現(xiàn)。這里沒啥好說的。
注意
在recyclerview中,實(shí)現(xiàn)動(dòng)態(tài)毛玻璃,需要特別適配,目前只適配了出現(xiàn)時(shí)的item顯示毛玻璃,其余適配將會(huì)放到下一個(gè)博客,敬請(qǐng)期待??!
that's all-------------------------------------------------
(代碼地址--庫libpicblur)[https://gitee.com/motosheep/androidutils-github]