将头图片变成圆形简单实现
package com.loaderman.customviewdemo; import android.content.Context; import android.graphics.*; import android.util.AttributeSet; import android.view.View; public class AvatorView extends View { private Paint mPaint; private Bitmap mBitmap; private BitmapShader mBitmapShader; public AvatorView(Context context, AttributeSet attrs) throws Exception{ super(context, attrs); mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.avator); mPaint = new Paint(); mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Matrix matrix = new Matrix(); float scale = (float) getWidth()/mBitmap.getWidth(); matrix.setScale(scale,scale); mBitmapShader.setLocalMatrix(matrix);//设置坐标变换矩阵 mPaint.setShader(mBitmapShader); float half = getWidth()/2; canvas.drawCircle(half,half,getWidth()/2,mPaint); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_gravity="center" android:gravity="center" android:background="@android:color/white" > <com.loaderman.customviewdemo.AvatorView android:layout_width="200dp" android:layout_height="200dp" /> </LinearLayout>
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!