项目背景:首先已经实现了一个折线图,可能存在N个颜色,需要将这个折线图存成bitmap,并去色,当做点击按钮的背景图片
如下图是实现结果:
要实现的就是红色框图部分
首先,建立一个util类:
/**
<span style="white-space:pre"> </span> * @Title: getRecordImage
<span style="white-space:pre"> </span> * @Description: 给bitmap去色
<span style="white-space:pre"> </span> * 2014年9月5日
<span style="white-space:pre"> </span> * </p>
<span style="white-space:pre"> </span> * @param 需要处理的mBitmap
<span style="white-space:pre"> </span> * @param 替换颜色 changeColor
<span style="white-space:pre"> </span> * @param 被替换的颜色 oldColor
<span style="white-space:pre"> </span> * @return Bitmap 去色后,上色完的图片
<span style="white-space:pre"> </span> * @author: aimee.zhang
<span style="white-space:pre"> </span> */
public class BitmapUtil {
public static Bitmap getRecordImage(Bitmap mBitmap, int changeColor, String[] oldColor) {
int mBitmapWidth = mBitmap.getWidth();
int mBitmapHeight = mBitmap.getHeight();
List<String> oldColorList = Arrays.asList(oldColor);
int mArrayColor[] = new int[mBitmapWidth * mBitmapHeight];
int count = 0;
for (int i = 0; i < mBitmapHeight; i++) {
for (int j = 0; j < mBitmapWidth; j++) {
// 获得Bitmap 图片中每一个点的color颜色值
int color = mBitmap.getPixel(j, i);
if (oldColorList.contains(subColor(color))) {
color = changeColor;
} else {
color = Color.parseColor("#e6e6e6");//折线图背景色
}
// 将颜色值存在一个数组中 方便后面修改
mArrayColor[count] = color;
count++;
}
}
mBitmap = Bitmap.createBitmap(mArrayColor, mBitmapWidth, mBitmapHeight, Config.ARGB_8888);
return mBitmap;
}
public static String subColor(int color) {
String oldColor = "#"+ Integer.toHexString(color);
return oldColor;
}
}
/**
* @Title: ChartBitmap
* @Description: 获取LL_lineChart的截图,保存bitmap,将截图去色,再在保留的轮廓中填上设计颜色 2014年9月5日
* @author: aimee.zhang
*/
private void ChartBitmap() {
LL_lineChart.destroyDrawingCache();
LL_lineChart.setDrawingCacheEnabled(true);
LL_lineChart.buildDrawingCache();
Bitmap catchbitmap = LL_lineChart.getDrawingCache();
try {
File sdDir = null;
boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
if (sdCardExist) // 如果SD卡存在,则获取跟目录
{
sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
}
File myCaptureFile = new File(sdDir + "/aa.jpg");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
LL_lineChart.getDrawingCache().compress(Bitmap.CompressFormat.JPEG,
80, bos);//将LL_lineChart区域截图,并保存
bos.flush();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
if (catchbitmap != null) {
Bitmap bitmap = Bitmap.createBitmap(catchbitmap, 40, 0, catchbitmap.getWidth() - 40,
catchbitmap.getHeight() - 70);
LL_appserver_respTime.setBackgroundDrawable(new BitmapDrawable(BitmapUtil.getRecordImage(bitmap,
Color.parseColor("#dddcdc"), lineColors)));//将LL_appserver_respTime的背景设置成经过去色后上色的bitmap
} else {
Log.i("CACHE_BITMAP", "DrawingCache=null");
}
}