该文章同步发布到简书,转载请注明出处
这篇博客应该算是博主真正意义上的第一篇自定义控件的博客,所以写出这个控件之后第一时间进行记录,废话不多说,先上效果图:
这个图在我CSDN博客的上一篇文章中已经上过了的,在上篇文章中就说明要做出这个效果。
自定义控件无非就是那几个步骤:
1. onMeasure
2. onLayout(ViewGroup中会重写,这里直接集成View,所以不会重写)
3. onDraw(所有自定义View的重要步骤)
现在根据上面的几个步骤简要说明一下:
首先,看下属性:
然后是控件的构造方法以及初始化操作和自定义属性的取值:
自定义属性在这:
然后在是重点步骤————onMeasure
onLayout这里就不需要重写了,所以直接来到onDraw,直接上代码
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//先画两个外圆
mPaint.setStrokeWidth(1);
mPaint.setColor(Color.BLUE);
canvas.drawCircle(mWidth/2, mHeight/2, wRadius, mPaint);
canvas.drawCircle(mWidth/2, mHeight/2, nRadius, mPaint);
//背景图片
Bitmap bgMap = BitmapFactory.decodeResource(getResources(), mapBg);
float scaleWidth = (float) (nRadius*2 - 80)/bgMap.getWidth();
float scaleHeight = (float) (nRadius*2 - 50)/bgMap.getHeight();
//缩放图片
Matrix mMatrix = new Matrix();
mMatrix.postScale(scaleWidth, scaleHeight);
Bitmap bgNew = Bitmap.createBitmap(bgMap, 0,0, bgMap.getWidth(), bgMap.getHeight(), mMatrix, true);
canvas.drawBitmap(bgNew, mWidth/2 - bgNew.getWidth()/2 , mHeight/2 - bgNew.getHeight()/2 , mPaint);
//缩放扫描的背景图片
Matrix scanMa = new Matrix();
Bitmap scaningMap = BitmapFactory.decodeResource(getResources(), mapScaning);
scanMa.postScale(0.8f, 0.8f);
Bitmap newScan = Bitmap.createBitmap(scaningMap,0,0,scaningMap.getWidth(),scaningMap.getHeight(),scanMa, true);`
//滚动圆滚动的矩形
mPaint.setStrokeWidth(gWidth);
loadingRectF = new RectF(mWidth/2 - gRadius, mWidth/2 -gRadius,
mWidth/2 +gRadius, mWidth/2 + gRadius);
//扫描bitmap
if(!isFirst){
isFirst = true;
scanRect = new Rect(mWidth/2 - gRadius + 20, mWidth/2 - gRadius + 20,
mWidth/2 +gRadius - 20, mWidth/2 + gRadius - 20);
}
//开始扫描
if(isStart && !isEnd){
canvas.drawBitmap(newScan, mWidth/2 - newScan.getWidth()/2, mHeight/2 - newScan.getHeight()/2, mPaint);
mPaint.setColor(Color.RED);
//画三个滚动的圆弧
canvas.drawArc(loadingRectF, topDegree, arc, false, mPaint);
canvas.drawArc(loadingRectF, bottomDegree, arc, false, mPaint);
canvas.drawArc(loadingRectF, thirdDegree, arc, false, mPaint);
mPaint.setColor(Color.GRAY);
//画扫描线 -- 通过修改top值来实现一直往下扫描效果
canvas.drawRect(scanRect.left, scanRect.top, scanRect.right, scanRect.top + 1, mPaint);
scanRect.top += scanDis;
if(scanRect.top >= scanRect.bottom){
scanRect.top = (int) loadingRectF.top + 20;
}
//圆弧滚动 -- 通过修改圆弧的初始值来实现滚动
startRotating();
}else{//结束扫描 完成扫描
Bitmap downMap = BitmapFactory.decodeResource(getResources(), mapDown);
Matrix downMatrix = new Matrix();
downMatrix.postScale(2.0f, 2.0f);
Bitmap newDownMap = Bitmap.createBitmap(downMap, 0,0, downMap.getWidth(), downMap.getHeight(),
downMatrix, true);
canvas.drawBitmap(newDownMap, mWidth/2 - newDownMap.getWidth()/2, mHeight/2 - newDownMap.getHeight()/2, mPaint);
}
}
代码里面都注释的很清楚了,我想不需要另外在说明了。还有几个方法就是圆弧滚动的实现以及开始扫描和完成扫描
最后,通过调用startScan方法即可执行扫描,调用stopScan完成扫描。
PS:最后说明一句,由于开始扫描和完成扫描没有实现动画效果感觉有点突兀,希望懂的朋友可以指点或者帮忙实现下也是可以滴,哈哈···