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

ShapeDrawable 妙用:幾行代碼實現 Android 放大鏡效果

編輯:關於 Android 程式設計

放大鏡效果聽起來複雜,其實抓住兩個點就很簡單:

1. ShapeDrawable 構造時可以指定描繪的形狀(比如 OvalShape 畫圓形);

2. 可以通過 shape.getPaint().setShader() 指定 Shader,而 BitmapShader 能接受一張圖片加一個 Matrix。

把這兩點串起來,問題就解決了:用 Shader 把原圖「平移 + 縮放」到合適位置,再讓 ShapeDrawable 以圓形區域裁剪顯示,就是放大鏡。

float scale = 1.2f;   // 放大倍率

int cx = 224;         // 放大中心 X
int cy = 357;         // 放大中心 Y
int r = 200;          // 鏡片半徑

// 指定形狀創建 ShapeDrawable
ShapeDrawable shape = new ShapeDrawable(new OvalShape());

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.bg1);
BitmapShader bs = new BitmapShader(bm, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);

// 用 Matrix 控制圖形的平移與縮放,區域指定也在這裡完成
Matrix m = new Matrix();
m.setTranslate(r - cx, r - cy);
m.postScale(scale, scale);
bs.setLocalMatrix(m);

// 為 ShapeDrawable 設置 Shader
shape.getPaint().setShader(bs);

// 指定描繪目標位置
shape.setBounds(
    (int) (cx - r * scale), (int) (cy - r * scale),
    (int) (cx + r * scale), (int) (cy + r * scale));

canvas.drawBitmap(bm, 0, 0, null);
shape.draw(canvas);

幾處細節值得留意:

  • Shader.TileMode.CLAMP 表示超出邊界時沿用邊緣像素顏色,不會出現重複平鋪的圖案。
  • setTranslate 與 postScale 的順序會影響最終位置,先平移再縮放與先縮放再平移結果不同,需要按實際效果微調。
  • scale 越大放大倍率越高,同時 setBounds 的範圍也要跟著放大,否則會出現鋸齒或空白。
  • 若要在自定義 View 中持續更新放大區域,只需在 invalidate 時重建 Matrix 並重設 Shader 即可。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved