該文章同步發佈到簡書,轉載請註明出處
這篇博客應該算是博主真正意義上的第一篇自定義控件的博客,所以寫出這個控件之後第一時間進行記錄,廢話不多說,先上效果圖:
這個圖在我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:最後說明一句,由於開始掃描和完成掃描沒有實現動畫效果感覺有點突兀,希望懂的朋友可以指點或者幫忙實現下也是可以滴,哈哈···