|
2 | 2 |
|
3 | 3 | import android.content.Context; |
4 | 4 | import android.content.res.Resources; |
| 5 | +import android.graphics.Bitmap; |
| 6 | +import android.graphics.Canvas; |
| 7 | +import android.graphics.drawable.BitmapDrawable; |
| 8 | +import android.graphics.drawable.Drawable; |
| 9 | +import android.graphics.drawable.ScaleDrawable; |
| 10 | +import android.graphics.drawable.VectorDrawable; |
5 | 11 | import android.os.Build; |
6 | 12 | import androidx.annotation.AttrRes; |
7 | 13 | import androidx.annotation.ColorInt; |
| 14 | +import androidx.annotation.DrawableRes; |
| 15 | +import androidx.appcompat.content.res.AppCompatResources; |
8 | 16 | import androidx.core.content.ContextCompat; |
| 17 | +import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat; |
| 18 | + |
9 | 19 | import android.text.Html; |
10 | 20 | import android.text.Spanned; |
11 | 21 | import android.text.TextUtils; |
@@ -231,4 +241,32 @@ public static double elevationFromNmea(String nmea) { |
231 | 241 | return NO_ELEVATION_VALUE; |
232 | 242 | } |
233 | 243 |
|
| 244 | + /** |
| 245 | + * Bitmap from vector drawable |
| 246 | + * |
| 247 | + * @param context |
| 248 | + * @param drawableId |
| 249 | + * @return |
| 250 | + */ |
| 251 | + public static Bitmap getBitmapFromDrawable(Context context, @DrawableRes int drawableId, int alpha) { |
| 252 | + Drawable drawable = AppCompatResources.getDrawable(context, drawableId); |
| 253 | + drawable.setAlpha(alpha); |
| 254 | + if (drawable instanceof BitmapDrawable) { |
| 255 | + return ((BitmapDrawable) drawable).getBitmap(); |
| 256 | + } else if (drawable instanceof VectorDrawableCompat) { |
| 257 | + return createBitmap(drawable); |
| 258 | + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && drawable instanceof VectorDrawable) { |
| 259 | + return createBitmap(drawable); |
| 260 | + } else { |
| 261 | + throw new IllegalArgumentException("unsupported drawable type"); |
| 262 | + } |
| 263 | + } |
| 264 | + |
| 265 | + private static Bitmap createBitmap(Drawable drawable) { |
| 266 | + Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); |
| 267 | + Canvas canvas = new Canvas(bitmap); |
| 268 | + drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); |
| 269 | + drawable.draw(canvas); |
| 270 | + return bitmap; |
| 271 | + } |
234 | 272 | } |
0 commit comments