微信等头像截取的实现

逛论坛看到别人有这个需求,自己也是打酱油,就写了一把。

界面如下:

主要有一个半透明的矩形框,用作截取区域。一个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;
}

这些就是技术点了。其他的没有什么的。

重要的是想法。

源代码怎么添加??郁闷了。。。

 

转载于:https://my.oschina.net/lifj/blog/68688

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值