BitmapFactory.decodeResource() returns null for shape defined in xml drawable

后端 未结 4 1400
有刺的猬
有刺的猬 2020-12-14 14:25

I looked through multiple similar questions, although I haven\'t found proper answer on my query.

I have a drawable, defined in shape.xml



        
相关标签:
4条回答
  • 2020-12-14 14:47
    public static Bitmap convertDrawableResToBitmap(@DrawableRes int drawableId, Integer width, Integer height) {
        Drawable d = getResources().getDrawable(drawableId);
    
        if (d instanceof BitmapDrawable) {
            return ((BitmapDrawable) d).getBitmap();
        }
    
        if (d instanceof GradientDrawable) {
            GradientDrawable g = (GradientDrawable) d;
    
            int w = d.getIntrinsicWidth() > 0 ? d.getIntrinsicWidth() : width;
            int h = d.getIntrinsicHeight() > 0 ? d.getIntrinsicHeight() : height;
    
            Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            g.setBounds(0, 0, w, h);
            g.setStroke(1, Color.BLACK);
            g.setFilterBitmap(true);
            g.draw(canvas);
            return bitmap;
        }
    
        Bitmap bit = BitmapFactory.decodeResource(getResources(), drawableId);
        return bit.copy(Bitmap.Config.ARGB_8888, true);
    }
    
    //------------------------
    
    Bitmap b = convertDrawableResToBitmap(R.drawable.myDraw , 50, 50);
    
    0 讨论(0)
  • 2020-12-14 14:57

    it is a drawable, not a bitmap. You should use getDrawable instead

    0 讨论(0)
  • 2020-12-14 14:57

    You may have put .xml into directory:.../drawable-24, and try to put it into .../drawable instead.

    it works for me, hope this can help someone.

    0 讨论(0)
  • 2020-12-14 15:05

    Since you want to load a Drawable, not a Bitmap, use this:

    Drawable d = getResources().getDrawable(R.drawable.your_drawable, your_app_theme);
    

    To turn it into a Bitmap:

    public static Bitmap drawableToBitmap (Drawable drawable) {
    
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable)drawable).getBitmap();
        }
    
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap); 
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
    
        return bitmap;
    }
    

    Taken from: How to convert a Drawable to a Bitmap?

    0 讨论(0)
提交回复
热议问题