700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Android自定义控件--仿安全卫士中的一键加速【圆形进度条】

Android自定义控件--仿安全卫士中的一键加速【圆形进度条】

时间:2022-08-21 18:15:05

相关推荐

Android自定义控件--仿安全卫士中的一键加速【圆形进度条】

最近看到a10615的:Android自定义控件–仿安全卫士中的一键加速。自己零零散散学习了几个月,也想尝试下。几天的功夫总算把它弄出来,虽然没有泓洋的强大,但是该有的自定义属性也有了,先来看看效果图。

代码并没有完全抄袭a10615的code,但是参考了它的设计方式,同时也有自己的理解。具体实现请点击:源码下载。

本文记录我碰到的几个难点:

一、小圆的半径计算,先看看a10615画的图。

,在应用直角边计算公式的时候,把角度跟弧度概念搞混了,计算r的时候,竟然用R1*Sin0.9,实际上应该是R1*Sin(3.14*0.9/180)。鄙视我,把高中的数学忘得一干二净。因此计算r的半径代码实现如下:

littleCircleRadius = (float)(Math.sin(3.14*0.9/180)*bigCircleRadius/(1+Math.sin(3.14*0.9/180)));

其中角度换弧度也可以用Math的库函数toRadians。即如下计算是最准的。

littleCircleRadius = (float)(Math.sin(Math.toRadians(0.9))*bigCircleRadius/(1+Math.sin(Math.toRadians(0.9))));

二、paint.measureText与paint.getTextBounds的区别,参考:Android Paint: .measureText() vs .getTextBounds()。重点是下面这张图片:

三、控件内字体居中绘制,baseline的计算,我的计算方法与a10615不太一样,我的公式:

控件的Y坐标值 + 控件的高度/2 - (fontMetrics.descent - fontMetrics.ascent)/2 - fontMetrics.ascent

比如计算button中文字的baseline的代码实现如下:

float strY = top + buttonHeight/2 - (fontMetrics.descent - fontMetrics.ascent)/2 - fontMetrics.ascent;

四、要保持自定view的宽高更具需求来设置,需要重写onMeasure方法。我是这么简单理解:layout设为match_parent时,mode为EXACTLY;为wrap_content或自定义长高时,mode为AT_MOST。具体参考:android中onMeasure初看,深入理解布局之一

@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {int desiredWidth = (int)bigCircleRadius*2;int desiredHeight = (int)bigCircleRadius*2;int widthMode = MeasureSpec.getMode(widthMeasureSpec);int widthSize = MeasureSpec.getSize(widthMeasureSpec);int heightMode = MeasureSpec.getMode(heightMeasureSpec);int heightSize = MeasureSpec.getSize(heightMeasureSpec);int width;int height;if (widthMode == MeasureSpec.EXACTLY) {width = widthSize;} else if (widthMode == MeasureSpec.AT_MOST) {width = Math.min(desiredWidth, widthSize);} else {width = desiredWidth;}if (heightMode == MeasureSpec.EXACTLY) {height = heightSize;} else if (heightMode == MeasureSpec.AT_MOST) {height = Math.min(desiredHeight, heightSize);} else {height = desiredHeight;}setMeasuredDimension(width, height);}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。