标准自定义控件CirvleView

本文介绍如何创建自定义的CircleView控件,通过继承View并实现圆的绘制。文章详细解释了自定义属性CircleColor的使用,以及onMeasure和onDraw方法的重写过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.写一个类继承View

2.自定义属性CircleColor

3.重写onMeasure方法

4.重写onDraw方法


<?xml version=“1.0” encoding=“utf-8”?>

<resources>

<declare-styleable name=”CircleView”>

<attr name="circle_color" format="color"/>

</declare-styleable>

</resources>



public class CircleView extends View {

private int mColor =Color.RED;

private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

public CircleView (Context context, AttributeSet attrs){

this(context,attrs,0)

public CircleView(Context context ,AttrbuteSet attrs, int deStyeAttr){

super (context,attrs,deStyleAttr);

TypedArray a= context.obtainStyledAttributes(attrs,R.styleable.CircleView);

mColor=a.getColor(R.styleable.CircleView_circle_color,Color.RED);

a.recycle();

init();

}

private void init(){

mPaint.setColor(mColor);

}

@override

protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec){

super.onMeasure(widthMeasureSpec,heightMeasureSpec);

int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);

int widthSpecSize =MeasureSpec.getSize(withMeasureSpec);

int heightSpecMode =MeasureSpec.getMode(heightMeasureSpec);

int heightSpecSize=MeasureSpec.getSize(heightMeasureSpec);

if(widthSpecMode==MeasureSpec.AT_MOST&&heightSpecMode ==MeasureSpec.AT_MOST){

setMeasuredDimension(200,200);

}else if(withSpecMode==MeasureSpec.AT_MOST)[

setMeasuredDimension(200,heightSpecSize);

} else if(heightMeasureMode == MeasureSpec.AT_MOST){

setMeasuredDimension(widthSpecSize,200);

}

}

@overtide

protected void onDraw (Canvas canvas){

super.onDraw(canvas);

final int paddingLeft =getPaddingLeft();

final int paddingRight=getPaddingRight();

final int paddingTop=getPaddingTop();

final int paddingBottom =getPaddingBottom();

int width =getWidth()-paddingLeft- paddingRight;

int height=getHeight()-paddingTop-paddingBottom;

int radius = Math.min(width,height)/2;

canvas.drawCircle(paddingLeft+width/2,paddingTop+height/2,radius,mPaint);

}


}


}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值