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

Android 圓角圓形圖片(二):讓自訂 ImageView 支援完整 scaleType

編輯:關於 Android 程式設計

問題現象

自訂圓角或圓形 ImageView 時,若直接在 onDraw 中畫 Bitmap,會發現只有 fitXY 能正常填滿,其他 scaleType 都會像 matrix 一樣從左上角開始顯示。

ImageView 的 scaleType

ImageView 的 scaleType 包含 matrix、center、centerCrop、centerInside、fitCenter、fitEnd、fitStart、fitXY。fitXY 會直接拉伸圖片填滿檢視;其他模式通常需要計算縮放與位移。

源碼中的縮放邏輯

ImageView 會在 configureBounds 中依 scaleType 建立 mDrawMatrix,再在 onDraw 中透過 canvas.concat 套用。若自訂 View 重寫 onDraw,卻沒有處理 Matrix,圖片就會失去縮放行為。

修正方式

可在自訂 View 中複製 configureBounds 的概念:先取得圖片寬高與檢視寬高,再依 scaleType 計算 Matrix。fitXY 可直接設定 bounds;centerCrop、centerInside 等則需計算 scale 與 translate。

若需要 ImageView 內部的 scaleTypeToScaleToFit 方法,可透過反射取得。完成後,再將 Matrix 套用到畫布,即可讓圓角圖片支援完整 scaleType。

GitHub 位址:https://github.com/913453448/CircleViewDemo

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