逛论坛看到别人有这个需求,自己也是打酱油,就写了一把。
界面如下:
主要有一个半透明的矩形框,用作截取区域。一个ok按钮,确定截取。一个图片控件,显示图片。
功能需求:
1.多点放大缩小图片;
2.移动图片;
3.提供预览。
我一开始的思路是这样的:
用户放大缩小图片时,记住缩放比例,然后确定时,按照比例来截图。但是有个问题:如何确定是哪块处于半透明框中?因为可以移动图片的。这就不好计算了。
后来想到一个简单的方法:
用户放大或缩小图片之后,点OK时,截取屏幕的截图。然后再计算出半透明矩形框的位置,截图。这样就避免了繁琐的计算来确定截图位置。
实现过程:
1.截取屏幕图像:
// 获取Activity的截屏,this指向一个activity
private Bitmap takeScreenShot()
{
View view = this.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
return view.getDrawingCache();
}
2.获取状态栏、标题栏的高度
int statusBarHeight = 0;
int titleBarHeight = 0;
private void getBarHeight()
{
// 获取状态栏高度
Rect frame = new Rect();
this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
statusBarHeight = frame.top;
int contenttop = this.getWindow()
.findViewById(Window.ID_ANDROID_CONTENT).getTop();
// statusBarHeight是上面所求的状态栏的高度
titleBarHeight = contenttop - statusBarHeight;
}
3.多点缩放图片
这段代码比较多,我就补贴代码了。看源码http://www.oschina.net/code/snippet_195456_34166吧。
4.创建半透明矩形区域
继承view,自绘。
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
/*这里就是绘制矩形区域*/
int width = this.getWidth();
int height = this.getHeight();
Paint paint = new Paint();
paint.setColor(0xaa000000);
//top
canvas.drawRect(0, 0, width, height/3, paint);
//left
canvas.drawRect(0, height/3, (width - height/3)/2, height*2/3, paint);
//right
canvas.drawRect((width + height/3)/2, height/3, width , height*2/3, paint);
//bottom
canvas.drawRect(0, height*2/3, width, height, paint);
}
5. 截取图片
/*获取矩形区域内的截图*/
private Bitmap getBitmap()
{
getBarHeight();
Bitmap screenShoot = takeScreenShot();
clipview = (ClipView)this.findViewById(R.id.clipview);
int width = clipview.getWidth();
int height = clipview.getHeight();
Bitmap finalBitmap = Bitmap.createBitmap(screenShoot,
(width - height / 3) / 2, height / 3 + titleBarHeight + statusBarHeight, height / 3, height / 3);
return finalBitmap;
}
这些就是技术点了。其他的没有什么的。
重要的是想法。
源代码怎么添加??郁闷了。。。