在我的项目中有这么一个功能需要把网络图片保存到本地,但是我这个是一个背景图和一张二维码,这些都是在本地是组合而成的,我的开始的思路是直接保存图片,但是这样保存下来是分开的,
这个是我效果图样式,我作为技术菜鸟能想到的把这块区域截下来不就行了吗就是干`
public class MainActivity extends Activity {
public Context context;
public Activity activity;
public Bitmap bitmap;
public int x, y, width, height;
public LinearLayout Layout;//最外层布局
public Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
activity = this;//
btn= (LinearLayout) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 裁取屏幕的指定大小
bitmap = takeScreenShotClip(activity, x, y, width, height);
boolean ok = savePic(bitmap, “sdcard/xx.png”);
if (ok) {
imageView.setImageBitmap(bitmap);
getBitmap(bitmap);//通知图库更新
Toast.makeText(context, “保存成功”, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, “保存失败”, Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
setOptions(linyout);//firstLayout
}
public static boolean savePic(Bitmap b, String strFileName) {
boolean sucess = false;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(strFileName);
if (null != fos)
{
b.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
sucess = true;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sucess;
}
//开始截图
public static Bitmap takeScreenShotClip(Activity activity,int x,int y,int width,int height) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
System.out.println(statusBarHeight);
// int width = activity.getWindowManager().getDefaultDisplay().getWidth();
// int height = activity.getWindowManager().getDefaultDisplay().getHeight();
Bitmap b = Bitmap.createBitmap(b1, x, y, width, height);
view.destroyDrawingCache();
return b;
}
//计算控件截取位置
private void setOptions(LinearLayout pLayout) {
int bottom = pLayout.getBottom();
int top = pLayout.getTop();
int left = pLayout.getLeft();
int right = pLayout.getRight();
float xx = pLayout.getX();
float yy = pLayout.getY();
//pLayout.getParent();
Log.e("getLocationInWindow", "bottom:" + bottom + "top:" + top + "left:" + left + "right:" + right + "xx:" + xx + "yy:" + yy);
x = left;
y = top;
width = right - left;
height = bottom - top;
Log.e("getWindowFocusChanged", "x:" + x + "y:" + y + "width:" + width + "height:" + height);
}
}
`