Android,View转换bitmap,bitmap转换drawable

bitmap转换drawable

View view1 = ViewGroup.inflate(context, R.layout.drawable_icon, null);
 Bitmap bitmap = createViewBitmap(view1);
 Drawable drawable=new BitmapDrawable(getResources(),bitmap);

View转换成Bitmap

public Bitmap createViewBitmap(View v) {
        Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(),
                Bitmap.Config.ARGB_8888); //创建一个和View大小一样的Bitmap
        Canvas canvas = new Canvas(bitmap);  //使用上面的Bitmap创建canvas
        v.draw(canvas);  //把View画到Bitmap上
        return bitmap;
    }

注意:v.getWidth()v.getHeight() 时 获取到的值可能为:0
导致报错:

java.lang.IllegalArgumentException: width and height must be > 0

解决办法可以参考:获取View的width和Height为0的解决方法

猜你喜欢

转载自blog.csdn.net/lxd_love_lgc/article/details/107759995