How to prevent Android's drawBitmap from only

2019-01-21 03:22发布

问题:

As per the original question, The end result is a rounded-rect png in an ImageView with a natural looking drop shadow.

I have the shadow working, but when it draws, it makes the entire image black.

How can I prevent the original image (definitely not black) from being black when adding the shadow?

    BlurMaskFilter blurFilter = new BlurMaskFilter(2, BlurMaskFilter.Blur.OUTER);
    Paint shadowPaint = new Paint();
    shadowPaint.setMaskFilter(blurFilter);

    int[] offsetXY = new int[2];
    Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pier_t);
    Bitmap shadowImage = originalBitmap.extractAlpha(shadowPaint, offsetXY);

    Canvas c = new Canvas(shadowImage);
    c.drawBitmap(originalBitmap, -offsetXY[0], -offsetXY[1], null);

    imageView.setImageBitmap(shadowImage);





UPDATE:

I implemented Josh's suggestion about copying over to the correct color space and now it works great! For future searchers, this code produces a drop shadow on an image view. You can play around with the x and y, as well as the OUTER constant to get the desired effect.

BlurMaskFilter blurFilter = new BlurMaskFilter(2, BlurMaskFilter.Blur.OUTER);
Paint shadowPaint = new Paint();
shadowPaint.setMaskFilter(blurFilter);

int[] offsetXY = new int[2];
Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pier_t);
Bitmap shadowImage = originalBitmap.extractAlpha(shadowPaint, offsetXY);
Bitmap shadowImage32 = shadowImage.copy(Bitmap.Config.ARGB_8888, true);

Canvas c = new Canvas(shadowImage32);
c.drawBitmap(originalBitmap, -offsetXY[0], -offsetXY[1], null);

imageView.setImageBitmap(shadowImage32);

回答1:

I commented in your last question, but here it is again.

The problem might be that you're drawing a 32-bit image (the original) onto an 8-bit image (the extracted shadowImage). If that's the case, do something like

Bitmap shadowImage32 = shadowImage.copy(ARGB_8888, true);

after the extractAlpha call, and draw onto that guy instead of the 8-bit shadowImage.



回答2:

You have to draw both the shadow image and the original image. The shadow image only contains the alpha values of the original image, not the actual colored pixels.