Android裁剪图片为圆形图片的实现原理与代码

所属分类: 软件编程 / Android 阅读数: 1873
收藏 0 赞 0 分享
以前在eoe论坛中找过裁剪图片为圆形图片的方法,但是效果都不是很理想,这几天因为公司业务的要求,需要对头像进行裁剪以圆形的方式显示,这个方法是根据传入的图片的高度(height)和宽度(width)决定的,如果是 width <= height时,则会裁剪高度,裁剪的区域是宽度不变高度从顶部到宽度width的长度;如果 width > height,则会裁剪宽度,裁剪的区域是高度不变,宽度是取的图片宽度的中心区域,不过不同的业务需求,对裁剪图片要求不一样,可以根据业务的需求来调整裁剪的区域。

好了,不多说了,直接上代码
复制代码 代码如下:

/**
* 转换图片成圆形
* @param bitmap 传入Bitmap对象
* @return
*/
public Bitmap toRoundBitmap(Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float roundPx;
float left,top,right,bottom,dst_left,dst_top,dst_right,dst_bottom;
if (width <= height) {
roundPx = width / 2;
top = 0;
bottom = width;
left = 0;
right = width;
height = width;
dst_left = 0;
dst_top = 0;
dst_right = width;
dst_bottom = width;
} else {
roundPx = height / 2;
float clip = (width - height) / 2;
left = clip;
right = width - clip;
top = 0;
bottom = height;
width = height;
dst_left = 0;
dst_top = 0;
dst_right = height;
dst_bottom = height;
}
Bitmap output = Bitmap.createBitmap(width,
height, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect src = new Rect((int)left, (int)top, (int)right, (int)bottom);
final Rect dst = new Rect((int)dst_left, (int)dst_top, (int)dst_right, (int)dst_bottom);
final RectF rectF = new RectF(dst);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, src, dst, paint);
return output;
}
更多精彩内容其他人还在看

android byte[] 和short[]转换的方法代码

这篇文章主要介绍了android byte[] 和short[]转换的方法代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

Android获取应用程序大小的方法

这篇文章主要介绍了Android获取应用程序大小的方法,有需要的朋友可以参考一下
收藏 0 赞 0 分享

Android获取其他包的Context实例代码

这篇文章主要介绍了Android获取其他包的Context实例代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

Android放大镜的实现代码

这篇文章主要介绍了Android放大镜的实现代码,有需要的朋友可以参考一下
收藏 0 赞 0 分享

Android 读取Properties配置文件的小例子

这篇文章主要介绍了Android 读取Properties配置文件的小例子,有需要的朋友可以参考一下
收藏 0 赞 0 分享

Android通讯录开发之删除功能的实现方法

这篇文章主要介绍了Android通讯录开发之删除功能的实现方法,有需要的朋友可以参考一下
收藏 0 赞 0 分享

使用ViewPager实现android软件使用向导功能实现步骤

现在的大部分android软件,都是使用说明,就是第一次使用该软件时,会出现向导,可以左右滑动,然后就进入应用的主界面了,下面我们就实现这个功能
收藏 0 赞 0 分享

android在异步任务中关闭Cursor的代码方法

android在异步任务中如何关闭Cursor?在我们开发应用的时候,很多时候会遇到这种问题,下面我们就看看代码如何实现
收藏 0 赞 0 分享

Android自定义桌面功能代码实现

android自定义桌面其实很简单,看一个例子就明白了
收藏 0 赞 0 分享

android将图片转换存到数据库再从数据库读取转换成图片实现代码

有时候我们想把图片存入到数据库中,尽管这不是一种明智的选择,但有时候还是不得以会用到,下面说说将图片转换成byte[]数组存入到数据库中去,并从数据库中取出来转换成图像显示出来
收藏 0 赞 0 分享
查看更多