在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
产生的模糊效果保持一致。