安卓实现圆角头像,已封装成工具类,方便使用

来源:互联网 发布:手机号码 java正则式 编辑:程序博客网 时间:2024/05/16 09:55

首先我们来说一下思路:

只需三步:

    在Canvas上画一个以原图的宽或高(最小的那个)为半径的圆

     再通过Paint设置图片相交的属性为SRC_IN,也就是说取两层的交集,并且显示的是上层。

     最后,将原图画在这个圆上。


工具类中,我注释加的很详细,大家应该都能看懂的

接下来,我们来看看这个工具类:

public class CircularHeadUtils {    public static Bitmap toCircularHead(Bitmap bitmap) {        //取得图片的宽高        int width = bitmap.getWidth();        int height = bitmap.getHeight();        //正方形的边长(取宽和高中最短的作边长)        int r = width > height ? height : width;        //构建一个bitmap        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);        //new一个Canvas,在output上画图        Canvas canvas = new Canvas(output);        Paint paint = new Paint();        //正方形        RectF rectF = new RectF(0,0,r,r);        //抗锯齿        paint.setAntiAlias(true);        //画圆角矩形(当x方向和y方向上的长度相等时,就是一个圆)        canvas.drawRoundRect(rectF, r/2, r/2, paint);        //设置当两个图形相交时的模式,为SRC_IN,代表保留相交部分的上层,去掉其余部分        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));        //将图片画在output上        canvas.drawBitmap(bitmap, null, rectF, paint);        return output;    }}

那我们如何使用它呢?

 

Activity中使用工具类创造圆角头像:

        ImageView mHead = (ImageView) findViewById(R.id.iv_head);        Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.head);        mHead.setImageBitmap(CircularHeadUtils.toCircularHead(b));

希望和大家多多交流,共同进步!

0 0
原创粉丝点击