自定义ImageView实现圆形图片,主要是在onDraw()方法中实现绘制圆形图片,在onMeasure()中测量圆形的半径并设置View的宽高。效果如下图
代码如下
public class CircleImageView extends ImageView {
//画笔 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(); Drawable drawable = getDrawable(); if (null != drawable) {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap(); //初始化BitmapShader,传入bitmap对象 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); } else {
super.onDraw(canvas); }
}
}
自定义好之后,就可以直接在xml布局中使用该控件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" tools:context="com.sun.zh.bezier.MainActivity"> <com.sun.zh.bezier.view.CircleImageView android:id="@+id/image" android:layout_width="200dp" android:layout_height="200dp" android:scaleType="centerCrop" android:src="@drawable/ic_timg" /> </RelativeLayout>
注意必须设置src图,设置background图不会出现圆形效果
在ImageView中src与background的区别:
background会根据ImageView组件给定的长宽进行拉伸,而src就存放的是原图的大小,不会进行拉伸。src是图片内容(前景),bg是背景,可以同时使用。此外scaleType只是对src起作用,bg可设置透明度。在动态加载图片中设置src可使用image.setImageResource(R.drawable.**)。