其实实现方式很简单,首先我们需要做的就是截取整个屏幕生成一个bitmap对象
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
bitmap = view.getDrawingCache();
然后我们需呀计算出我们选定区域的坐标点,注意正选和反选的计算方式不同 ,
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
x = 0;
y = 0;
width = 0;
height = 0;
x = (int) event.getX();
y = (int) event.getY();
}
if(event.getAction() == MotionEvent.ACTION_MOVE){
m = (int) event.getX();
n = (int) event.getY();
myView.setSeat(x, y, m, n);
myView.postInvalidate();
}
if(event.getAction() == MotionEvent.ACTION_UP){
if(event.getX()>x){
width = (int)event.getX()-x;
}else{
width = (int)(x-event.getX());
x = (int) event.getX();
}
if(event.getY()>y){
height = (int) event.getY()-y;
}else{
height = (int)(y-event.getY());
y = (int) event.getY();
}
image2.setImageBitmap(getBitmap(this));
}
if(myView.isSign()){
return false;
}else{
return true;
}
}
然后为我们计算出来的坐标区域添加选中效果
protected void onDraw(Canvas canvas) {
if(sign){
paint.setColor(Color.TRANSPARENT);
}else{
paint.setColor(Color.RED);
paint.setAlpha(80);
canvas.drawRect(new Rect(x, y, m, n), paint);
}
super.onDraw(canvas);
}
最后生成我们需要的图片展示出来,顺便保存到SD卡下一张。
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int toHeight = frame.top;
bitmap = Bitmap.createBitmap(bitmap, x, y+2*toHeight, width, height);
try {
FileOutputStream fout = new FileOutputStream("mnt/sdcard/test.png");
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fout);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
view.setDrawingCacheEnabled(false);