自定義view實現圓中心顯示文字
阿新 • • 發佈:2018-11-10
自定義view實現:畫一個矩形 然後畫一個圓 再在圓中心顯示文字,效果如下
RectF rect = new RectF(100,100,500,500);//畫一個矩形 Paint mPaint = new Paint(); mPaint.setColor(Color.GRAY); mPaint.setStyle(Paint.Style.FILL); canvas.drawRect(rect, mPaint); //設定畫筆的樣式,空心STROKE mPaint.setStyle(Paint.Style.FILL); //設定抗鋸齒 mPaint.setAntiAlias(true); mPaint.setColor(Color.RED); canvas.drawCircle(rect.centerX(),rect.centerY(),150,mPaint); mPaint.setColor(Color.WHITE); mPaint.setTextSize(50); mPaint.setStyle(Paint.Style.FILL); //該方法即為設定基線上那個點究竟是left,center,還是right 這裡我設定為center mPaint.setTextAlign(Paint.Align.CENTER); Paint.FontMetrics fontMetrics = mPaint.getFontMetrics(); float top = fontMetrics.top;//為基線到字型上邊框的距離,即上圖中的top float bottom = fontMetrics.bottom;//為基線到字型下邊框的距離,即上圖中的bottom int baseLineY = (int) (rect.centerY() - top/2 - bottom/2);//基線中間點的y軸計算公式 canvas.drawText("小學",rect.centerX(),baseLineY,mPaint);