Drawable和Bitmap无法绘制的几个问题
1个回答
展开全部
1.canvas.drawBitmap无法绘制或绘制空白的问题:
通过自定义属性获取的图片资源一般为Drawable,需要使用该方法绘制时需要将Drawable转换为Bitmap,但是这里转换为bitmap有几个坑:
第一,mBitmap = Bitmap.createBitmap(imgRes.getIntrinsicWidth(), imgRes.getIntrinsicHeight(),imgRes.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
这个转换无效绘制图片无法展示。
第二,当图片资源设置为AdaptiveIconDrawable时,即app的icon资源时,无法绘制。
正确的转换方法为:
private BitmapgetmBitmap(Drawable drawable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (drawableinstanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}else if (drawableinstanceof AdaptiveIconDrawable) {
Drawable[] drr =new Drawable[2];
drr[0] = ((AdaptiveIconDrawable) drawable).getBackground();
drr[1] = ((AdaptiveIconDrawable) drawable).getForeground();
LayerDrawable layerDrawable =new LayerDrawable(drr);
int width = layerDrawable.getIntrinsicWidth();
int height = layerDrawable.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas =new Canvas(bitmap);
layerDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
layerDrawable.draw(canvas);
return bitmap;
}
}else {
return ((BitmapDrawable) drawable).getBitmap();
}
return null;
}
2.通过Drawable.draw()方法绘制图片为空白,当使用Drawable的draw绘制时一定要加上这句话:
imgRes.setBounds(new Rect(0,0,imgRes.getIntrinsicWidth(),imgRes.getIntrinsicHeight()));
才有效!!!
通过自定义属性获取的图片资源一般为Drawable,需要使用该方法绘制时需要将Drawable转换为Bitmap,但是这里转换为bitmap有几个坑:
第一,mBitmap = Bitmap.createBitmap(imgRes.getIntrinsicWidth(), imgRes.getIntrinsicHeight(),imgRes.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
这个转换无效绘制图片无法展示。
第二,当图片资源设置为AdaptiveIconDrawable时,即app的icon资源时,无法绘制。
正确的转换方法为:
private BitmapgetmBitmap(Drawable drawable) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (drawableinstanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}else if (drawableinstanceof AdaptiveIconDrawable) {
Drawable[] drr =new Drawable[2];
drr[0] = ((AdaptiveIconDrawable) drawable).getBackground();
drr[1] = ((AdaptiveIconDrawable) drawable).getForeground();
LayerDrawable layerDrawable =new LayerDrawable(drr);
int width = layerDrawable.getIntrinsicWidth();
int height = layerDrawable.getIntrinsicHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas =new Canvas(bitmap);
layerDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
layerDrawable.draw(canvas);
return bitmap;
}
}else {
return ((BitmapDrawable) drawable).getBitmap();
}
return null;
}
2.通过Drawable.draw()方法绘制图片为空白,当使用Drawable的draw绘制时一定要加上这句话:
imgRes.setBounds(new Rect(0,0,imgRes.getIntrinsicWidth(),imgRes.getIntrinsicHeight()));
才有效!!!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询