为ImageView添加阴影

时间:2016-01-09 10:39:46

标签: android xml image android-imageview shadow

我想为ImageView添加阴影(右侧和底侧) 下面我发布了两张带阴影效果的图片 我想要相同的阴影效果。

如何将此阴影效果应用于我的ImageView?

右侧阴影的图像
enter image description here

带有右下阴影的图像
enter image description here

2 个答案:

答案 0 :(得分:6)

设置填充大小右侧和底部,背景设置阴影

<ImageView
    android:id="@+id/imageview"
    android:background="@drawable/drop_shadow"
    <!--android:background="#660000"--> This breaks the syntax highlight
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"        
    android:paddingRight="10px"
    android:paddingBottom="10px"
    android:src="@drawable/pic1"
/>

答案 1 :(得分:4)

尝试使用位图

    public Bitmap imgshadow(final Bitmap bm, final int dstHeight, final int dstWidth, int color, int size, float dx, float dy) {
        final Bitmap mask = Bitmap.createBitmap(dstWidth, dstHeight, 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, 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(Mode.SRC_OUT));
        maskCanvas.drawBitmap(bm, dropShadow, paint);

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

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



 final Bitmap src = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    final Bitmap shadows = imgshadow(src, src.getHeight(), src.getWidth(), Color.BLACK, 3, 1, 3);
    final ImageView iv = (ImageView)findViewById(R.id.imageview1);
    iv.setImageBitmap(shadows);