在Android中,BlurMaskFilter
用于對視圖應用模糊效果。處理不同分辨率時,需要注意以下幾點:
dp
單位而不是px
單位設置模糊半徑。這樣可以確保在不同分辨率的屏幕上,模糊效果的一致性。float blurRadiusInDp = 10;
float density = getResources().getDisplayMetrics().density;
float blurRadiusInPixels = blurRadiusInDp * density;
BlurMaskFilter
對象時,使用計算出的blurRadiusInPixels
值。BlurMaskFilter blurMaskFilter = new BlurMaskFilter(blurRadiusInPixels, BlurMaskFilter.BlurStyle.NORMAL);
BlurMaskFilter
應用到Canvas
上。View view = findViewById(R.id.my_view);
Canvas canvas = new Canvas(view.getBitmap());
canvas.drawColor(Color.WHITE); // 設置背景顏色
view.setLayerType(View.LAYER_TYPE_SOFTWARE, blurMaskFilter);
res/drawable
目錄下創建多個尺寸的模糊遮罩圖片資源。然后,根據設備的屏幕密度,選擇合適的圖片資源。int density = getResources().getDisplayMetrics().density;
int resourceId;
if (density >= 2.0) {
resourceId = R.drawable.blur_mask_hdpi;
} else if (density >= 1.5) {
resourceId = R.drawable.blur_mask_mdpi;
} else {
resourceId = R.drawable.blur_mask_ldpi;
}
Drawable blurMaskDrawable = getResources().getDrawable(resourceId);
blurMaskDrawable.setBounds(0, 0, blurMaskDrawable.getIntrinsicWidth(), blurMaskDrawable.getIntrinsicHeight());
blurMaskDrawable
應用到BlurMaskFilter
對象。ShapeDrawable shapeDrawable = (ShapeDrawable) blurMaskDrawable;
float[] points = new float[shapeDrawable.getShape().nPoints];
shapeDrawable.getShape().getPoints(points);
float[] matrix = new float[9];
Matrix.setRectToRect(matrix, 0, 0, shapeDrawable.getIntrinsicWidth(), shapeDrawable.getIntrinsicHeight(), 0, 0, view.getWidth(), view.getHeight());
blurMaskFilter.setMatrix(matrix);
Canvas
繪制到視圖上。canvas.drawBitmap(view.getBitmap(), 0, 0, null);
canvas.drawPath(shapeDrawable.getPath(), blurMaskFilter);
通過以上方法,可以確保在不同分辨率的屏幕上,BlurMaskFilter
產生的模糊效果保持一致。