我们要实现的是如下的效果,
1.该view在设置属性之后时候会有数字和圆圈不断增长的效果
2.该view在按下和放开状态下显示不同的样式。
这种效果逻辑上并不复杂,底层灰色圆圈和蓝色扇形圆圈都是用canvas.drawArc()绘制出来的,中间的数字用drawtext绘制,数字不断增长的效果用了继承Animation的动画类;在按下和放开状态下显示不同的样式是重写了View 的setPressed()方法。
先贴出所有代码,再一一解释
import com.jcodecraeer.util.MyUtils; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.Transformation; public class CircleBar extends View { private RectF mColorWheelRectangle = new RectF(); private Paint mDefaultWheelPaint; private Paint mColorWheelPaint; private Paint textPaint; private float mColorWheelRadius; private float circleStrokeWidth; private float pressExtraStrokeWidth; private String mText; private int mCount; private float mSweepAnglePer; private float mSweepAngle; private int mTextSize; BarAnimation anim; public CircleBar(Context context) { super(context); init(null, 0); } public CircleBar(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } public CircleBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs, defStyle); } private void init(AttributeSet attrs, int defStyle) { circleStrokeWidth = MyUtils.dip2px(getContext(), 10); pressExtraStrokeWidth = MyUtils.dip2px(getContext(), 2); mTextSize = MyUtils.dip2px(getContext(), 40); mColorWheelPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mColorWheelPaint.setColor(0xFF29a6f6); mColorWheelPaint.setStyle(Paint.Style.STROKE); mColorWheelPaint.setStrokeWidth(circleStrokeWidth); mDefaultWheelPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mDefaultWheelPaint.setColor(0xFFeeefef); mDefaultWheelPaint.setStyle(Paint.Style.STROKE); mDefaultWheelPaint.setStrokeWidth(circleStrokeWidth); textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.LINEAR_TEXT_FLAG); textPaint.setColor(0xFF333333); textPaint.setStyle(Style.FILL_AND_STROKE); textPaint.setTextAlign(Align.LEFT); textPaint.setTextSize(mTextSize); mText = "0"; mSweepAngle = 0; anim = new BarAnimation(); anim.setDuration(2000); } @Override protected void onDraw(Canvas canvas) { canvas.drawArc(mColorWheelRectangle, -90, 360, false, mDefaultWheelPaint); canvas.drawArc(mColorWheelRectangle, -90, mSweepAnglePer, false, mColorWheelPaint); Rect bounds = new Rect(); String textstr=mCount+""; textPaint.getTextBounds(textstr, 0, textstr.length(), bounds); canvas.drawText( textstr+""