如何将ColorDrawable转换为Bitmap?谷歌登录头像保存遇此难题
搞定谷歌头像保存的小问题
嘿,作为新手能想到用Glide加载头像已经很棒了!不过你现在的方法确实绕了弯路,而且遇到的ColorDrawable问题其实是个小坑——大概率是你在Glide还没加载完头像的时候,就急着去拿ImageView的Drawable了,这时候ImageView显示的是默认占位色,所以拿到的是纯色的ColorDrawable,而不是你要的头像Bitmap。
我给你两个方案,优先推荐第一个最优解:
最优方案:直接用Glide获取Bitmap,跳过ImageView中转
完全没必要把头像先加载到ImageView再去抠Bitmap,Glide本身就支持直接获取加载后的Bitmap,这样既高效又不会出错。用CustomTarget<Bitmap>就能轻松实现:
String profilePicUrl = googleSignInAccount.getPhotoUrl().toString(); Glide.with(this) .asBitmap() // 指定加载为Bitmap类型 .load(profilePicUrl) .into(new CustomTarget<Bitmap>() { @Override public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) { // 头像加载完成!直接拿到Bitmap,调用你的保存方法就行 savePicToInternalStorage(resource); } @Override public void onLoadCleared(@Nullable Drawable placeholder) { // 这里可以处理加载被取消的情况,比如释放资源,新手暂时可以空着 } });
这样一步到位,根本不需要中间的ImageView,完美解决你的保存需求。
退而求其次:如果一定要转ColorDrawable为Bitmap(不推荐)
如果你只是好奇怎么把ColorDrawable转成Bitmap(毕竟这不是你要的头像,只是占位色),可以通过创建Bitmap然后绘制颜色的方式:
ColorDrawable drawable = (ColorDrawable) intermediaryIV.getDrawable(); int solidColor = drawable.getColor(); // 创建和ImageView尺寸一致的Bitmap Bitmap bitmap = Bitmap.createBitmap(intermediaryIV.getWidth(), intermediaryIV.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); canvas.drawColor(solidColor); // 现在这个bitmap就是ColorDrawable对应的纯色图了 savePicToInternalStorage(bitmap);
但再次提醒:这个方法只能得到纯色图,不是你的谷歌头像,所以优先用第一个方案哦!
内容的提问来源于stack exchange,提问作者chargerstriker
相关产品推荐
相关产品推荐

