在android中添加阴影到位图

时间:2017-04-29 09:23:04

标签: android picasso

我使用Picasso将drawable加载到图像中。我需要为我创建的位图添加一个Drophadow,我试图通过添加ShadowTransformation来实现这一点。

使用此 This stackoverflow answer我到目前为止有这个:

public class DropShadowTransformation implements Transformation {


    @Override
    public Bitmap transform(Bitmap source) {
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setShadowLayer(12, 0, 0, Color.YELLOW);
        // Important for certain APIs
        paint.setShadowLayer(4,source.getWidth(),source.getHeight(),10);
        int[] offsetXY = new int[2];
        Bitmap shadowImage = source.extractAlpha(paint, offsetXY);
        Bitmap shadowImage32 = shadowImage.copy(Bitmap.Config.ARGB_8888, true);
        final Bitmap shadow = addShadow(shadowImage32, shadowImage32.getHeight(), shadowImage32.getWidth(), Color.BLACK, 3, 1, 3);


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

        source.recycle();
        return shadowImage32;

    }

    @Override
    public String key() {
        return "dropshadow";
    }

    public Bitmap addShadow(final Bitmap bm, final int dstHeight, final int dstWidth, int color, int size, float dx, float dy) {
        final Bitmap mask = Bitmap.createBitmap(dstWidth, dstHeight, Bitmap.Config.ALPHA_8);

        final Matrix scaleToFit = new Matrix();
        final RectF src = new RectF(0, 0, bm.getWidth(), bm.getHeight());
        final RectF dst = new RectF(0, 0, dstWidth - dx, dstHeight - dy);
        scaleToFit.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER);

        final Matrix dropShadow = new Matrix(scaleToFit);
        dropShadow.postTranslate(dx, dy);

        final Canvas maskCanvas = new Canvas(mask);
        final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        maskCanvas.drawBitmap(bm, scaleToFit, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
        maskCanvas.drawBitmap(bm, dropShadow, paint);

        final BlurMaskFilter filter = new BlurMaskFilter(size, BlurMaskFilter.Blur.NORMAL);
        paint.reset();
        paint.setAntiAlias(true);
        paint.setColor(color);
        paint.setMaskFilter(filter);
        paint.setFilterBitmap(true);

        final Bitmap ret = Bitmap.createBitmap(dstWidth, dstHeight, Bitmap.Config.ARGB_8888);
        final Canvas retCanvas = new Canvas(ret);
        retCanvas.drawBitmap(mask, 0,  0, paint);
        retCanvas.drawBitmap(bm, scaleToFit, null);
        mask.recycle();
        return ret;
    }

}

我在gridview适配器中使用它

 Picasso.with(context).load(id).noFade().transform(new DropShadowTransformation()).resize(400,400).into(myImageView);

但是,尽管谷歌搜索尝试了几种不同风格的addShadow,但我没有运气。 DO显示图像,但没有任何阴影。

谢谢

1 个答案:

答案 0 :(得分:0)

尝试将回调添加到毕加索代码 -

setfield