इसलिए अन्य उत्तरों की तलाश (और उपयोग) के बाद, लगता है कि वे सभी को संभाल रहे हैं ColorDrawableऔर PaintDrawableबुरी तरह से। (विशेष रूप से लॉलीपॉप पर) ऐसा लगता था कि Shaderरंगों का ठोस ब्लॉक ठीक से संभाला नहीं गया था।
मैं अब निम्नलिखित कोड का उपयोग कर रहा हूं:
public static Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
// We ask for the bounds if they have been set as they would be most
// correct, then we check we are > 0
final int width = !drawable.getBounds().isEmpty() ?
drawable.getBounds().width() : drawable.getIntrinsicWidth();
final int height = !drawable.getBounds().isEmpty() ?
drawable.getBounds().height() : drawable.getIntrinsicHeight();
// Now we check we are > 0
final Bitmap bitmap = Bitmap.createBitmap(width <= 0 ? 1 : width, height <= 0 ? 1 : height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
दूसरों के विपरीत, यदि आप फोन setBoundsपर Drawableयह एक बिटमैप में बदलने के लिए पूछ रहा से पहले, यह बिटमैप सही आकार में आकर्षित करेगा!