我试图通过在自定义视图中覆盖onDraw以编程方式创建一个带有BlurMaskFilter图层(投影效果)的灰色Rect和黑色Rect。我可以让它在屏幕上绘制没有任何问题,但当我尝试将视图绘制到位图时,结果是不同的。在绘制到位图时,看起来BlueMaskFilter应用于View而不是黑色Rect的特定图层。
我所缺少的是使绘制的位图与屏幕上绘制的输出相同?
CustomView的onDraw覆盖:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// draw black box (shadow) first
RectF rectShadow = new RectF();
rectShadow.set(10, 10, 120, 120);
Paint shadowPaint = new Paint();
shadowPaint.setMaskFilter(new BlurMaskFilter(5, Blur.NORMAL));
shadowPaint.setStyle(Paint.Style.FILL);
shadowPaint.setColor(Color.DKGRAY);
shadowPaint.setAntiAlias(true);
canvas.drawRect(rectShadow, shadowPaint);
setLayerType(View.LAYER_TYPE_SOFTWARE, shadowPaint);
// draw grey box
RectF rectGray = new RectF();
rectGray.set(0, 0, 100, 100);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor("#656565"));
paint.setAntiAlias(true);
canvas.drawRoundRect(rectGray, paint);
}
将视图保存到位图的功能:
public void saveViewToBitmap( View customView int outWidth, int outHeight ) {
customView.setLayoutParams(new ViewGroup.LayoutParams(outWidth, outHeight));
customView.measure(
ViewGroup.MeasureSpec.makeMeasureSpec(customView.getLayoutParams().width,
ViewGroup.MeasureSpec.EXACTLY),
ViewGroup.MeasureSpec.makeMeasureSpec(customView.getLayoutParams().height,
ViewGroup.MeasureSpec.EXACTLY));
customView.layout(0, 0,
customView.getMeasuredWidth(), customView.getMeasuredHeight());
customView.requestLayout();
Bitmap outputBitmap = Bitmap.createBitmap(outWidth, outHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(outputBitmap);
customView.draw(canvas);
return outputBitmap;
}
请注意,在下面的图像中,屏幕图像的灰色矩形具有清晰的边缘,而绘制的位图使灰色矩形的顶部和左侧边缘模糊,以显示问题。
屏幕上的图片:http://i.stack.imgur.com/0Hl0t.png
从saveViewToBitmap创建的位图保存的图像:http://i.stack.imgur.com/xNzi5.png
谢谢!