本文主要是介绍Andorid自定义拖动弧形进度条,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在android自定义控件中,我们使用进度显示,为了好看,一般都不会用系统自带的。原因大家都懂的。而现在各种自定义进度条显示也是层出不穷,在实际开发中遇到的情况是需要带拖动效果的弧形进度条。下面我们先看看这个效果图:
开始自定义之前,我们就要把要用到的东西先定义出来,初始化
//进度边框画笔private Paint bgpaint;//进度底色画笔private Paint colorpaint;//文本画笔private Paint txtpaint;//进度颜色画笔private Paint propaint;//控件中心位置坐标private int cx, cy;//控件宽高private int width, height;//弧形体宽高private int whsize;//判断是否按下private boolean isdown;//分配圆弧数的比例private float angle = 180 / 13;private Paint cicpaint;//当前点private int currentdit;
在构造方法中初始化相关参数
private void init(){bgpaint = new Paint();colorpaint = new Paint();txtpaint = new Paint();propaint = new Paint();cicpaint = new Paint();cicwpaint = new Paint();//抗锯齿bgpaint.setAntiAlias(true);//设置颜色bgpaint.setColor(Color.GREEN);//设置画笔风格 空心bgpaint.setStyle(Paint.Style.STROKE);//画笔宽度bgpaint.setStrokeWidth(35);//设置画笔尾部圆滑bgpaint.setStrokeCap(Paint.Cap.ROUND);colorpaint.setAntiAlias(true);colorpaint.setColor(Color.WHITE);colorpaint.setStyle(Paint.Style.STROKE);colorpaint.setStrokeWidth(33);colorpaint.setStrokeCap(Paint.Cap.ROUND);propaint.setAntiAlias(true);propaint.setColor(Color.GREEN);propaint.setStyle(Paint.Style.STROKE);propaint.setStrokeWidth(33);propaint.setStrokeCap(Paint.Cap.ROUND);txtpaint.setAntiAlias(true);txtpaint.setColor(Color.BLACK);txtpaint.setStyle(Paint.Style.FILL);txtpaint.setStrokeWidth(1);txtpaint.setTextSize(30);cicpaint.setAntiAlias(true);cicpaint.setColor(Color.GREEN);cicpaint.setStyle(Paint.Style.FILL);cicpaint.setStrokeWidth(1);cicpaint.setTextSize(20);cicwpaint.setAntiAlias(true);cicwpaint.setColor(Color.WHITE);cicwpaint.setStyle(Paint.Style.FILL);cicwpaint.setStrokeWidth(1);cicwpaint.setTextSize(20);//保存点的位置point.x = (int) Dp2Px(getContext(), 45);point.y = (int) (whsize - Dp2Px(getContext(), 45));}
将初始化方法,放入构造方法中
public MyView(Context context){super(context);init();}public MyView(Context context, AttributeSet attrs){super(context, attrs);init();}
我们这个自定义控件没有设置自有属性,大家可以自由扩展,好了接下来,就是要获得尺寸。那么有两种方式,一种是在onMeasure()方法中得到控件的宽高。还有就是在onSizeChanged()方法中获得View的高宽。这次我们在onSizeChanged()方法中获得,如果对控件的测量有不熟悉的,可以看看我上一篇blog,android控件测量与布局
onsizechange()方法中怎么获得呢,请看:
@Overrideprotected void onSizeChanged(int w, int h, int oldw, int oldh){width = w;height = h;whsize = w > h ? h : w;cx = width / 2;cy = height / 2;super.onSizeChanged(w, h, oldw, oldh);}
尺寸得到之后,我们就开始显示进度了。当然通过onDraw()方法。分别画进度背景,线条,等
@Overrideprotected void onDraw(Canvas canvas){super.onDraw(canvas);drawarc(canvas);Log.d("renk", "invar");if (isdown){drawmap(canvas);} else{drawbit(canvas);}}
先画,进度背景及边框
private void drawarc(Canvas canvas){RectF oval = new RectF(Dp2Px(getContext(), 45),Dp2Px(getContext(), 45), whsize - Dp2Px(getContext(), 45),whsize - Dp2Px(getContext(), 45));//画圆弧canvas.drawArc(oval, -180, 180, false, bgpaint);canvas.dra
这篇关于Andorid自定义拖动弧形进度条的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!