1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapShader; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Shader; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import androidx.annotation.Nullable; import androidx.appcompat.widget.AppCompatImageView;
public class CircleImageView extends AppCompatImageView {
private Paint mPaint;
private int mRadius;
private float mScale;
public CircleImageView(Context context) { super(context); }
public CircleImageView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); }
public CircleImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); }
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int size = Math.min(getMeasuredWidth(), getMeasuredHeight()); mRadius = size / 2; setMeasuredDimension(size, size); }
@SuppressLint("DrawAllocation") @Override protected void onDraw(Canvas canvas) { mPaint = new Paint(); Bitmap bitmap = drawableToBitmap(getDrawable()); @SuppressLint("DrawAllocation") BitmapShader bitmapShader=new BitmapShader(bitmap, Shader.TileMode.CLAMP,Shader.TileMode.CLAMP);
mScale=(mRadius*2.0f)/Math.min(bitmap.getHeight(),bitmap.getWidth());
Matrix matrix=new Matrix(); matrix.setScale(mScale,mScale); bitmapShader.setLocalMatrix(matrix);
mPaint.setShader(bitmapShader);
canvas.drawCircle(mRadius,mRadius,mRadius,mPaint); }
private Bitmap drawableToBitmap(Drawable drawable) { if (drawable instanceof BitmapDrawable) { BitmapDrawable bd = (BitmapDrawable) drawable; return bd.getBitmap(); } int w = drawable.getIntrinsicWidth(); int h = drawable.getIntrinsicHeight(); Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, w, h); drawable.draw(canvas); return bitmap; } }
|