1. 程式人生 > >自定義view

自定義view

width als tint war 樣式 attr 寬度 rectf declare

1:四個構造方法,其中有一個參數,兩個參數,三個參數,四個參數;

2:四個方法:1:onMeasuer()測量高度,2:onDraw()繪制需要一個畫筆panit3:onLayout()定位,定位視圖的位置,4:onTouchEvent()監聽事件

3:首先要學會畫圓

下面是一些代碼

<declare-styleable name="circleView"> <attr name="textSize" format="dimension" /> <attr name="text" format="string" /> <attr name="circleColor" format="color" /> <attr name="arcColor" format="color" /> <attr name="textColor" format="color" /> <attr name="startAngle" format="integer" /> <attr name="sweepAngle" format="integer" /> </declare-styleable>
技術分享   Ⅰ、textSize——對應中間文本文字的大小   Ⅱ、text——對應中間文本   Ⅲ、circleColor——對應內圓的顏色   Ⅳ、arcColor——對應外環的顏色   Ⅴ、textColor——對應文本的顏色   Ⅵ、startAngle——對應外環的起始角度   Ⅶ、sweepAngle——對應外環掃描角度   緊接著,就是在自定義控件的初始化方法中來獲取這些自定義屬性: 技術分享 TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.circleView); if (ta != null) { circleColor = ta.getColor(R.styleable.circleView_circleColor, 0); arcColor = ta.getColor(R.styleable.circleView_arcColor, 0); textColor = ta.getColor(R.styleable.circleView_textColor, 0); textSize = ta.getDimension(R.styleable.circleView_textSize, 50); text = ta.getString(R.styleable.circleView_text); startAngle = ta.getInt(R.styleable.circleView_startAngle, 0); sweepAngle = ta.getInt(R.styleable.circleView_sweepAngle, 90); ta.recycle(); }
技術分享   這裏在多說一嘴子,為了釋放更多的資源,一定要將TypedArray這個對象進行資源的釋放。   接下來,在OnMeasure()方法中,初始化要繪制畫筆樣式,獲取屏幕的寬度,計算中間位置的坐標,以及指定外接矩形的寬高代碼如下: 技術分享 private void init() { int length = Math.min(width, height); mCircleXY = length / 2; mRadius = length * 0.5f / 2; mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG); mCirclePaint.setColor(circleColor); mRectF = new RectF(length * 0.1f, length * 0.1f, length * 0.9f, length * 0.9f); mArcPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mArcPaint.setColor(arcColor); mArcPaint.setStyle(Paint.Style.STROKE); mArcPaint.setStrokeWidth((width * 0.1f)); mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mTextPaint.setTextSize(textSize); mTextPaint.setColor(textColor); mTextPaint.setTextAlign(Align.CENTER); }
技術分享   將我們設置的自定義屬性,設置給不同筆刷。   做了這麽多準備以後,我們所需的就是在OnDraw方法中繪制內圓、外環與文字。代碼如下: 技術分享 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); drawSth(canvas); } private void drawSth(Canvas canvas) { canvas.drawCircle(mCircleXY, mCircleXY, mRadius, mCirclePaint); canvas.drawArc(mRectF, startAngle, sweepAngle, false, mArcPaint); canvas.drawText(text, 0, text.length(), mCircleXY, mCircleXY + textSize / 4, mTextPaint); }

自定義view