Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自訂 View:繼承 TextView 自繪背景教學

編輯:關於 Android 程式設計

本文將示範如何透過繼承 TextView 並自訂 onDraw 方法,繪製出具有雙層邊框效果的背景,供需要的朋友參考。

效果預覽:

實作流程:

1. 初始化:設定畫筆

 mPaintIn = new Paint(); mPaintIn.setAntiAlias(true); mPaintIn.setDither(true); mPaintIn.setStyle(Paint.Style.FILL); mPaintIn.setColor(getResources().getColor(R.color.colorPrimary)); mPaintOut = new Paint(); mPaintOut.setAntiAlias(true); mPaintOut.setDither(true); mPaintOut.setStyle(Paint.Style.FILL); mPaintOut.setColor(getResources().getColor(R.color.colorAccent)); 

2. 繪製外框、內框與文字

取得元件的寬高

 int width = getMeasureWidth(); int height = getMeasureHeight(); 

進行繪製

 @Override protected void onDraw(Canvas canvas) { //繪制背景,在繪制文字之前繪制 canvas.drawRect(new Rect(0, 0, getMeasuredWidth(), getMeasuredHeight()), mPaintIn); canvas.drawRect(new Rect(10, 10, getMeasuredWidth()-10, getMeasuredHeight()-10), mPaintOut); super.onDraw(canvas); } 

以上就是本文的全部內容,希望對大家學習 Android 自訂元件有所幫助,也歡迎多多支持本站。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved