需求:最新开发,有几个渐变色的背景,因为图片比较大,为减小应用体积,用drawable资源文件来加载,然后代码转为Bitmap在设置背景。
实现: 1、drawable文件(色值随意定的,只是demo):
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!--实现应用背景颜色渐变-->
<gradient
android:startColor="@color/colorAccent"
android:endColor="@color/colorPrimaryDark"
android:angle="270"/>
</shape>
2、代码中转Bitmap
private Bitmap getBitmapGradient(){
Drawable drawable = mContext.getResources().getDrawable(R.drawable.background_gradient);
GradientDrawable gradientDrawable = (GradientDrawable) drawable;
//我这图片宽高是全局变量mWidth,mHeight
bitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
gradientDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
gradientDrawable.draw(canvas);
return bitmap;
}
参考链接: Converting GradientDrawable to Bitmap
参考代码:
public static Bitmap drawableToBitmap(Context mContext, int drawableInt) {
Bitmap bitmap;
Drawable drawable = getDrawable(mContext, drawableInt);
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}else if(drawable instanceof GradientDrawable){
GradientDrawable gradientDrawable = (GradientDrawable) drawable;
bitmap = Bitmap.createBitmap(140, 140, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
gradientDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
gradientDrawable.draw(canvas);
return bitmap;
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
|