简单的圆角ImageView的方法
李国帅
在android开发中,圆角ImageView比较常见,实现方法也有那么几种,不过比较简单的还是重载的方法,实现起来也比较简单。下面献丑总结一下。
创建重载类
package com.lgs7907.widget;
import com.lgs7907.R;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundImageView extends ImageView {
float radius = 180.0f;//20.0f;// 画出圆角效果,圆角(180度为正圆)
public RoundImageView(Context context) {
super(context);
}
public RoundImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
//super(context, attrs);
}
public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
//获取圆角半径的大小
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView);
radius = a.getInt(R.styleable.RoundImageView_radius,180);
a.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
Path clipPath = new Path();
int w = this.getWidth();
int h = this.getHeight();
//向路径中添加圆角矩形,Path.Direction.CW表示顺时针方向
clipPath.addRoundRect(new RectF(0, 0, w, h), radius, radius, Path.Direction.CW);
canvas.clipPath(clipPath);
super.onDraw(canvas);//修改画板
}
}
添加圆角ImageView的自定义属性
实现自定义圆角的大小
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RoundImageView">
<attr name="radius" format="integer" />
</declare-styleable>
</resources>
在界面中添加ImageView
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:widget="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
tools:context="${relativePackage}.${activityClass}" >
<com.lgs7907.widget.RoundImageView
android:id="@+id/imageView1"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginTop="0dp"
android:scaleType="fitCenter"
android:src="@drawable/u20"
widget:radius="12"/>
加载本项目的自定义属性
xmlns:widget="http://schemas.android.com/apk/res-auto"
添加自定义属性
widget:radius="12"
结束
以上3步即可实现圆角ImageView。