推荐安卓开发神器(里面有各种UI特效和android代码库实例)
android中开发中,有时候为了某种效果需要给ImageView 或者LinearLayout画阴影。
为ImageView画阴影的主要的思想利用已知图片,然后构造一个阴影的bitmap。最后设置阴影的bitmap作为ImageView的背景。
这里参考了一个帖子:http://stackoverflow.com/questions/3567312/android-drop-shadow-on-view
利用这个思想。构造代码如下:
public void drawImageDropShadow(){ BlurMaskFilter blurFilter = new BlurMaskFilter(3, BlurMaskFilter.Blur.OUTER); Paint shadowPaint = new Paint(); shadowPaint.setMaskFilter(blurFilter); int[] offsetXY =new int[2]; Bitmap originalBitmap = BitmapFactory.decodeResource(this.getResources(),R.drawable.favoritelist); Bitmap shadowBitmap = originalBitmap.extractAlpha(shadowPaint,offsetXY); Bitmap shadowImage32 = shadowBitmap.copy(Bitmap.Config.ARGB_8888, true); Canvas c = new Canvas(shadowImage32); c.drawBitmap(originalBitmap, 0,0, null); ImageView imageView1 = (ImageView)findViewById(R.id.shadowImageView); imageView1.setImageBitmap(shadowImage32); }
下面是设置LinearLayout的背景。用xml文件画Rectangle来作为LinearLayout的背景。思想和前面的一样。不同的是通过.xml创建一个Drawable,然后
制定 宽和高, 将Drawable转化bitmap 画阴影bitmap,然后将阴影bitmap转化为drawable,最后将drawable设置为LinearLayout的背景。
代码如下:
说明需要一个方法:将drawable转化为bitmap
一般通用的方法为:
public static Bitmap drawableToBitmap(Drawable drawable) { Bitmap bitmap = Bitmap .createBitmap( drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); //canvas.setBitmap(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; }
我创建的drawable是一个xml文件,而不是图片,所以,drawable.getIntrinsicHeight()得不到值。所以要手动传递参数设宽度和高度。代码如下:
private Bitmap drawableToBitmap(Drawable drawable,int width,int height) { Bitmap bitmap = Bitmap.createBitmap( width, height, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, width, height); drawable.draw(canvas); return bitmap; }
最后设置阴影的代码:
public void drawLayoutDropShadow(){ LinearLayout linearLayout = (LinearLayout)findViewById(R.id.testShadowLinearLayout); BlurMaskFilter blurFilter = new BlurMaskFilter(3, BlurMaskFilter.Blur.OUTER); Paint shadowPaint = new Paint(); shadowPaint.setMaskFilter(blurFilter); Drawable drawable = this.getResources().getDrawable(R.drawable.backgroundservicescolor); int[] offsetXY =new int[2]; Bitmap originalBitmap = drawableToBitmap(drawable,200,100); Bitmap shadowBitmap = originalBitmap.extractAlpha(shadowPaint,offsetXY); Bitmap shadowImage32 = shadowBitmap.copy(Bitmap.Config.ARGB_8888, true); Canvas c = new Canvas(shadowImage32); c.drawBitmap(originalBitmap, 0,0, null); Drawable d =new BitmapDrawable(shadowImage32); linearLayout.setBackgroundDrawable(d); }
最后的效果如下: