上一次讲了简单的自定义View,大家肯定喷我,这尼玛自定义有毛意思!好,那我就来个有点意思的,意思一下。
菊花在植物分类学中是菊科、菊属的多年生宿根草本植物,根据经典的记载,中国栽培菊花历史已有3000多年...额,偏题了。。。
以上是效果,不知道怎么搞成gif,就截了个图,感兴趣的继续往下看。。
整个步骤和自定义View(基础)一致,不了解的可以去看看。
balabalabala一堆代码。。。
public class ProgressBar extends View { /** * 第一圈的颜色 */ private int mFirstColor; /** * 第二圈的颜色 */ private int mSecondColor; /** * 圈的宽度 */ private int mCircleWidth; /** * 当前进度 */ private int mProgress; /** * 速度 */ private int mSpeed; /** * 画笔 */ private Paint mPaint; //中间文字区域 private Rect mBound; public ProgressBar(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ProgressBar(Context context) { this(context, null); } public ProgressBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.customProgress, defStyle, 0); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.customProgress_firstColor: mFirstColor = a.getColor(attr, Color.GREEN); break; case R.styleable.customProgress_secondColor: mSecondColor = a.getColor(attr, Color.RED); break; case R.styleable.customProgress_circleWidth: mCircleWidth = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_PX, 20, getResources().getDisplayMetrics())); break; case R.styleable.customProgress_speed: mSpeed = a.getInt(attr, 1000);// 默认1000 break; } } a.recycle(); mPaint = new Paint(); //绘图 new Thread() { @Override public void run() { super.run(); while (true) { if(mProgress>=360){ return; } mProgress++; postInvalidate();//会触发调用onDraw方法 try { Thread.sleep(mSpeed); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } @Override protected void onDraw(Canvas canvas) { int centre = getWidth() / 2; // 获取圆心的x坐标 int radius = centre - mCircleWidth / 2;// 半径 mPaint.setStrokeWidth(mCircleWidth); // 设置圆环的宽度 mPaint.setAntiAlias(true); // 消除锯齿 mPaint.setStyle(Paint.Style.STROKE); // 设置空心 mPaint.setColor(mFirstColor); // 设置圆环的颜色 canvas.drawCircle(centre,centre,radius,mPaint); RectF oval = new RectF(centre - radius, centre - radius, centre + radius, centre + radius); // 用于定义的圆弧的形状和大小的界限 mPaint.setColor(mSecondColor); // 设置圆环的颜色 canvas.drawArc(oval, -90, mProgress, false, mPaint); // 根据进度画圆弧 //中间文字 mPaint.reset(); mBound = new Rect();//字体区域 String per=(int)(mProgress/3.6)+"%"; mPaint.setColor(Color.DKGRAY); mPaint.setTextSize(100); mPaint.getTextBounds(per, 0, per.length(), mBound); canvas.drawText(per, getWidth() / 2- mBound.width()/2, getHeight() / 2+ mBound.height()/2, mPaint); } } 自定义属性和布局就不展示了。下一节深入了解
