mol*_*mol 37 android xml-drawable android-drawable
我查看了多个类似的问题,虽然我的查询没有找到正确的答案.
我有一个drawable,在shape.xml中定义
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="@color/bg_color" />
</shape>
Run Code Online (Sandbox Code Playgroud)
我想将其转换为Bitmap对象以执行某些操作,但BitmapFactory.decodeResource()返回null.
这就是我这样做的方式:
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.shape);
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?是BitmapFactory.decodeResource()适用于XML定义可绘制?
Phi*_*oda 65
由于您要加载a Drawable而不是a Bitmap,请使用以下命令:
Drawable d = getResources().getDrawable(R.drawable.your_drawable, your_app_theme);
Run Code Online (Sandbox Code Playgroud)
把它变成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;
}
Run Code Online (Sandbox Code Playgroud)
小智 9
Android KTX现在具有将可绘制对象转换为位图的扩展功能
val bitmap = ContextCompat.getDrawable(context, R.drawable.ic_user_location_pin)?.toBitmap()
if (bitmap != null) {
markerOptions.icon(BitmapDescriptorFactory.fromBitmap(bitmap))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19961 次 |
| 最近记录: |