Android实现头像圆角

Posted 谜语+

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android实现头像圆角相关的知识,希望对你有一定的参考价值。

先看一下效果图

 

首先在res->values下新建一个xml命名为attrs

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="RoundImageView">
        <attr name="type" format="enum">
            <enum name="circle" value="1"/>
            <enum name="round" value="2"/>
        </attr>
        <attr name="radius" format="dimension"/>
    </declare-styleable>
</resources>

 

然后建一个java类,命名 RoundImageView

  1 package com.example.logintest.circleImage;
  2 
  3 import android.annotation.SuppressLint;
  4 import android.content.Context;
  5 import android.content.res.TypedArray;
  6 import android.graphics.Bitmap;
  7 import android.graphics.BitmapShader;
  8 import android.graphics.Canvas;
  9 import android.graphics.Matrix;
 10 import android.graphics.Paint;
 11 import android.graphics.RectF;
 12 import android.graphics.Shader;
 13 import android.graphics.drawable.Drawable;
 14 import android.os.Build;
 15 import android.util.AttributeSet;
 16 import android.util.TypedValue;
 17 import android.widget.ImageView;
 18 import com.example.logintest.R;
 19 
 20 
 21 /**
 22  * Created by leo on 17/3/14.
 23  */
 24 
 25 public class RoundImageView extends androidx.appcompat.widget.AppCompatImageView {
 26     /**
 27      * 圆形模式
 28      */
 29     private static final int MODE_CIRCLE = 1;
 30     /**
 31      * 普通模式
 32      */
 33     private static final int MODE_NONE = 0;
 34     /**
 35      * 圆角模式
 36      */
 37     private static final int MODE_ROUND = 2;
 38     private Paint mPaint;
 39     private int currMode = 0;
 40     /**
 41      * 圆角半径
 42      */
 43     private int currRound = dp2px(10);
 44 
 45     public RoundImageView(Context context) {
 46         super(context);
 47         initViews();
 48     }
 49 
 50     public RoundImageView(Context context, AttributeSet attrs) {
 51         this(context, attrs, 0);
 52     }
 53 
 54     public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
 55         super(context, attrs, defStyleAttr);
 56         obtainStyledAttrs(context, attrs, defStyleAttr);
 57         initViews();
 58     }
 59 
 60     private void obtainStyledAttrs(Context context, AttributeSet attrs, int defStyleAttr) {
 61         TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView, defStyleAttr, 0);
 62         currMode = a.hasValue(R.styleable.RoundImageView_type) ? a.getInt(R.styleable.RoundImageView_type, MODE_NONE) : MODE_NONE;
 63         currRound = a.hasValue(R.styleable.RoundImageView_radius) ? a.getDimensionPixelSize(R.styleable.RoundImageView_radius, currRound) : currRound;
 64         a.recycle();
 65     }
 66 
 67     private void initViews() {
 68         mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
 69     }
 70 
 71     @Override
 72     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
 73         /**
 74          * 当模式为圆形模式的时候,我们强制让宽高一致
 75          */
 76         if (currMode == MODE_CIRCLE) {
 77             super.onMeasure(widthMeasureSpec, heightMeasureSpec);
 78             int result = Math.min(getMeasuredHeight(), getMeasuredWidth());
 79             setMeasuredDimension(result, result);
 80         } else {
 81             super.onMeasure(widthMeasureSpec, heightMeasureSpec);
 82         }
 83     }
 84 
 85     @SuppressLint("DrawAllocation")
 86     @Override
 87     protected void onDraw(Canvas canvas) {
 88         Drawable mDrawable = getDrawable();
 89         Matrix mDrawMatrix = getImageMatrix();
 90         if (mDrawable == null) {
 91             return; // couldn\'t resolve the URI
 92         }
 93 
 94         if (mDrawable.getIntrinsicWidth() == 0 || mDrawable.getIntrinsicHeight() == 0) {
 95             return;     // nothing to draw (empty bounds)
 96         }
 97 
 98         if (mDrawMatrix == null && getPaddingTop() == 0 && getPaddingLeft() == 0) {
 99             mDrawable.draw(canvas);
100         } else {
101             final int saveCount = canvas.getSaveCount();
102             canvas.save();
103 
104             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
105                 if (getCropToPadding()) {
106                     final int scrollX = getScrollX();
107                     final int scrollY = getScrollY();
108                     canvas.clipRect(scrollX + getPaddingLeft(), scrollY + getPaddingTop(),
109                             scrollX + getRight() - getLeft() - getPaddingRight(),
110                             scrollY + getBottom() - getTop() - getPaddingBottom());
111                 }
112             }
113             canvas.translate(getPaddingLeft(), getPaddingTop());
114             if (currMode == MODE_CIRCLE) {//当为圆形模式的时候
115                 Bitmap bitmap = drawable2Bitmap(mDrawable);
116                 mPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
117                 canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, mPaint);
118             } else if (currMode == MODE_ROUND) {//当为圆角模式的时候
119                 Bitmap bitmap = drawable2Bitmap(mDrawable);
120                 mPaint.setShader(new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
121                 canvas.drawRoundRect(new RectF(getPaddingLeft(), getPaddingTop(), getWidth() - getPaddingRight(), getHeight() - getPaddingBottom()),
122                         currRound, currRound, mPaint);
123             } else {
124                 if (mDrawMatrix != null) {
125                     canvas.concat(mDrawMatrix);
126                 }
127                 mDrawable.draw(canvas);
128             }
129             canvas.restoreToCount(saveCount);
130         }
131     }
132 
133     /**
134      * drawable转换成bitmap
135      */
136     private Bitmap drawable2Bitmap(Drawable drawable) {
137         if (drawable == null) {
138             return null;
139         }
140         Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
141         Canvas canvas = new Canvas(bitmap);
142         //根据传递的scaletype获取matrix对象,设置给bitmap
143         Matrix matrix = getImageMatrix();
144         if (matrix != null) {
145             canvas.concat(matrix);
146         }
147         drawable.draw(canvas);
148         return bitmap;
149     }
150 
151     private int dp2px(float value) {
152         return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value, getResources().getDisplayMetrics());
153     }
154 }
View Code

这是一个自定义的ImageView

 

然后就是页面布居中的引用了

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@color/threefragment_color"
android:id="@+id/person">
<com.example.logintest.circleImage.RoundImageView
    android:id="@+id/img_tx"
    android:layout_width="100dp"
    android:layout_height="100dp"
    app:type="circle"
    android:src="@drawable/touxiang"
    android:layout_marginTop="30dp"
    android:layout_centerHorizontal="true"
    />

</RelativeLayout>

 

参考博客链接 

以上是关于Android实现头像圆角的主要内容,如果未能解决你的问题,请参考以下文章

iOS之设置用户头像的圆角

Android 功能系列篇

Qt 圆角头像的实现

登录圆形头像之网络加载与缓存到本地

Android 添加GridView中图片的圆角样式

#yyds干货盘点#CSS实现随机不规则圆角头像