我在programatically中为我的活动创建了截图。工作完美。我在拍摄我的活动中显示的图像后出现问题。如何隐藏它?
我的代码:
public class MainActivity extends AppCompatActivity {
File cacheDir;
final Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button print = (Button) findViewById(R.id.btn_print);
print.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
takeScreenShot();
}
});
}
private void takeScreenShot() {
View u = findViewById(R.id.activity_main);
int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
u.measure(spec, spec);
u.layout(0, 0, u.getMeasuredWidth(), u.getMeasuredHeight());
Bitmap b = getBitmapFromView(u,u.getMeasuredHeight(),u.getMeasuredWidth());
final String root = Environment.getExternalStorageDirectory().toString();
File myPath = new File(root + "/saved_img");
myPath.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+n+".jpg";
File file = new File(myPath, fname);
FileOutputStream fos = null;
if(file.exists()) file.delete();
try{
fos = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch(FileNotFoundException e){
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
Toast.makeText(this,"screen captured",Toast.LENGTH_SHORT).show();
}
public Bitmap getBitmapFromView(View u, int totalHeight, int totalWidth){
Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth,totalHeight , Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = u.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
u.draw(canvas);
return returnedBitmap;
}
}
如何解决这个问题?我点击按钮之前的输出图像,
这是我输出2后点击按钮, enter image description here
答案 0 :(得分:0)
这是我的错误。在获取屏幕截图后,我在捕获图像大小时设置了布局大小(基于获取测量宽度和高度)我删除了程序中的下面一行,它完美地工作。
u.layout(0,0,u.getMeasuredWidth(),u.getMeasuredHeight());
因为该行设置保存图像精确高度&宽度进入当前布局。那个错误。我解决了它。感谢所有人的帮助。再次感谢...