kotlin版
androidx.appcompat.widget.AppCompatImageView(context, atts) {
private var paint: Paint? = null
private var mRadius = 0f
private var mScale = 0f
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val size = min(measuredHeight, measuredWidth)
mRadius = (size / 2).toFloat()
setMeasuredDimension(size, size)
}
override fun onDraw(canvas: Canvas?) {
paint = Paint()
val mDrawable = drawable
if (mDrawable != null) {
val bitmap = mDrawable.toBitmap()
// 初始化BitmapShader 傳入bitmap
val bitmapShader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
mScale = (mRadius * 2.0f) / min(bitmap.height, bitmap.width)
val matris = Matrix()
matris.setScale(mScale, mScale)
bitmapShader.setLocalMatrix(matris)
paint?.shader = bitmapShader
canvas?.drawCircle(mRadius, mRadius, mRadius, paint!!)
} else {
super.onDraw(canvas)
}
}
}
java
public class CustomImager extends androidx.appcompat.widget.AppCompatImageView {
public CustomImager(@NonNull Context context) {
super(context);
}
public CustomImager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomImager(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
//畫(huà)筆
private Paint mPaint;
//圓形圖片的半徑
private int mRadius;
//圖片的宿放比例
private float mScale;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//由于是圓形柬甥,寬高應(yīng)保持一致
int size = Math.min(getMeasuredWidth(), getMeasuredHeight());
mRadius = size / 2;
setMeasuredDimension(size, size);
}
@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
mPaint = new Paint();
Drawable drawable = getDrawable();
if (null != drawable) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
//初始化BitmapShader最岗,傳入bitmap對(duì)象
BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
//計(jì)算縮放比例
mScale = (mRadius * 2.0f) / Math.min(bitmap.getHeight(), bitmap.getWidth());
Matrix matrix = new Matrix();
matrix.setScale(mScale, mScale);
bitmapShader.setLocalMatrix(matrix);
mPaint.setShader(bitmapShader);
//畫(huà)圓形,指定好坐標(biāo)硫朦,半徑,畫(huà)筆
canvas.drawCircle(mRadius, mRadius, mRadius, mPaint);
} else {
super.onDraw(canvas);
}
}
}