public class CornerImageview extends AppCompatImageView { int width=0; int height=0; int topLeft=0; int topRight=0; int bottomLeft=0; int bottomRight=0; boolean isCircle=false; public CornerImageview(Context context) { super(context); } public CornerImageview(Context context, AttributeSet attrs) {//将各种dp大小转化为px大小,不然大小是对不上的 super(context, attrs); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CornerImageview); topLeft=DensityUtil.dip2px(context,ta.getInteger(R.styleable.CornerImageview_topLeft,0)); topRight=DensityUtil.dip2px(context,ta.getInteger(R.styleable.CornerImageview_topRight,0)); bottomLeft=DensityUtil.dip2px(context,ta.getInteger(R.styleable.CornerImageview_bottomLeft,0)); bottomRight=DensityUtil.dip2px(context,ta.getInteger(R.styleable.CornerImageview_bottomRight,0)); isCircle=ta.getBoolean(R.styleable.CornerImageview_isCircle,false); } public CornerImageview(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) {//获取view大小 super.onLayout(changed, left, top, right, bottom); width = getWidth(); height = getHeight(); } @Override protected void onDraw(Canvas canvas) { Path path = new Path(); if (!isCircle){//按照用户设置的圆角大小切割 path.moveTo(topLeft, 0); path.lineTo(width - topRight, 0); path.quadTo(width, 0, width, topRight); path.lineTo(width, height - bottomRight); path.quadTo(width, height, width - bottomRight, height); path.lineTo(bottomLeft, height); path.quadTo(0, height, 0, height - bottomLeft); path.lineTo(0, topLeft); path.quadTo(0, 0, topLeft, 0); canvas.clipPath(path); }else {//如果属性为原型,则原型切割 path.addCircle(width/2,height/2,width/2, Path.Direction.CCW); canvas.clipPath(path); } super.onDraw(canvas); } }
之后找到attrs.xml文件,如果没有则创建一个,添加以下代码
<declare-styleable name="CornerImageview"> <attr name="topLeft" format="integer" /> <attr name="topRight" format="integer" /> <attr name="bottomLeft" format="integer"/> <attr name="bottomRight" format="integer"/> <attr name="isCircle" format="boolean"/> </declare-styleable>
在xml布局文件中的用法
圆形时:
<com.example.orphanhelp.view.CornerImageview android:src="@drawable/hand" android:layout_gravity="center_vertical" app:isCircle="true" android:layout_centerVertical="true" android:layout_width="20dp" android:layout_height="20dp"/>
圆角时:
<com.example.orphanhelp.view.CornerImageview android:id="@+id/im_yjfk" android:src="@drawable/hand" android:layout_gravity="center_vertical" app:topRight="20" android:layout_centerVertical="true" android:layout_width="20dp" android:layout_height="20dp"/>
只需要填数字即可 topright topleft bottomright bottomleft则控制四个角的圆角大小